How to do custom image cropping in android - android

In my application, I need to take images from gallery/camera, crop those images, then save the cropped images some where else. The below code does most of that, but cannot crop images to my liking. Using the below code, I can crop images using 4 coordinates, top, bottom, left and right side of image middle coordinates; but I need to crop using 8 coordinates. This image shows what I mean.
public class MainActivity extends Activity {
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 2;
private static final int PRESS_OK = 3;
ImageView imgview;
String m_path;
Bitmap m_thePic;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
Button buttonOk = (Button) findViewById(R.id.btn_ok);
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/Images/");
folder.mkdirs();
buttonCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 100);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
buttonOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String m_path = Environment.getExternalStorageDirectory().toString();
File m_imgDirectory = new File(m_path + "/Images/");
File m_file = new File(m_path);
String m_fileid = "nm_tech" + System.currentTimeMillis() + "";
m_file = new File(m_path, "/Images/" + m_fileid + ".jpg");
Uri outputFileUri = Uri.fromFile(m_file);
Intent intent = new Intent(MainActivity.this,
ImageGalleryDemoActivity.class);
intent.putExtra("image", m_fileid);
startActivity(intent);
// startActivityForResult(intent,PRESS_OK);
// call android default camera
// Toast.makeText(getApplicationContext(), ,1234).show();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras = data.getExtras();
Bitmap m_thePic = extras.getParcelable("data");
String m_path = Environment.getExternalStorageDirectory().toString();
File m_imgDirectory = new File(m_path + "/Images/");
if (!m_imgDirectory.exists()) {
m_imgDirectory.mkdir();
}
OutputStream m_fOut = null;
File m_file = new File(m_path);
m_file.delete();
String m_fileid = "nm_tech" + System.currentTimeMillis() + "";
m_file = new File(m_path, "/Images/" + m_fileid + ".jpg");
try {
if (!m_file.exists()) {
m_file.createNewFile();
}
m_fOut = new FileOutputStream(m_file);
Bitmap m_bitmap = m_thePic.copy(Bitmap.Config.ARGB_8888, true);
m_bitmap.compress(Bitmap.CompressFormat.PNG, 100, m_fOut);
m_fOut.flush();
m_fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
m_file.getAbsolutePath(),
m_file.getName(),
m_file.getName());
} catch (Exception p_e) {
}
if (requestCode == PICK_FROM_CAMERA) {
if (extras != null) {
// Bitmap photo = extras.getParcelable("data");
imgview.setImageBitmap(m_thePic);
}
}
if (requestCode == PICK_FROM_GALLERY) {
// Bundle extras2 = data.getExtras();
if (extras != null) {
imgview.setImageBitmap(m_thePic);
}
}
if (requestCode == PRESS_OK) {
Bundle extras11 = data.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
/*
* Bitmap photo = extras.getParcelable("data");
* imgview.setImageBitmap(photo); Intent n=new
* Intent(getApplicationContext(),ImageGalleryDemoActivity.class);
* n.putExtra("data",photo); startActivity(n);
*/
}
}
}

Here is a simple way for you to create minimum needed rect from an array of coordinates
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Rect r = getRect(new int[]{10, 10, 20, 20, 30, 30}, new int[]{20, 100, 10, 110, 20, 100});
System.out.println(r.left + " " + r.top + " " + r.bottom + " " + r.right);
}
public Rect getRect(int[] x, int y[]){
Rect r = new Rect();
// Set the first coordinate, in order not to include 0, 0
r.set(x[0], y[0], x[0], y[0]);
for(int i = 1; i < x.length; i++){
r.union(x[i], y[i]);
}
return r;
}
EDIT: look you have 8 points, just call this getRect like this
Rect rectToDraw = getRect(new int{yourx1, yourx2, yourx3, yourx4, yourx5, yourx6, yourx7, yourx8,}, new int{youry1, youry2, youry3, youry4, youry5, youry6, youry7, youry8});
You can pass this function ass many points you want, not just 8
Hope this helps and enjoy your work

Related

Android Choose Image or Camera

