Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/image_picker/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.7.0

* Android: Fix image orientation problem (if Exif information exist in the image file)

## 0.6.0+17

* iOS: Fix a crash when user captures image from the camera with devices under iOS 11.
Expand Down
3 changes: 2 additions & 1 deletion packages/image_picker/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,6 @@ android {
}

dependencies {
api 'androidx.legacy:legacy-support-v4:1.0.0'
api 'androidx.exifinterface:exifinterface:1.0.0'
api 'androidx.core:core:1.0.2'
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package io.flutter.plugins.imagepicker;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we keep the file name the same for this PR? Renaming the file keeps the diff hard to review in Github.


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import androidx.exifinterface.media.ExifInterface;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class ExifHandler {

public ExifInterface copyExif(final String filePathOri, String filePathDest) throws IOException {

ExifInterface newExif = new ExifInterface(filePathDest);
final ExifInterface originalExif = new ExifInterface(filePathOri);
List<String> attributes =
Arrays.asList(
"FNumber",
"ExposureTime",
"ISOSpeedRatings",
"GPSAltitude",
"GPSAltitudeRef",
"FocalLength",
"GPSDateStamp",
"WhiteBalance",
"GPSProcessingMethod",
"GPSTimeStamp",
"DateTime",
"Flash",
"GPSLatitude",
"GPSLatitudeRef",
"GPSLongitude",
"GPSLongitudeRef",
"Make",
"Model",
"Orientation");

for (String attribute : attributes) {
setIfNotNull(originalExif, newExif, attribute);
}

newExif.saveAttributes();

return newExif;
}

private static void setIfNotNull(ExifInterface oldExif, ExifInterface newExif, String property) {
if (oldExif.getAttribute(property) != null) {
newExif.setAttribute(property, oldExif.getAttribute(property));
}
}

// from : https://github.com/google/cameraview/issues/22#issuecomment-363047917
public Bitmap getNormalOrientationBitmap(String imageAbsolutePath)
throws IOException {
Bitmap bitmap = BitmapFactory.decodeFile(imageAbsolutePath);
ExifInterface ei = new ExifInterface(imageAbsolutePath);

int orientation =
ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't it just be matrix.setScale(1, -1) ?

matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
}

return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

public void setNormalOrientation(ExifInterface exif) throws IOException {
exif.setAttribute(ExifInterface.TAG_ORIENTATION,
String.valueOf(ExifInterface.ORIENTATION_NORMAL));
exif.saveAttributes();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,13 @@ void retrieveLostImage(MethodChannel.Result result) {
if (path != null) {
Double maxWidth = (Double) resultMap.get(ImagePickerCache.MAP_KEY_MAX_WIDTH);
Double maxHeight = (Double) resultMap.get(ImagePickerCache.MAP_KEY_MAX_HEIGHT);
String newPath = imageResizer.resizeImageIfNeeded(path, maxWidth, maxHeight);
String newPath = null;
try {
newPath = imageResizer.normalizeImage(path, maxWidth, maxHeight);
new File(path).delete();
} catch (IOException e) {
finishWithError("failed_to_read_image", e.getMessage());
}
resultMap.put(ImagePickerCache.MAP_KEY_PATH, newPath);
}
if (resultMap.isEmpty()) {
Expand Down Expand Up @@ -509,14 +515,19 @@ private void handleImageResult(String path, boolean shouldDeleteOriginalIfScaled
if (methodCall != null) {
Double maxWidth = methodCall.argument("maxWidth");
Double maxHeight = methodCall.argument("maxHeight");
String finalImagePath = imageResizer.resizeImageIfNeeded(path, maxWidth, maxHeight);

finishWithSuccess(finalImagePath);
try {
final String finalImagePath = imageResizer.normalizeImage(path, maxWidth, maxHeight);
if (shouldDeleteOriginalIfScaled) {
new File(path).delete();
}

finishWithSuccess(finalImagePath);

//delete original file if scaled
if (!finalImagePath.equals(path) && shouldDeleteOriginalIfScaled) {
new File(path).delete();
} catch (IOException e) {
finishWithError("failed_to_read_image", e.getMessage());
}

} else {
finishWithSuccess(path);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static void registerWith(PluginRegistry.Registrar registrar) {

final File externalFilesDirectory =
registrar.activity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
final ExifDataCopier exifDataCopier = new ExifDataCopier();
final ExifHandler exifDataCopier = new ExifHandler();
final ImageResizer imageResizer = new ImageResizer(externalFilesDirectory, exifDataCopier);
final ImagePickerDelegate delegate =
new ImagePickerDelegate(registrar.activity(), externalFilesDirectory, imageResizer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,53 @@
package io.flutter.plugins.imagepicker;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import androidx.exifinterface.media.ExifInterface;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

class ImageResizer {
private final File externalFilesDirectory;
private final ExifDataCopier exifDataCopier;
private final ExifHandler exifHandler;

ImageResizer(File externalFilesDirectory, ExifDataCopier exifDataCopier) {
ImageResizer(File externalFilesDirectory, ExifHandler exifHandler) {
this.externalFilesDirectory = externalFilesDirectory;
this.exifDataCopier = exifDataCopier;
this.exifHandler = exifHandler;

}

/**
* If necessary, resizes the image located in imagePath and then returns the path for the scaled
* image.
* This method will utilize the Exif information to try to place the image in normal orientation
* and then resize it.
*
* <p>If no resizing is needed, returns the path for the original image.
* <p>This method will always apply the operations of fix and resize operation.
* returns the path for the scaled image.
* This will create a new image file for every call.
*/
String resizeImageIfNeeded(String imagePath, Double maxWidth, Double maxHeight) {
boolean shouldScale = maxWidth != null || maxHeight != null;
String normalizeImage(String imagePath, Double maxWidth, Double maxHeight) throws IOException {

if (!shouldScale) {
return imagePath;
}

try {
File scaledImage = resizedImage(imagePath, maxWidth, maxHeight);
exifDataCopier.copyExif(imagePath, scaledImage.getPath());
final Bitmap bitmap = exifHandler.getNormalOrientationBitmap(imagePath);
final File file = resizedImage(bitmap, imagePath, maxWidth, maxHeight);
final ExifInterface newExif = exifHandler.copyExif(imagePath, file.getPath());

bitmap.recycle();

exifHandler.setNormalOrientation(newExif);

return file.getPath();

return scaledImage.getPath();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private File resizedImage(String path, Double maxWidth, Double maxHeight) throws IOException {
Bitmap bmp = BitmapFactory.decodeFile(path);
private File resizedImage(
Bitmap bmp,
String path,
Double maxWidth,
Double maxHeight
) throws IOException {

double originalWidth = bmp.getWidth() * 1.0;
double originalHeight = bmp.getHeight() * 1.0;

Expand Down Expand Up @@ -85,9 +92,10 @@ private File resizedImage(String path, Double maxWidth, Double maxHeight) throws

Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, width.intValue(), height.intValue(), false);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
boolean saveAsPNG = bmp.hasAlpha();
scaledBmp.compress(
saveAsPNG ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 100, outputStream);
final boolean saveAsPNG = bmp.hasAlpha();
final CompressFormat selectedFormat = saveAsPNG ? CompressFormat.PNG : CompressFormat.JPEG;

scaledBmp.compress(selectedFormat, 100, outputStream);

String[] pathParts = path.split("/");
String imageName = pathParts[pathParts.length - 1];
Expand All @@ -96,7 +104,7 @@ private File resizedImage(String path, Double maxWidth, Double maxHeight) throws
FileOutputStream fileOutput = new FileOutputStream(imageFile);
fileOutput.write(outputStream.toByteArray());
fileOutput.close();

scaledBmp.recycle();
return imageFile;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
Expand Down Expand Up @@ -51,7 +52,7 @@ public void getFullImagePath(Uri imageUri, ImagePickerDelegate.OnPathReadyListen
}

@Before
public void setUp() {
public void setUp() throws IOException {
MockitoAnnotations.initMocks(this);

when(mockActivity.getPackageName()).thenReturn("com.example.test");
Expand All @@ -60,12 +61,12 @@ public void setUp() {
when(mockFileUtils.getPathFromUri(any(Context.class), any(Uri.class)))
.thenReturn("pathFromUri");

when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, null))
.thenReturn("originalPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", WIDTH, HEIGHT))
when(mockImageResizer.normalizeImage("pathFromUri", null, null))
.thenReturn("scaledPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", WIDTH, null)).thenReturn("scaledPath");
when(mockImageResizer.resizeImageIfNeeded("pathFromUri", null, HEIGHT))
when(mockImageResizer.normalizeImage("pathFromUri", WIDTH, HEIGHT))
.thenReturn("scaledPath");
when(mockImageResizer.normalizeImage("pathFromUri", WIDTH, null)).thenReturn("scaledPath");
when(mockImageResizer.normalizeImage("pathFromUri", null, HEIGHT))
.thenReturn("scaledPath");

mockFileUriResolver = new MockFileUriResolver();
Expand Down Expand Up @@ -282,18 +283,6 @@ public void onActivityResult_WhenPickFromGalleryCanceled_FinishesWithNull() {
verifyNoMoreInteractions(mockResult);
}

@Test
public void
onActivityResult_WhenImagePickedFromGallery_AndNoResizeNeeded_FinishesWithImagePath() {
ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall();

delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY, Activity.RESULT_OK, mockIntent);

verify(mockResult).success("originalPath");
verifyNoMoreInteractions(mockResult);
}

@Test
public void
onActivityResult_WhenImagePickedFromGallery_AndResizeNeeded_FinishesWithScaledImagePath() {
Expand Down Expand Up @@ -331,16 +320,6 @@ public void onActivityResult_WhenTakeImageWithCameraCanceled_FinishesWithNull()
verifyNoMoreInteractions(mockResult);
}

@Test
public void onActivityResult_WhenImageTakenWithCamera_AndNoResizeNeeded_FinishesWithImagePath() {
ImagePickerDelegate delegate = createDelegateWithPendingResultAndMethodCall();

delegate.onActivityResult(
ImagePickerDelegate.REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA, Activity.RESULT_OK, mockIntent);

verify(mockResult).success("originalPath");
verifyNoMoreInteractions(mockResult);
}

@Test
public void
Expand Down
Loading