I am trying to develop app which save image to gallery.
I want to call the camera through intent, capture images, and save it locally in the gallery
but the issue is image quality is very poor. can anyone help me figure out why?
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
if you get image from data directly, it's in bad quality
Your code is the legacy equivalent of using ActivityResultContracts.TakePicturePreview. It is specifically set up to return a low-resolution bitmap, suitable for a preview.
Instead, use ActivityResultContracts.TakePicture, and supply your destination Uri as part of the contract.
See this and this for more.
Related
I was adding a new feature to my drawing app project where users could open any picture from the phone gallery and draw on it. But I am having issues saving the new bitmap. Here are the details below :
My app has 3 activities :
Main Activity as a menu,
RecyclerView activity that acts as a gallery,
Drawing activity where users draw
Up until recently whenever a user saved an image, it would create two copies of it. One private that would be stored in application's personal storage that is not available to phone's gallery to use but is displayed in applications own gallery activity, and one public picture in media which will be displayed in the phones gallery. My gallery class checks the internal folder of the application and lists all files in it to display, that is why I also save in private app directory too. Save image method has two sections that handles the scoped storage issues with api 28+ and <28 respectively.
Recently I added a feature where users can pick any picture from phone's gallery and edit it (both images that app created and those that it did not).It uses intent picker function.
Expected results are :
Open a picture from the gallery in the drawing activity and draw on top of it
Save edited version as a new image both privately in app's storage and a public shared copy in phones main gallery
Current issues :
Image opens and is drawn upon without problems (both images made by the app and foreign pictures)
Saving images causes the app to save an empty bitmap in phones private gallery and changes (edits drawn) in shared storage on the phone without actual image that was meant to be edited.
Here is the code :
From MainActivty, code that opens the images from phone's gallery in order to edit them.
// checks permissions for reading external and scoped storage before opening image picker
private void pickAnImage() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SDK >= Q , requesting permission");
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1000);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SDK < Q , requesting permission");
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1000);
} else {
Log.d(TAG, "Permission exists, starting pick intent");
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, IMAGE);
}
}
// handles results from permissions and begins intent picker
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1000) {
Log.d(TAG, "result code good");
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Permission is granted, starting pick");
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, IMAGE);
} else {
Log.d(TAG, "While result code is good, permission was denied");
Toast.makeText(MainActivity.this, "Permission Denied !", Toast.LENGTH_SHORT).show();
}
}
}
// handles results from intent picker and feeds the image path to the drawing activity for image editing
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == IMAGE && data != null) {
Log.d(TAG, "Data from picked image is not null, creating uri and path");
Uri selectedImageUri = data.getData();
String picturePath = getPath(getApplicationContext(), selectedImageUri);
// Log.d("Picture Path", picturePath);
if (picturePath != null) {
Log.d(TAG, "Path creating success, calling art activity");
Intent intent = new Intent(getApplicationContext(), ArtActivity.class);
intent.putExtra("image", picturePath);
startActivity(intent);
} else {
Log.d(TAG, "Path was null");
finish();
}
}else{
Log.d(TAG, "Data seems to be null, aborting");
}
}
// obtains the path from the picked image
private static String getPath(Context context, Uri uri) {
String result = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(proj[0]);
result = cursor.getString(column_index);
Toast.makeText(context, "" + result, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
else {
Toast.makeText(context.getApplicationContext(), "Failed to get image path , result is null or permission problem ?", Toast.LENGTH_SHORT).show();
result = "Not found";
Toast.makeText(context, "" + result, Toast.LENGTH_SHORT).show();
}
return result;
}
Below are methods that handle bitmap editing process :
// Inside initialization method that sets up paint and bitmap objects before drawing
if (bitmap != null) {
// if bitmap object is not null it means that we are feeding existing bitmap to be edited, therefore we just scale it to screen size before giving it to canvas
loadedBitmap = scale(bitmap, width, height);
} else {
// bitmap fed to this method is null therefore it means we are not editing existing picture so we create a new object to draw on
this.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888, true);
}
Inside onDraw method that handles drawing as it happens :
if (loadedBitmap != null) {
// loadedBitmap not being null means we are editing existing image from above, we previously scaled it so now we feed it to the canvas for editing
canvas.drawBitmap(loadedBitmap, 0, 0, paintLine);
canvas.clipRect(0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight());
} else {
// we are not editing an image so we draw new empty bitmap to use
canvas.drawBitmap(bitmap, 0, 0, tPaintline);
}
And finally, here is the infamous save image method that is the root of current problems :
#SuppressLint("WrongThread") // not sure what to do otherwise about this lint
public void saveImage() throws IOException {
//create a filename and canvas
String filename = "appName" + System.currentTimeMillis();
Canvas canvas;
// loadedBitmap is the edited one, bitmap is a new one if we did not edit anything
if(loadedBitmap != null){
canvas = new Canvas(loadedBitmap);
} else{
canvas = new Canvas(bitmap);
}
// save image handle for newer api that has scoped storage and updated code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// feed all the data to content values
OutputStream fos;
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
draw(canvas);
// compress correct bitmap, loaded is edited, bitmap is new art
if(loadedBitmap != null){
loadedBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}else{
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
Objects.requireNonNull(fos).close();
imageSaved = true;
} else {
// for api older then 28 before scoped storage
// create app directory and a new image file
ContextWrapper cw = new ContextWrapper(getContext());
File directory = cw.getDir("files", Context.MODE_PRIVATE);
pathString = cw.getDir("files", Context.MODE_PRIVATE).toString();
File myPath = new File(directory, filename + ".jpg");
FileOutputStream fileOutputStream = new FileOutputStream(myPath);
// check permissions
try {
if(ContextCompat.checkSelfPermission(
context, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED){
draw(canvas);
// save edited or new bitmap to private internal storage
if(loadedBitmap != null){
MediaStore.Images.Media.insertImage(context.getContentResolver(), loadedBitmap, filename, "made with appName");
}else{
MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, filename, "made with appName");
}
// now also add a copy to shared storage so it will show up in phone's gallery
addImageToGallery(myPath.getPath(), context);
imageSaved = true;
}else{
// request permissions if not available
requestPermissions((Activity) context,
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
100);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Save image to gallery method used above :
// for old api <28, it adds the image to shared storage and phone's gallery
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
That is all, if anyone knows bitmap, canvas and permissions (old and new) feel free to help. I am sure tha changes I need are small. Check the current issues above in order to know what to look for.
I am developing an android app where user is selecting the image either from gallery or capture from camera. When user get the image from gallery i get the image uri then i pass this uri to other activity in string form. then in next activity i convert that string into uri and then uri into bitmap and set the image bitmap in imageview. Now when i capture the image from camera i get the image bitmap.
Now i want to convert this bitmap into valid uri and pass to next activity
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
System.out.println("URLLL "+selectedImage);
Log.v("PhotoActivity", "Captured image");
//Create intent
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", selectedImage.toString());
//Start Flag Display activity
startActivity(intent);
Log.v("PHOTO ACTIVITY", " uri: " + selectedImage);
}
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", photo);
//Start Flag Display activity
startActivity(intent);
}
This is how i get the uri in next activity
String imageUriString=getIntent().getStringExtra("URI");
final Uri selectedImage=Uri.parse(imageUriString);
and then convert the uri into bitmap like this
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),
selectedImage);
} catch (IOException e) {
e.printStackTrace();
bitmap=StringToBitMap(imageUriString);
}
My main goal is to convert the bitmap into uri
You write your Bitmap into the local Cache of the Application and retrieve it from there.
Bitmap photo = (Bitmap) data.getExtras().get("data");// Get the Bitmap
val file = File(context.cacheDir,"CUSTOM NAME") //Get Access to a local file.
file.delete() // Delete the File, just in Case, that there was still another File
file.createNewFile()
val fileOutputStream = file.outputStream()
val byteArrayOutputStream = ByteArrayOutputStream()
photo.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream)
val bytearray = byteArrayOutputStream.toByteArray()
fileOutputStream.write(bytearray)
fileOutputStream.flush()
fileOutputStream.close()
byteArrayOutputStream.close()
val URI = file.toURI()
Now you can send the URI to another Activity as a String and retrieve the URI from the String and get the Bitmap from the URI.
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", URI.toString());
//Start Flag Display activity
startActivity(intent);
Provide the path of image it will provide you image uri
Uri selectedImageURI = data.getData();
File imageFile = new File(getRealPathFromURI(selectedImageURI));
Uri yourUri = Uri.fromFile(f);
Use the following function so you will get image
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
Try this:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView.setImageBitmap(bitmap);
I am currently working on an activity that will let the user select an image from the gallery, and then put that image's URI into an SQLite database.
I have another activity where I take that URI and display it on an ImageView. I have this working perfectly on Lollipop and older. But anything newer it crashes when I pull up the activity that displays the image.
Here is the LOGCAT line of the crash:
Caused by: java.lang.SecurityException: Permission Denial: opening provider com.google.android.apps.photos.contentprovider.MediaContentProvider from ProcessRecord{8193e94 13574:jeremy.com.wineofmine/u0a97} (pid=13574, uid=10097) that is not exported from uid 10044
This makes it seem like a permissions thing, but I am requesting the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL STORAGE in the manifest, as well as requesting those permissions on run-time on the activity where it displays the image.
And here is the exact line where it's crashing (this is in the activity where it displays the image:)
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageURI);
And this is imageURI:
imageURI = Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE)));
//This code returns this: content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F62/ACTUAL/860591124
Here is the code to the relevant bits.
This is the intent to open up the gallery:
Intent intentGallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentGallery, SELECT_IMAGE);
And this is the onActivityResult method. The main goal of this method is to set the imageThumbail ImageView as the thumbnail, and also to set "photoURI" as the selected image's URI.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//This is if they choose an image from the gallery
if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK) {
if (requestCode == SELECT_IMAGE) {
// Get the url from data
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
Log.i("ADDACTIVITY", "Image Path : " + path);
bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
bitmapThumbnail = ThumbnailUtils.extractThumbnail(bitmap,175,175);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapThumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray = stream.toByteArray();
// Set the image in ImageView
imageThumbnail.setImageBitmap(bitmapThumbnail);
//Setting photoURI (which gets put into the database) as the gallery's image URI
photoURI = data.getData();
}
}
}
}
Any pointers to what I could be doing wrong, would be great.
I am using Camera intent to capture a photo on android, when intent from onActivityResult returns bitmap it has wrong orientation on some phones.
I know there are ways to fix this,but all the solutions I have seen talk about image stored in file.
What I am retrieving from intent is directly bitmap image. I want to know how I can get exif data of a bitmap and then correct its orientation. I repeat I have seen answers which deal with file and not bitmap, so please consider this before down voting.
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
And result is as follows
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
How to get orientation and rotate it.
UPDATE
Exif is a file format that inserts some information data to JPEG.
https://www.media.mit.edu/pia/Research/deepview/exif.html
And Bitmap is data structior data holds row pixel data, no exif info.
So I think it is impossible to get exif info from Bitmap.
There is no method to get exif info.
https://developer.android.com/reference/android/graphics/Bitmap.html
ORIGINAL
I agree with #DzMobNadjib .
I think the info of rotation is only in exif.
To take exif, I recommend you to take following steps.
1. Start camera activity with file path.
See [Save the Full-size Photo] capture of this document.
You can start the camera activity with file path.The camera activity will save the image to the file path that you passed.
2. In 'onActivityResult', Follow this answer (as #DzMobNadjib suggested)
Your code will be like this:
(Sorry I'm not tested. Please read carefuly and follow the above answer)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Uri uri = data.getData();
Bitmap bitmap = getAdjustedBitmap(uri);
}
}
}
private Bitmap getAdjustedBitmap(Uri uri) {
FileInputStream is = null;
try {
ExifInterface exif = new ExifInterface(uri.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
is = new FileInputStream(new File(uri.getPath()));
Bitmap sourceBitmap = BitmapFactory.decodeStream(is);
int width = sourceBitmap.getWidth();
int height = sourceBitmap.getHeight();
return Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return null;
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }
return 0;
}
I am developing an application in which i want to capture the image from the camera and display it in another activity in an image view, my problem is that able to capture the image but after capturing i am redirected to first activity instead to second one.
Here is my Code..
PictureOptions.java
public void buttonCameraOpen(View view)
{
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** 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_PICTURES), "Easy Heal");
// 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;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && null!=data) {
// Image captured and saved to fileUri specified in the Intent
//selectedphoto = (Bitmap) data.getExtras().get("data");
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]);
String filePath = cursor.getString(columnIndex);
File f =new File(filePath);
String filename = f.getName();
cursor.close();
selectedphoto = BitmapFactory.decodeFile(filePath);
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
//intent.putExtra("data", selectedphoto);
intent.setData( selectedImage );
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
PictureOptions.xml
<Button
android:id="#+id/buttonCameraOpen"
android:layout_width="fill_parent"
android:layout_height="72dp"
android:layout_weight="0.35"
android:onClick="buttonCameraOpen"
android:text="#string/button_camera_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Uri imageUri = getIntent().getData();
//Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageURI(imageUri);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
I finally found an awesome solution
This library is used to capture image from camera or select from gallery and return back image in File format in onActivityResult method, which can be used further in the application.
Use
EasyImage Library
Uri uriSavedImage=Uri.fromFile(new File("/sdcard/flashCropped.png"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
After clicking the image, check whether it exists or not. Then send the path to the image file to the next activity and display it via Bitmap.
Call the camera intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
then on activity for result use this
'case REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
saveBitmap(imageBitmap);
mimageView1.setImageBitmap(imageBitmap);
mIntent.putExtra("ACTIVITY_CODE", 1);
startActivity(mIntent);
break;
the add this method in ur same class
public void saveBitmap(Bitmap bmp)
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/DCIM";
try
{
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "time");
cameraUrl=file.getAbsolutePath();
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
Log.e("errr in ","inserting the image at parictular location");
}
}
then call this in ur another activity where u want the image
String valueC = getIntent().getExtras().getString("CAMERA");
Log.v("imageBitmap", ""+valueC);
Bitmap yourSelectedImageC = BitmapFactory.decodeFile(valueC);
mImgV_image.setImageBitmap(yourSelectedImageC);
I have same problem after spending 2 days finally i got the anwer
First activity
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
Intent intent= new Intent(this,SecondActivity.class);
selfiSrc.putExtra("imgurl", uri );
startActivity(intent);
}
SecondActivity
Imageview iv_photo=(ImageView)findViewById(R.id.iv_photo);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
path = (Uri) extras.get("imgurl");
iv_photo.setImageURI(path);
}
Another way see my answer
Android - how can i transfer ImageView from one activity to another activity?