I have implemented the code for choosing an image from SD or Camera.
But, my image doesn't show up in ImageView and I can't choose an image from SD card.
When I click on an image from SD card it jumps instant back to my Activity.
final String[] items = new String[] {"From Camera","From SD Card"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
if(which == 0){
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),"event_image"+String.valueOf(System.currentTimeMillis()+".jpg"));
imageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageCaptureUri);
intent.putExtra("return data",true);
startActivityForResult(intent,PICK_FROM_CAMERA);
}catch(Exception ex){
ex.printStackTrace();
}
dialog.cancel();
}else{
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Complete action using"),PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.imageView);
imagePicker = (ImageButton) findViewById(R.id.image_picker);
imagePicker.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dialog.show();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode != RESULT_OK)
return;
Bitmap bitmap = null;
String path ="";
if(requestCode == PICK_FROM_FILE) {
imageCaptureUri = data.getData();
path = getRealPathFromURI(imageCaptureUri);
if(path == null)
path = imageCaptureUri.getPath();
if(path != null){
bitmap = BitmapFactory.decodeFile(path);
}
}else{
path = imageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentURI){
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentURI,proj,null,null,null);
if(cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
First you need to use permission WRITE_EXTERNAL_STORAGE in AndroidManifest.xml
In your xml layout :
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#f241c9" />
<Button
android:id="#+id/btnCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Take Photo" />
<Button
android:id="#+id/btnPick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Pick Photo" />
In your activity class :
private static final String TAG = "my_log";
private static final int REQUEST_CAPTURE_FROM_CAMERA = 1;
private static final int REQUEST_PICK_FROM_FILE = 2;
private static final int REQUEST_CROP_INTENT = 3;
ImageView img;
Button btnCapture, btnPick;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnPick = (Button) findViewById(R.id.btnPick);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_captured.jpg");
// put Uri as extra in intent object
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, REQUEST_CAPTURE_FROM_CAMERA);
}
});
btnPick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == REQUEST_CAPTURE_FROM_CAMERA) {
try {
cropImage(Uri.fromFile(file));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_PICK_FROM_FILE) {
try {
cropImage(data.getData());
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else if (requestCode == REQUEST_CROP_INTENT) {
// Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap from extras
Bitmap bitmap = extras.getParcelable("data");
img.setImageBitmap(bitmap);
if (saveBitmapToStorage(bitmap)) {
Log.d(TAG, "Bitmap saved to file successful.");
} else {
Log.d(TAG, "Failed to save Bitmap to storage.");
}
}
}
public void cropImage(Uri picUri) {
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, REQUEST_CROP_INTENT);
}
private boolean saveBitmapToStorage(Bitmap finalBitmap) {
boolean result = false;
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_cropped.jpg");
Log.d(TAG, "file path = " + file.getAbsolutePath());
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// send Broadcast to notify this photo and see it in Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Android : Integrating gallery functionality with camera capture

I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.
What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.
I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.
I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.
I searched for similar functionality, but the problem is, I have not found, where such features are integrated.
Java code :
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private static boolean galleryFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if(!galleryFlag){
// I think the gallery open code should come here.
}
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
}else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if(!(reducedSizeBitmap == null)){
if(reducedSizeBitmap == null){
Log.d("Image bitmap"," Is null");
}
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
}
}
}
I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)
Edit with Answer
Finally the integration works. I had to combine answers from the one I received and here on SO.
Final Code
public class AddPhotosForRestaurant extends RestaurantDrawerActivity {
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
private Uri imageToUploadUri = null;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private boolean galleryFlag = false;
private boolean uploadNow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
set(null, null);
final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if (uploadNow) {
uploadNow = false;
galleryFlag = true;
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
}
if (!galleryFlag) {
galleryFlag = true;
uploadNow = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_INTENT_REQUEST_CODE);
} else {
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if (imageToUploadUri != null) {
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if (reducedSizeBitmap != null) {
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
}
if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = Uri.parse(data.getDataString());
reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImage);
ImgPhoto.setImageBitmap(reducedSizeBitmap);
} catch (Exception e) {
Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if (!(reducedSizeBitmap == null)) {
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
}
}
}
Thanks a lot for all your help.. :-)
In Constant file write in my case(ActivityConstantUtils.java)
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
To open Gallery & get path of selected image use following code :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
After that you get path in onActivityResult() method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
String imagePath = getFilePath(data);
// TODO: Here you set data to preview screen
}catch(Exception e){}
}
}
private String getFilePath(Intent data) {
String imagePath;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}

