Use this simple code to capture using the device camera
IMP Note: Add those permision to the mainfest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
The mainActivity
public class MainActivity extends Activity {
private static final int CAMERA_PIC_REQUEST = 1111;//Constant ID for ActivityResult
private ImageView mImage; // To display the thumbnail
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImage = (ImageView) findViewById(R.id.camera_image);
// Start an intent for Camera Capture with ResultActivity
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST) {
// Get the image in a Bitmap extension to assign it to the ImageView
if (data.getExtras() == null)
return;
Bitmap thumb = (Bitmap) data.getExtras().get("data");
mImage.setImageBitmap(thumb);
// Compress the Bitmap image into JPEG to save it on the device
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumb.compress(Bitmap.CompressFormat.JPEG, 100, bytes);// 100 is the scale..for less quality decrease the number
// Save the image on the root SDCard
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "imageName.png");
try {
// Create the file to save the image
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (Exception e) {
}
}
}
}
Put This in your Layout MainActivity.XML :
<ImageView android:id="@+id/camera_image"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…