Image from ACTION_IMAGE_CAPTURE Rotated - java

I am trying to simply get an image from a phone's camera. Surprisingly, it returns rotated. I've scoured the internet for fixes and came across many solutions using ExifInterface, but it only works sometimes. It gets the orientation wrong seemingly randomly, as I merely recompile and see different results. I have found some people saying this is a fault of the class itself being bugged.
I found other solutions that require like two additional libraries and more java files to do the job, but that just seems ridiculous (and I am avoiding additional packages). How come images are rotated in the first place (in storage they are perfectly fine), and how hard can it possibly be to fix the issue? Also - rotating the Image View also works (and seems much easier than literally creating a rotated image), but I need to know by how much to rotate the view.
EDIT---- I realized that the image is consistently rotated 270 degrees clockwise from the orientation the image was taken in (inside the intent) if the back camera was used, and 90 degrees if the front camera was used. Thus I only really need a way to find out this orientation.
Intent called here:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = setUpPhotoFile();
mCurrentPhotoPath = photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} catch (IOException ex) {
// Error occurred while creating the File
photoFile = null;
mCurrentPhotoPath = null;
}
// Continue only if the File was successfully created
if (photoFile != null) {
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
} else {
Toast noStorage = Toast.makeText(this, "Cannot access mounted storage.", Toast.LENGTH_SHORT);
noStorage.show();
}
}
}
Bitmap created here:
private void setPic() {
/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scale = 1;
if (photoH > targetH|| photoW > targetW) {
scale = Math.max(
(int)Math.pow(2, (int) Math.ceil(Math.log(targetW /
(double) photoW)) / Math.log(0.5)),
(int)Math.pow(2, (int) Math.ceil(Math.log(targetH /
(double) photoH)) / Math.log(0.5)));
;
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scale;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
/*-----------How should I rotate bitmap/mImageView to correct orientation?*/
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
}

The best solution I have found is this one:
https://www.samieltamawy.com/how-to-fix-the-camera-intent-rotated-image-in-android/
I post the link because I don't want all the credit.
Sami Eltamawy has written a function that rotate the image if its need to be rotated.
I try the code and is working on my devices that the image got rotated.

Related

Camera Intent Image Preview Orientation

I take an image in Android using the following Code:
File image = new File(this.images_object_dir, loadedObjekt.getFilename());
Uri uri = FileProvider.getUriForFile(this, FILE_PROVIDER, image);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_ACTIVITY_CODE);
In the camera intent, the image preview is always in portrait mode on my Huawei P20 Pro. On another test-device the preview image (the one where you can decide if you wanna retake the image) is stuck in the "inital" rotation as well which looks ugly. For instance, if you want to take an image in landscape mode, the preview gets flipped to portrait mode.
Is there a solution for this?
There are ~2 billion Android devices, spread across ~20,000 device models. There are dozens, if not hundreds, of pre-installed camera apps across those device models. There are plenty of other camera apps that the user can download and install.
Your code might start any of them.
In the camera intent, the image preview is always in portrait mode on my Huawei P20 Pro
That is the behavior of that one camera app out of hundreds.
On another test-device the preview image (the one where you can decide if you wanna retake the image) is stuck in the "inital" rotation as well which looks ugly.
That is the behavior of that one camera app out of hundreds.
There is no requirement for a camera app to behave that way. Of course, there is no requirement for a camera app to have preview images at all.
Is there a solution for this?
If you wish to use ACTION_IMAGE_CAPTURE, no. The behavior of those hundreds of camera apps is up to the developers of those camera apps, not you.
There are other options for taking pictures, such as using the camera APIs directly or using third-party libraries like Fotoapparat or CameraKit-Android.
Use ExifInterface to check the orientation of the image while decoding it. Then you rotate the image to get required image in proper orientation.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap decoded = BitmapFactory.decodeFile(filePath, options);
if (decoded == null) return null;
try {
ExifInterface exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotation = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
rotation = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
rotation = 270;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
rotation = 180;
}
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap newBitmap = Bitmap.createBitmap(decoded, 0, 0, decoded.getWidth(),
decoded.getHeight(), matrix, true);
decoded.recycle();
Runtime.getRuntime().gc();
decoded = newBitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
If you want to use support library in order to support devices with lower API levels, use the following dependency:
implementation 'com.android.support:exifinterface:27.1.1'
and import android.support.media.ExifInterface