getActivityResult() method give null in Intent parameter

good morning sir, I have used Navigation drawer and fragment. i'm using ActionBarActivity and in which i have called this Fragment. in my Fragment i capture image from camera so in getActivityResult() method not give me Intent values.
public class CameraDemo extends Fragment implements View.OnClickListener {
ImageButton mImgBtnActivityBack,mImgBtnActivityWrong,mImgBtnActivityRight ,mImgBtnActivityEdit ,mImgBtnActivitySearch ,mImgBtnActivityAdd ,mImgBtnActivityNext,mImgBtnActivitySetting;
LinearLayout mLinearLayout1,mLinearLayout2;
Button mFragSignatureClear,mBtnBlack,mBtnRed,mSIBtnSubmit,mSIBtnCamera,mSIBtnAdd ;
PaintView mPaintView;
int currrID = 0;
android.support.v4.app.Fragment fragment;
public int st = 3;
int sizex, sizeh;
Paint paint = new Paint() ;
Uri imageUri=null ;
final int CAMERA_DATA = 1888, INTENT_DATA = 1 ;
Bitmap mbkground ;
public CameraDemo() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mbkground = null ;
mLinearLayout2=(LinearLayout) rootView.findViewById(R.id.draw);
mPaintView = new PaintView(getActivity().getApplicationContext());
mLinearLayout2.addView(mPaintView);
mFragSignatureClear=(Button) rootView.findViewById(R.id.fragSignatureClear);
mFragSignatureClear.setOnClickListener(this);
mBtnBlack=(Button)rootView.findViewById(R.id.black);
mBtnBlack.setOnClickListener(this);
mBtnRed=(Button)rootView.findViewById(R.id.red);
mBtnRed.setOnClickListener(this);
mSIBtnSubmit=(Button) rootView.findViewById(R.id.fragSIBtnSubmit);
mSIBtnSubmit.setOnClickListener(this);
mSIBtnCamera=(Button) rootView.findViewById(R.id.camera) ;
mSIBtnCamera.setOnClickListener(this) ;
mSIBtnAdd = (Button) rootView.findViewById(R.id.add) ;
mSIBtnAdd . setOnClickListener( this );
DisplayMetrics m = this.getResources().getDisplayMetrics();
float density = getResources().getDisplayMetrics().density;
int w = m.widthPixels;
int h = m.heightPixels;
sizex = w;
sizeh = h;
Log.i("hi", "" + sizex);
Log.i("hi", "" + sizeh);
Log.i("hi", "" + density);
float fsize = sizex / density;
return rootView;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.black){
currrID=v.getId();
}else if(v.getId()==R.id.black){
currrID=v.getId();
}else if(v.getId()==R.id.fragSIBtnSubmit){
mPaintView.toJPEGFile();
mPaintView.SaveFile();
}else if(v.getId()==R.id.camera){
captureImage();
}else if(v.getId()==R.id.add){
mPaintView.loadFromFile();
}
else {
Toast.makeText(getActivity().getApplicationContext(), "FragSIPhotos Add Button OnClick", Toast.LENGTH_SHORT).show();
}
}
class Point {
float x, y;
public String toString() {
return x + "," + y;
}
}
public class LineData {
List<Point> points = new ArrayList<Point>();
LineData(List<Point> p) {
points.addAll(p);
}
public void Draw(Canvas mCanvas, Paint paint) {
float fData[] = new float[points.size() * 4];
int Index = 0;
for (Point point : points) {
if (Index > 0) {
fData[Index++] = point.x;
fData[Index++] = point.y;
}
fData[Index++] = point.x;
fData[Index++] = point.y;
// canvas.drawCircle(point.x, point.y, 5, paint);
}
if (Index > 2)
mCanvas.drawLines(fData, 0, Index - 2, paint);
}
}
public class PaintView extends View implements View.OnTouchListener {
private static final String TAG = "PaintView" ;
Paint paint = new Paint() ;
int t = 0 ;
List<Point> points = new ArrayList<Point>() ;
List<LineData> pointsred = new ArrayList<LineData>() ;
List<LineData> pointsblack = new ArrayList<LineData>() ;
public PaintView(Context context) {
super(context) ;
setFocusable(true) ;
setFocusableInTouchMode(true) ;
List<Point> points = new ArrayList<Point>() ;
setDrawingCacheEnabled(true) ;
this.setOnTouchListener(this) ;
mbkground = BitmapFactory.decodeResource(getResources(),
R.drawable.plain) ;
paint.setAntiAlias(true) ;
paint.setStrokeMiter(10.0f) ;
paint.setStrokeWidth(st) ;
currrID = R.id.red ;
}
#Override
public void onDraw(Canvas mCanvas) {
mCanvas.drawBitmap(mbkground, 0, 0, null);
// canvas.drawColor(Color.WHITE) ;
this.setBackgroundColor(Color.BLACK);
// To Do Paint for text
//this code for my image app
//yesss very good
/* Paint mText= new Paint(Color.RED);
mText.setTextSize(25);
mCanvas.drawText("Hiren",100,100,mText);
*/ if (currrID == R.id.red)
paint.setColor(Color.RED) ;
else if (currrID == R.id.black)
paint.setColor(Color.BLACK) ;
else
paint.setColor(Color.BLACK) ;
float fdata[] = new float[points.size() * 4] ;
int Index = 0 ;
for (Point point : points) {
if (Index > 0) {
fdata[Index++] = point.x ;
fdata[Index++] = point.y ;
}
fdata[Index++] = point.x ;
fdata[Index++] = point.y ;
// canvas.drawCircle(point.x, point.y, 5, paint);
}
if (Index > 2)
mCanvas.drawLines(fdata, 0, Index - 2, paint);
paint.setColor(Color.RED) ;
for (LineData lines : pointsred)
lines.Draw(mCanvas, paint) ;
paint.setColor(Color.BLACK) ;
for (LineData lines : pointsblack)
lines.Draw(mCanvas, paint) ;
paint.setColor(Color.WHITE) ;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
points.clear() ;
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
{
LineData data = new LineData(points) ;
if (currrID == R.id.red)
pointsred.add(data) ;
else if (currrID == R.id.black)
pointsblack.add(data) ;
points.clear() ;
}
} else {
Point point = new Point() ;
point.x = event.getX() ;
point.y = event.getY() ;
points.add(point) ;
}
invalidate() ;
return true;
}
public void toJPEGFile() {
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/") ;
if (!folder.exists())
folder.mkdirs() ;
try {
this.setDrawingCacheEnabled(true) ;
File f = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/" + "Mateco" + ".png") ;
// file mFile = new File(Environment.g)
FileOutputStream fos = new FileOutputStream(f) ;
Bitmap bitmap = this.getDrawingCache() ;
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos) ;
// 80 quality bet 0-100 define
fos.flush() ;
fos.close() ;
this.setDrawingCacheEnabled(false) ;
} catch (FileNotFoundException e) {
e.printStackTrace() ;
} catch (IOException e) {
e.printStackTrace() ;
}
}
public void loadFromFile() {
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream(
Environment.getExternalStorageDirectory() + "/Mateco/"
+ "mateco" + ".jpg");
buf = new BufferedInputStream(in);
mbkground = BitmapFactory.decodeStream(buf);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
public void setBitMap(){
/* mbkground = BitmapFactory.decodeResource(getResources(),
R.drawable.background) ;
*/
}
public void setBitMap(Bitmap photo){
mbkground = photo;
}
public void SaveFile() {
Toast.makeText(getActivity().getApplicationContext(),"Save 1",Toast.LENGTH_SHORT).show();
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/");
if (!folder.exists())
folder.mkdirs();
try {
this.setDrawingCacheEnabled(true);
t++;
File f = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos = new FileOutputStream(f);
Bitmap bitmap = this.getDrawingCache();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
// 80 quality bet 0-100 define
fos.flush();
fos.close();
File temp = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/" + "Mateco" + ".png");
temp.delete();
this.setDrawingCacheEnabled(false);
} catch (FileNotFoundException e) {
Toast.makeText(getActivity().getApplicationContext(),"FILE_NOT_FOUND_EXCEPTION "+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getActivity().getApplicationContext(),"IO_EXCEPTION "+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(
"file://"
+ Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().getApplicationContext().sendBroadcast(mediaScanIntent);
Toast.makeText(getActivity().getApplicationContext(),"Save 9",Toast.LENGTH_SHORT).show();
} else {
getActivity().getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
Toast.makeText(getActivity().getApplicationContext(),"Save 11",Toast.LENGTH_SHORT).show();
}
}
}
public void captureImage(){
// Define the file-name to save photo taken by Camera activity
String fileName = "Mateco.jpg";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
// Log.e("Intrenal Storage "+MediaStore.Images.Media.INTERNAL_CONTENT_URI.toString(),"");
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
// imageUri is the current activity attribute, define and save it for later usage
Uri imageUri = getActivity().getApplicationContext().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
/* Uri imageUri=getActivity().getApplicationContext().getContentResolver().insert( MediaStore. Images. Media. INTERNAL_CONTENT_URI,values ) ;
*/
/**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, INTENT_DATA);
Log.e("captureImage()", "state -1");
getActivity().startActivityForResult(intent, CAMERA_DATA);
Log.e("captureIma ge()", "end");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("OnActivityResult()", "1");
try {
if (requestCode == CAMERA_DATA && resultCode == getActivity().RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Log.e("OnActivityResult()", "2");
InputStream stream =getActivity().getApplicationContext(). getContentResolver().openInputStream(
data.getData());
mbkground = BitmapFactory.decodeStream(stream);
Log.e("OnActivityResult()", "2.1");
Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.e("OnActivityResult()", "2.2");
mPaintView.setBitMap(photo);
Log.e("OnActivityResult()", "3");
} else {
// Image capture failed, advise user
Log.e("OnActivityResult()", "5");
}
}catch (Exception objException){
Log.e("onActivityResult();",""+objException.getMessage());
}
}
}
Please change
getActivity().startActivityForResult(intent, CAMERA_DATA);
// this call your activity onActivityResult
to
startActivityForResult(intent, CAMERA_DATA);
// this call your Fragment onActivityResult
And your Activity result like below. super will callback your fragment onActivity resulty
#Override
protected void onActivityResult(int requestId, int responseId, Intent data) {
super.onActivityResult(requestId, responseId, data);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//to do
}
you should write this method in your activity, not in fragment.
Mr.Lockesh suggesion is right i will apply this and then after only change one variable locally to global solve the problem.
thanks to all
public String getFileName(){
return "file.jpeg" ;
}
public void captureImage(){
// Define the file-name to save photo taken by Camera activity
fileName = getFileName();
Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri(fileName)); // set the image file name
// Start the image capture intent to take photo
startActivityForResult(mIntent, CAMERA_DATA);
}
public Uri getPhotoFileUri(String fileName) {
// Get safe storage directory for photos
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Camera");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d("Camera", "failed to create directory");
}
// Return the file target for the photo based on filename
return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_DATA) {
if (resultCode == getActivity().RESULT_OK ) {
Uri takenPhotoUri = getPhotoFileUri(fileName);
// by this point we have the camera photo on disk
Bitmap photo = BitmapFactory.decodeFile(takenPhotoUri.getPath());
// Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.e("OnActivityResult()", "2.2");
mPaintView.setBitMap(photo);
Toast.makeText(getActivity().getApplicationContext(), "Image Set SuccessFully", Toast.LENGTH_SHORT).show();
// Load the taken image into a preview
/* ImageView ivPreview = (ImageView) findViewById(R.id.ivPreview);
ivPreview.setImageBitmap(takenImage);*/
} else { // Result was a failure
Toast.makeText(getActivity().getApplicationContext(), "Picture wasn't taken! or data is null", Toast.LENGTH_SHORT).show();
}
}
}

