I've been following the Camera API Demo from the android developer site. After fixing alot of stuf i've come to my last problem. I want to use the picture i've just taken and display it in another activity (like when after you take a picture you first gotta accept it or redo it style).
My TakePhoto class :
public class TakePhoto extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
ImageButton captureButton;
private Camera mCamera;
private CameraPreview mPreview;
private Handler handler = new Handler();
private int SELECT_PICTURE = 1;
private String selectedImagePath;
FrameLayout preview;
private String documentType;
private Camera.Parameters p;
private PictureCallback mPicture = new PictureCallback() {
private String TAG = "DocsPro";
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d(TAG, "Error creating media file, check storage permissions : PICTURE FILE IS NULL");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.d(TAG, "fos.new");
fos.write(data);
Log.d(TAG, "fos.write");
fos.close();
Log.d(TAG, "fos.close");
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
//Accessing cameras
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.scan);
Intent myIntent = getIntent();
documentType = myIntent.getStringExtra("documentType");
Button terug = (Button) findViewById(R.id.button_terug);
ImageButton iTerug = (ImageButton) findViewById(R.id.imageButton_terug);
ImageButton gallery = (ImageButton) findViewById(R.id.button_galery);
ImageButton flash = (ImageButton) findViewById(R.id.button_flash);
preview = (FrameLayout) findViewById(R.id.camera_preview);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(TakePhoto.this, mCamera);
captureButton = (ImageButton) findViewById(R.id.button_capture);
preview.addView(mPreview);
captureButton.bringToFront();
gallery.bringToFront();
flash.bringToFront();
p = mCamera.getParameters();
gallery.setOnClickListener(
new OnClickListener(){
#Override
public void onClick(View v)
{
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
}
);
flash.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(p.getFlashMode() == android.hardware.Camera.Parameters.FLASH_MODE_ON){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(p);
mCamera.startPreview();
Log.e("Torch","MODE ON");
}else if(p.getFlashMode() == android.hardware.Camera.Parameters.FLASH_MODE_OFF){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(p);
mCamera.release();
mCamera=null;
Log.e("Torch","MODE OFF");
}else if(p.getFlashMode() == android.hardware.Camera.Parameters.FLASH_MODE_AUTO){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(p);
mCamera.startPreview();
Log.e("Torch","MODE AUTO");
}else if(p.getFlashMode() == android.hardware.Camera.Parameters.FLASH_MODE_TORCH){
p.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
mCamera.setParameters(p);
mCamera.startPreview();
Log.e("Torch","MODE TORCH");
}else{
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(p);
mCamera.startPreview();
Log.e("Torch","MODE ELSE");
}
}
});
// Add a listener to the Capture button
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
handler.postDelayed(new Runnable() {
#Override
public void run() {
mCamera.autoFocus(autoFocusCallback);
}
}, 1500L);
}
AutoFocusCallback autoFocusCallback=new AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
mCamera.takePicture(null, null, mPicture);
}
};
});
// Add listeners to Terug buttons
terug.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TakePhoto.this, PickDocumentType.class);
startActivity(intent);
finish();
}
});
// Add listeners to Terug buttons
iTerug.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TakePhoto.this, PickDocumentType.class);
startActivity(intent);
finish();
}
});
}
/**
* A safe way to get an instance of the Camera object.
*/
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/**
* Create a File for saving an image or video
*/
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "DocsPro");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null)
{
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else return null;
}
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
#Override
public void onStop()
{
super.onStop();
releaseCamera();
}
//Receiving camera intent result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Log.d("foto", "Image saved to:\n" +
data.getData());
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
else if (requestCode == SELECT_PICTURE)
{
if (resultCode == RESULT_OK) {
releaseCamera();
Uri selectedImageUri = data.getData();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
Intent edit = new Intent(TakePhoto.this, EditPhoto.class);
edit.putExtra("filepath", selectedImagePath);
edit.putExtra("documentType", documentType);
startActivity(edit);
finish();
releaseCamera();
}
}
}
}
How do i get the image taken in the above class and transfer it to my new activity?
EDIT SOLUTION OF MY OWN :
I remembered that i had a method that would create the directory for my image, so i knew the location. Only trick was to get the filepath. And because the method getOutputMediaFile was saved in a File I just had to getAbsolutePath() and sent it with the intent :
String filepath = pictureFile.getAbsolutePath();
Intent edit = new Intent(TakePhoto.this, EditPhoto.class);
edit.putExtra("filepath", filepath);
startActivity(edit);
finish();
Then in the other activity i just get it like this and display it:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bijsnijden);
Intent myIntent = getIntent();
imagePath = myIntent.getStringExtra("filepath");
documentType = myIntent.getStringExtra("documentType");
ImageView imageView = (ImageView) findViewById(R.id.Image);
imageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
Convert it to a Byte array before you add it to the intent, send it out, and decode.
//Convert to byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",byteArray);
Then in Activity 2:
byte[] byteArray = getIntent().getByteArrayExtra("image");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Related
I want to upload image from gallery in my android app. When I click on button, the gallery should be opened. After selecting image, I want to open another activity named UploadActivity. There the thumbnail of the image should be previewed. The Upload Button will below the thumbnail.
But when I Choose photo from gallery, then the thumbnail of the image are not previewing. I am unable to upload the photo also. My Code goes here: (Scan.Java)
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int SELECT_IMAGE = 2;
private Uri fileUri; // file url to store image/video
ImageView dummy;
private Button btnCapturePicture;
private Button btnGallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan);
dummy = (ImageView) findViewById(R.id.dummyphoto);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
btnGallery = (Button) findViewById(R.id.btnGallery);
/**
* Capture image button click event
*/
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// capture picture
captureImage();
}
});
btnGallery.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
openGallery();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching Gallery to Choose Image
*/
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
else if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(Scan.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
UploadActivity.Java Code goes here:
private ProgressBar progressBar;
private String filePath = null;
private TextView txtPercentage;
private ImageView imgPreview;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
btnUpload = (Button) findViewById(R.id.btnUpload);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
// Receiving the data from previous activity
Intent i = getIntent();
// image path that is captured in previous activity
filePath = i.getStringExtra("filePath");
// boolean flag to identify the media type, image
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
/**
* Displaying captured image on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
Here is Logcat:
E/MainActivity: Response from server: java.io.FileNotFoundException: /mnt/sdcard/Pictures/master/IMG_20170127_152930.jpg: open failed: ENOENT (No such file or directory)
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "IMG_20170127_152930.jpg");
//Try this.
After these changes i suggested below I hope your problem will be solved:
Remove these two lines from openGallery() because I think they are redundant.
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
They are needed when we use Intent.ACTION_PICK. So after editing openGallery() looks like:
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"),SELECT_IMAGE);
}
Add this statement in your onActivityResult() :
fileUri = data.getData();
so it looks:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
...
else if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
fileUri = data.getData(); //added this line
launchUploadActivity(true);
}
} else if (resultCode == Activity.RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Same applies to the camera intent also.
Request EXTERNAL_STORAGE permission and also run time permission if your target Android version is 6.0 or above.
EDIT:
Sorry couple of things I have not mentioned those are required are given bellow:
You may like to send the Uri instead of path this way:
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(this, UploadActivity.class);
i.setData(fileUri);
// i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
And then in UploadActivity do the following:
...
private InputStream mInputStream; // Use this stream to create bitmap and upload to server
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// Receiving the data from previous activity
Intent i = getIntent();
try {
mInputStream = getContentResolver().openInputStream(i.getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
...
}
...
...
private void previewMedia(boolean isImage){
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(mInputStream,null,options);
imgPreview.setImageBitmap(bitmap);
} else {
imgPreview.setVisibility(View.GONE);
}
}
...
This works for me and hope will work on you too.
It's bugging me for few days know. Problem is that I don't know if I'm going in right direction.
My starting activity is ImageDisplay class which calls startActivityForRestult for CustomCamera activity. After picture is taken user is returned to ImageDisplay and capture image should be displayed, but its not. What am I doing wrong?
Second thing, I guess its really important, at which point camera should be released?
ImageDisplay:
public class ImageDisplay extends Activity{
ImageView imageHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.al_imagedisplay);
imageHolder = (ImageView) findViewById(R.id.imageView1);
Intent intent = new Intent(this, CustomCamera.class);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("result");
imageHolder.setImageBitmap(photo);
}
}
}
CustomCamera:
public class CustomCamera extends Activity {
private Camera mCamera;
private NewItemSurfaceView mPreview;
Button captureButton;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
public static final String MY_CAMERRA_APP = "MyCameraApp";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.al_newitem_camera);
captureButton = (Button) findViewById(R.id.buttonClick);
// Create an instance of Camera
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
// Create our Preview view and set it as the content of our activity.
mPreview = new NewItemSurfaceView(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.flCamera);
preview.addView(mPreview);
// Add a listener to the Capture button
captureButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
});
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("Camera error",
"Error creating media file, check storage permissions: ");
return;
}
Log.i("Picture", pictureFile.toString());
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("Camera error", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Camera error", "Error accessing file: " + e.getMessage());
}
Intent returnIntent = new Intent();
returnIntent.putExtra("result", pictureFile);
setResult(RESULT_OK, returnIntent);
finish();
}
};
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.i("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
modify onActivityResult method like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
String photoPath = (String) data.getExtras().get("result");
imageHolder.setImageBitmap(BitmapFactory.decodeFile("photoPath"));
}
}
Do some modification in your onPictureTaken method like this
Intent returnIntent = getIntent();
returnIntent.putExtra("result", pictureFile.getAbsolutePath());
setResult(RESULT_OK, returnIntent);
finish();
I'm working with eclipse to develop a custom camera app for android. I've figured out how to display the preview of the camera, but I can't figure out how to take a picture without saving the image. When a picture is taken, I don't want to save the image or display it to the screen, I simply want it saved to a data type that I can use within the app and overwrite when another picture is taken.
Edit:
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private Bitmap picture;
private static Uri mImageCaptureUri;
private static Bitmap photo = null;
private byte[] image;
private int PICK_FROM_CAMERA = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
#Override
protected void onCreate(Bundle savedInstanceState) {
releaseCameraAndPreview();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
else{
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
image = bos.toByteArray();
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()){
f.delete();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//creates camera class for functions
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
Log.v("Schweigen", "camera will not open");
}
return camera;
}
//releases camera on completion
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.v("Schweigen", "onShutter");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.v("Schweigen", "onPictureTaken");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//picture = BitmapFactory.decodeByteArray(data , 0, data.length);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
};
}
Make a Uri from the picture.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Uri uriSavedImage=Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString()+"/ImagesFolder/image.jpg"));
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
Edit: After that you may store it in a byte[].
As I told you, you have to get the the Intent from the Camera and set it to a Uri:
private static Uri mImageCaptureUri;
private static Bitmap photo = null;
private byte[] image;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
else{
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
image = bos.toByteArray();
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
}
}
The API to directly take a picture is here.
Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery.Just recorded Video/Audio is not played with some devices. Getting "sorry, video cannot be played", but same video played in gallery.
below is my code
public class CaptureImageActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "ICS Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private VideoView videoPreview;
private TextView cancel, send;
private Intent intent1;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
HomeActivity.myempid = 1;
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_capture_image);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
cancel = (TextView) findViewById(R.id.cancel);
send = (TextView) findViewById(R.id.send);
int mode = getIntent().getIntExtra(
ApplicationConstants.IntentKeys.KEY_MODE, 0);
try {
if (HomeActivity.camera != null) {
HomeActivity.camera.release();
HomeActivity.camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (mode == 0)
captureImage();
else
recordVideo();
/*
* Capture image button click event
*/
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
}
});
/*
* Record video button click event //
*/
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent picMessageIntent = new Intent(
android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
File downloadedPic = new File(fileUri.getPath());
System.out.println("PATH " + fileUri.getPath());
picMessageIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(downloadedPic));
startActivity(picMessageIntent);
// CaptureImageActivity.this.finish();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent1, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/*
* Recording video
*/
private void recordVideo() {
intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent1.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image
// file
// name
// start the video capture Intent
startActivityForResult(intent1, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
System.out.println("RESULT CANCELED");
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
// Uri.parse(fileUri.getPath())));
System.out.println("RESULT OK");
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
finish();
} else {
System.out.println("FAIL");
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
System.out.println(bitmap);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo() {
try {
System.out.println("PATH " + fileUri.getPath());
getContentResolver().notifyChange(Uri.parse(fileUri.getPath()),
null);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoPreview);
// mc.setMediaPlayer(videoPreview);
// hide image preview
// videoPreview.setOnPreparedListener(new OnPreparedListener() {
//
// public void onPrepared(MediaPlayer mp) {
// // TODO Auto-generated method stub
// mp.start();
// }
// });
imgPreview.setVisibility(View.GONE);
// getWindow().clearFlags(
// WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
videoPreview.setVisibility(View.VISIBLE);
// 02-15 11:51:52.973: I/System.out(17840): PATH
// /mnt/sdcard/Pictures/ICS Camera/VID_20140215_115133.mp4
videoPreview.setVideoPath(fileUri.getPath());
// videoPreview.setVideoURI(Uri.parse(Provoder.CONTENT_URI_BASE
// + Uri.encode(fileUri.getPath())));
videoPreview.setMediaController(mc);
videoPreview.requestFocus();
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/*
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
Solved my issue by using below code
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.kubical.ES.R;
import com.kubical.ES.util.ApplicationConstants;
public class CaptureImageActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
// directory name to store captured images and videos
private ImageView imgPreview;
private VideoView videoPreview;
private TextView cancel, send;
private Intent intent1;
private String filePath;
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
HomeActivity.myempid = 1;
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_capture_image);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
cancel = (TextView) findViewById(R.id.cancel);
send = (TextView) findViewById(R.id.send);
int mode = getIntent().getIntExtra(
ApplicationConstants.IntentKeys.KEY_MODE, 0);
try {
if (HomeActivity.camera != null) {
HomeActivity.camera.release();
HomeActivity.camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if (mode == 0)
captureImage();
else
recordVideo();
/*
* Capture image button click event
*/
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
}
});
/*
* Record video button click event //
*/
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent picMessageIntent = new Intent(
android.content.Intent.ACTION_SEND);
picMessageIntent.setType("image/jpeg");
File downloadedPic = new File(filePath);
System.out.println("PATH " + filePath);
picMessageIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(downloadedPic));
startActivity(picMessageIntent);
// CaptureImageActivity.this.finish();
}
});
// Checking camera availability
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
finish();
}
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/*
* Capturing Camera Image will lauch camera app requrest image capture
*/
private void captureImage() {
intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/*
* Recording video
*/
private void recordVideo() {
intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent1, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
previewCapturedImage(data);
} else if (resultCode == RESULT_CANCELED) {
System.out.println("RESULT CANCELED");
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
CaptureImageActivity.this.finish();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
previewVideo(data);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Intent intent = new Intent(CaptureImageActivity.this,
HomeActivity.class);
startActivity(intent);
HomeActivity.myempid = 1;
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
finish();
} else {
System.out.println("FAIL");
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage(Intent data) {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
System.out.println("PATH IS " + filePath);
cursor.close();
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
System.out.println(bitmap);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/*
* Previewing recorded video
*/
private void previewVideo(Intent data) {
try {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filePath = cursor.getString(column_index);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoPreview);
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(filePath);
videoPreview.setMediaController(mc);
videoPreview.requestFocus();
videoPreview.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have complete working code to take a picture, crop it, send email with image attachment.
Here is the flow of the code:
Take a picture > Find and select the picture we just took from Gallery > Crop it > Email attachment.
I would like to find out how I can skip the whole "Find and select the picture we just took from Gallery" part out and just go straight into cropping immediately after taking the picture.
Is there an Intent that can do what I am requesting?
I've tried this tutorial but it still makes the user go into gallery and look for the picture they just took
http://www.londatiga.net/featured-articles/how-to-select-and-crop-image-on-android/
EDIT I should also mention that I have a custom view when I am taking pictures so Im not sure if I can use Intent MediaStore.ACTION_IMAGE_CAPTURE
Here is the code that executes the cropping AND also makes you choose the image you just took by looking in the gallery.
Intent crop_pic = new Intent(Intent.ACTION_PICK, uriTarget); // used to be ACTION_GET_CONTENT /ACTION_PICK
crop_pic.putExtra("crop", "true"); // this enables crop feature
//crop_pic.putExtra("aspectX", 200); // this defines the aspect ration
//crop_pic.putExtra("aspectY", 150);
//crop_pic.putExtra("outputX", 500); // this defines the output bitmap size
//crop_pic.putExtra("outputY", 500);
//crop_pic.putExtra("scale", true);
try { crop_pic.putExtra("return-data", false); // true to return a Bitmap, false to directly save the cropped iamge
crop_pic.putExtra(MediaStore.EXTRA_OUTPUT, uriTarget); // save output image in uri
//crop_pic.setDataAndType(uriTarget, "image/*"); // this will open all images in the Galery
startActivityForResult(crop_pic, EMAIL_PIC);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
catch (ActivityNotFoundException e) {
toast.showToastDialog(getApplicationContext(), e.toString());
}
LOGCAT.DEBUG(TAG, "Cropping Picture");
}
Is there an Intent im not aware of that can just start cropping if I supply it with a uri Target?
Here is the full code:
public class DigitalSignature extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceHolder surfaceHolder;
boolean previewing = false;
Uri uriTarget;
String[] recipients = new String[]{"test#gmail.com", "",};
final int CROP_PIC = 1, EMAIL_PIC = 2, RETURN_ACTIVITY = 3, FINISH = 4, INDEX_GALLERY = 5;
final String TAG = "Digital Signature";
ToastBuilder toast = new ToastBuilder(this);
ProjectDebug LOGCAT = new ProjectDebug();
ProgressDialogManager pDialog = new ProgressDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DigitalSignature.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
DigitalSignature.this.setContentView(R.layout.digitalsignature);
DigitalSignature.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
DigitalSignature.this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
DigitalSignature.this.getWindow().setFormat(PixelFormat.TRANSLUCENT); // Used to be TRANSPARENT
SurfaceView surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(DigitalSignature.this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
LayoutInflater controlInflater = LayoutInflater.from(getApplicationContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
DigitalSignature.this.addContentView(viewControl, layoutParamsControl); // Applying Filters and Parameters
TextView alignsig = (TextView)findViewById(R.id.alignsig);
alignsig.setText("Please take picture of the signature for" + "\n" + "Job Number " + DIGIJOB);
Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
LOGCAT.DEBUG(TAG, "Taking Picture");
// Sets camera monochrome filter ( Black and Whiite )
Camera.Parameters parameters = camera.getParameters();
parameters.setColorEffect(android.hardware.Camera.Parameters.EFFECT_MONO);
camera.setParameters(parameters);
camera.startPreview();
// Initiate Camera Focus
camera.autoFocus(mAutoFocusCallback);
// Creates Directory to save image in gallery
uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
//Notify the MediaScanner that a new file has been added and should be indexed so it shows up in the MediaStore.
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(uriTarget);
sendBroadcast(intent);
}
});
}
Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
}
};
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
//bmp = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
cropPic();
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
toast.showToastDialog(getApplicationContext(), "Image saved: " + uriTarget.toString());
}
catch (IOException e) {
toast.showToastDialog(getApplicationContext(), e.toString());
}
// camera.startPreview(); // No need to start preview, we are saving
}}; // picture and no longer initiating camera
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CROP_PIC:
cropPic();
LOGCAT.DEBUG(TAG, "cropPic Case");
break;
case EMAIL_PIC:
emailPic();
LOGCAT.DEBUG(TAG, "emailPic Case");
break;
case RETURN_ACTIVITY:
returnActivity();
LOGCAT.DEBUG(TAG, "returnActivity Case");
break;
}
}
private void cropPic() {
Intent crop_pic = new Intent(Intent.ACTION_PICK, uriTarget); // used to be ACTION_GET_CONTENT /ACTION_PICK
crop_pic.putExtra("crop", "true"); // this enables crop feature
//crop_pic.putExtra("aspectX", 200); // this defines the aspect ration
//crop_pic.putExtra("aspectY", 150);
//crop_pic.putExtra("outputX", 500); // this defines the output bitmap size
//crop_pic.putExtra("outputY", 500);
//crop_pic.putExtra("scale", true);
try { crop_pic.putExtra("return-data", false); // true to return a Bitmap, false to directly save the cropped iamge
crop_pic.putExtra(MediaStore.EXTRA_OUTPUT, uriTarget); // save output image in uri
//crop_pic.setDataAndType(uriTarget, "image/*"); // this will open all images in the Galery
startActivityForResult(crop_pic, EMAIL_PIC);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
catch (ActivityNotFoundException e) {
toast.showToastDialog(getApplicationContext(), e.toString());
}
LOGCAT.DEBUG(TAG, "Cropping Picture");
}
private void emailPic(){
// new email_pic().execute();
GMailSender m = new GMailSender("username#gmail.com", "testtest");
String[] toArr = { "sendingto#gmail.com" };
m.setTo(toArr);
m.setFrom("sendingto#gmail.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment(getRealPathFromURI(uriTarget));
if(m.send()) {
Toast.makeText(DigitalSignature.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(DigitalSignature.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
// OLD METHOD OF SENDING EMAIL
/* Intent email_pic = new Intent(Intent.ACTION_SEND); // Commence choose photo action
email_pic.putExtra(Intent.EXTRA_EMAIL, recipients); // Inserts Digital Signature address automatically in recipient
email_pic.putExtra(Intent.EXTRA_SUBJECT, DIGIJOB); // Inserts Track Number automatically in subject
email_pic.putExtra(Intent.EXTRA_STREAM, uriTarget); // Attaches image to Gmail
email_pic.setType("image/jpeg"); // Converts image to jpeg
startActivityForResult(email_pic, RETURN_ACTIVITY);
overridePendingTransition(R.anim.fadein, R.anim.fadeout); */
JOB = "job"; // Reset job variable from track no (1736) to "job" so
LOGCAT.DEBUG(TAG, "Emailing Picture"); // when you go back into Jobs Activity, it can parse data.
returnActivity();
}
private void returnActivity() {
Intent email_pic = new Intent(DigitalSignature.this, AgentPortalActivity.class);
startActivityForResult(email_pic, FINISH);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
LOGCAT.DEBUG(TAG, "Returning Activity");
}
private String getRealPathFromURI(Uri uriTarget) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uriTarget, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
LOGCAT.DEBUG("getRealPathFromURI", cursor.getString(column_index));
return cursor.getString(column_index);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try { camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch (IOException e) {
toast.showToastDialog(getApplicationContext(), e.toString());
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
//camera = Camera.open(0);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
You just need to use the MediaStore.ACTION_IMAGE_CAPTURE intent action. That will launch the camera. And in your onActivityResult you can get a the image that was just taken. Now you can crop it and send it and whatever else you'd like. Below is an example.
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File cameraPhotoFile = new File(pics, System.currentTimeMillis()+".jpg");
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraPhotoFile));
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_CODE_CAMERA) {
MediaScannerConnection.scanFile(this,
new String[]{cameraPhotoFile.getAbsolutePath()}, null, null);
// do something with the image located at cameraPhotoFile
I've included the MediaScannerConnection because the image will not show up in the gallery until it gets scanned. You can remove that if you want, but I like images that were taken to show up. The bitmap is now located in the "cameraPhotoFile." Use that file however you like.
Also, here are the docs from Google about this called Taking Photos Simply. It's pretty straight forward
The easiest solution i can think of is:
Call the ACTION_IMAGE_CAPTURE Intent to take a picture with the Stock Camera
onActivityResult you will get the content uri of the new picture over data.getData()
Do it like vogella here http://blog.vogella.com/2011/09/13/android-how-to-get-an-image-via-an-intent/ and directly open an inputstream to the new picture
no need for the pick intent.