SetImageUri showing no Image

I want to let a image on my phone to show up in the Imageview. But in the ANdroid Studio emulator it is working but not on my own phone.
String imgPath = getIntent().getExtras().getString("imgPath");
System.out.println(imgPath);
if(!imgPath.equals("?"))
{
File img_file = new File(imgPath);
ImageView imgView = findViewById(R.id.show_image_war);
imgView.setImageURI(Uri.fromFile(img_file));
}
The path is /storage/emulated/0/imagesWarranty/img_MyWarranty_ID1.jpg . Both on the image in my phone and the path in my code where I get the image.
It might be issue of resolution. Even I was getting error of resolution while I was displaying image from uri.
I used below code and It worked for me :
Uri imageUri = Uri.parse(imagePath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(imageUri.getPath()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
if (imageHeight > 4096 || imageWidth > 4096) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imageUri.toString(), opts);
viewHolder.imgAvatarLogoList3.setImageBitmap(bitmap);
} else {
Picasso.with(context)
.load(new File(imageUri.getPath())) // Uri of the picture
.into(viewHolder.imgAvatarLogoList3);
}
Addition to this answer [https://stackoverflow.com/a/48354307/9255006]
In that rotation bug define the image orientation for the image using ExifInterface.
Here is the code
private void SetOrientation(){
try {
ExifInterface exif=new ExifInterface(photoURI.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_UNDEFINED);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { orientationInDegrees=90; }
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) { orientationInDegrees=180; }
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) { orientationInDegrees=270; }
else { orientationInDegrees=0; }
Toast.makeText(this, String.valueOf(orientationInDegrees), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
You can then set this orientation to your image.
This happens when the image has a very high resolution that the system needs some additional milliseconds to display, and since this happens in the UI thread onDraw() of the image view will draw it as an empty.
The easiest way I found for this issue is to use the Picasso library this way:
Picasso.get().load(imgUri).fit().centerCrop()
.into(imageview);
The reason behind those two methods (fit(), centerCrop())
Is that fit make sure that the image fit the bound container and then crop the image which force the system to redraw the image but this time with the convenient resolution (because of fit and crop).

Image losing quality and size in android?

I have an app which takes photos of receipts and upload it to a remote server.
I get the full-sized photo of the image from the camera intent correctly.I followed this using the official documentation in Google developer.
I then set my picture like this.
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.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;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
//Bitmap bitmap = null;
//try
//{
//bitmap = MediaStore.Images.Media.getBitmap(getContentResolver() , //Uri.parse(mCurrentPhotoPath));
//}
//catch (Exception e)
//{
//handle exception
//}
imageView.setImageBitmap(bitmap);
new ImageSaver(getApplicationContext()).
setFileName("currentImage.png").
setDirectoryName("Android_Upload").
save(bitmap);
Model.currentImage = "currentImage.png";
}
This works fine when viewed on the device. But after its sent to the server and viewed from there, the image size is too small.
ImageSaver class pretty much saves the image elsewhere and compresses it but with 100 quality in png.I do this, so I can later the image in the database as Blob(again with 100 quality)
How can I decode the image and show the image in the image view but without losing quality (and the size?)
Apparently, you have scaled down your image while decoding.
You may want to remove the following line:
bmOptions.inSampleSize = scaleFactor;

How to set imageview from Image Arraylist?

I am using this library but they did not explain all details like other libraries on the github.
in onCreate
ImagePicker.create(this)
.folderMode(true) // folder mode (false by default)
.folderTitle("Folder") // folder selection title
.imageTitle("Tap to select") // image selection title
.single() // single mode
// multi mode (default mode)
.limit(10) // max images can be selected (99 by default)
.showCamera(true) // show camera or not (true by default)
.imageDirectory("Camera") // directory name for captured image ("Camera" folder by default)
// original selected images, used in multi mode
.start(12); // start image picker activity with request code
It is working I can see gallery.
onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageview = (ImageView)findViewById(R.id.iv1);
if (requestCode == 12 && resultCode == RESULT_OK && data != null) {
ArrayList<Image> images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
// do your logic ....
imageview.setImageBitmap(images);//It is not working, I know it is not bitmap but how to set?
}
}
Finally how to set imageview ?
You can't set an image view to an arraylist of images, you can only set an image view to have one image as a source.
Also, looks like you are processing your images on the main thread, which is also not a good idea.
your images are in the Array, but you have to use them on multiple image views or a custom view that displays multiple images
private Bitmap getScreenshot(Image image) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
// ??????Bitmap???
Bitmap bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.RGB_565);
bitmap.copyPixelsFromBuffer(buffer);
image.close();
return bitmap;
}
Image is resource rather than a image but you can use above API to get bitmap by using ByteBuffer. Pass images.get(position) in getScreenshot(Image image). it'll return bitmap then simply set imageView.setImageBitmap(bitmap)
Example link