Set ImageView with selected Image from Camera or Gallery

In my Activity I want put in a ImageView a photo from camera or gallery!
From camera this code work well, while when I take an image from gallery it works until when I choose my photo! After, it don't give me it in imageview! Who can help me?
Here is it MainActivity code:
public class MainActivity extends Activity {
private Button mTakePhoto;
private ImageView mImageView;
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTakePhoto = (Button) findViewById(R.id.take_photo);
mImageView = (ImageView) findViewById(R.id.imageview);
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
mTakePhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
#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;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
setPic();
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
finish();
}
break;
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(TAG, "onResume: " + this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
}
String mCurrentPhotoPath;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storageDir = Environment.getExternalStorageDirectory() + "/uploads";
File dir = new File(storageDir);
if (!dir.exists())
dir.mkdir();
File image = new File(storageDir + "/" + imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.i(TAG, "photo path = " + mCurrentPhotoPath);
return image;
}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);
mImageView.setImageBitmap(rotatedBMP);
}
public void callCamera() {
dispatchTakePictureIntent();
}
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
}
}
Thanks,Marco
Because you have this code in your camera :
mImageView.setImageBitmap(rotatedBMP);
But you dont have it on the gallery. You should set the bitmap too in case PICK_FROM_GALLERY on your onActivityResult.
The code should be like this :
if (extras2 != null)
{
Bitmap yourImage = extras2.getParcelable("data");
//your other code
mImageView.setImageBitmap(yourImage);
}