Bitmap Memory Error Android

I am making an Android game, but when I load my Bitmaps, I get a memory error. I know that this is caused by a very large Bitmap (it's the game background), but I don't know how I could keep from getting a "Bitmap size extends VM Budget" error. I can't rescale the Bitmap to make it smaller because I can't make the background smaller. Any suggestions?
Oh yeah, and here's the code that causes the error:
space = BitmapFactory.decodeResource(context.getResources(),
R.drawable.background);
space = Bitmap.createScaledBitmap(space,
(int) (space.getWidth() * widthRatio),
(int) (space.getHeight() * heightRatio), false);
You're going to have to sample down the image. You can't "scale" it down smaller than the screen obviously, but for small screens etc it doesn't have to be as high resolution as it is for big screens.
Long story short you have to use the inSampleSize option to downsample. It should actually be pretty easy if the image fits the screen:
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
final Display display = wm.getDefaultDisplay();
final int dimension = Math.max(display.getHeight(), display.getWidth());
final Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
InputStream bitmapStream = /* input stream for bitmap */;
BitmapFactory.decodeStream(bitmapStream, null, opt);
try
{
bitmapStream.close();
}
catch (final IOException e)
{
// ignore
}
final int imageHeight = opt.outHeight;
final int imageWidth = opt.outWidth;
int exactSampleSize = 1;
if (imageHeight > dimension || imageWidth > dimension)
{
if (imageWidth > imageHeight)
{
exactSampleSize = Math.round((float) imageHeight / (float) dimension);
}
else
{
exactSampleSize = Math.round((float) imageWidth / (float) dimension);
}
}
opt.inSampleSize = exactSampleSize; // if you find a nearest power of 2, the sampling will be more efficient... on the other hand math is hard.
opt.inJustDecodeBounds = false;
bitmapStream = /* new input stream for bitmap, make sure not to re-use the stream from above or this won't work */;
final Bitmap img = BitmapFactory.decodeStream(bitmapStream, null, opt);
/* Now go clean up your open streams... : ) */
Hope that helps.
This may help you: http://developer.android.com/training/displaying-bitmaps/index.html
From the Android Developer Website, a tutorial on how to efficiently display bitmaps + other stuff. =]
I don't understand why are you using ImageBitmap? for background. If its necessary , its okay. Otherwise please use Layout and set its background because you are using background image.
This is important. (Check Android docs. They have clearly indicated this issue.)
You can do this in following way
Drawable d = getResources().getDrawable(R.drawable.your_background);
backgroundRelativeLayout.setBackgroundDrawable(d);
In most android devices the Intent size equals 16MB. You MUST Follow these instructions Loading Large Bitmap Efficiently

Categories

Resources