Save two images as a single image in android

I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that??
I tried some code but it is not working.
Here is my code.
XML File:
<ImageView
android:id="#+id/innerImage"
android:layout_width="300dp"
android:layout_height="230dp"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled"
android:background="#drawable/white"/>
<Button
android:id="#+id/btnselectPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ivImage"
android:layout_alignLeft="#+id/ivImage"
android:layout_marginBottom="16dp"
android:text="#string/select_photo" />
<ImageView
android:id="#+id/ivImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled" />
<Button
android:id="#+id/btnsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/btnselectPhoto"
android:layout_alignBottom="#id/btnselectPhoto"
android:layout_alignRight="#+id/ivImage"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#id/btnselectPhoto"
android:text="#string/save" />
And here is my Java Code:
public class MainActivity extends ActionBarActivity {
private static String mTempDir;
Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call method for selecting Image
SelectImage();
}
// method for selecting image
private void SelectImage() {
// items to put in alert box
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
// Alert box
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo");
// Click Event of button
Button btn = (Button) findViewById(R.id.btnselectPhoto);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Set items in alert box
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// Start Camara
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
// Open Gallery
else if (items[item].equals("Choose from Library")) {
Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
// Cancel code
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
}
// This method is called for setting image in imageview.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final String picturePath;
ImageView iv = (ImageView) findViewById(R.id.innerImage);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv.setImageBitmap(bm);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (requestCode == 2) {
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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
// Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
saveimage(picturePath);
}
}
}
private void saveimage(String imgPath) {
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
mCurrent = "temp.png";
mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
mTopImage = BitmapFactory.decodeFile(imgPath);
mComboImage = new Canvas(mBackground);
mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
mComboImage.drawBitmap(mTopImage, 0f, 0f, null);
Button savebtn = (Button) findViewById(R.id.btnsave);
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
mBitmapDrawable = new BitmapDrawable(getResources(), mBackground);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
I worked on a similar issue once, and i solved it by putting both images in the same linear layout an creating Bitmap from that layout. Than you can just write a function to save that Bitmap where ever you want.
Here's some sample code:
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
public void combineImages(Bitmap c, Bitmap s,String loc) {
Bitmap cs = null;
int width, height = 0;
if(c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight(), null);
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(loc + tmpImg);
cs.compress(CompressFormat.PNG, 100, os);
} catch(IOException e) {
Log.e("combineImages", "problem combining images", e);
}
}
You can combine two bitmaps using this.
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
ll=(LinearLayout)findViewById(R.id.linearlayout);
//Add button in your layout and write the below code onclick of button.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/saved_picture");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
});

Categories

Resources