diff --git a/packages/image_picker/CHANGELOG.md b/packages/image_picker/CHANGELOG.md index 832947312211..e3813a323b87 100644 --- a/packages/image_picker/CHANGELOG.md +++ b/packages/image_picker/CHANGELOG.md @@ -1,3 +1,8 @@ +## 0.4.0 + +* **Breaking change**. The `source` parameter for the `pickImage` is now required. Also, the `ImageSource.any` option doesn't exist anymore. +* Use the native Android image gallery for picking images instead of a custom UI. + ## 0.3.1 * Bugfix: Android version correctly asks for runtime camera permission when using `ImageSource.camera`. diff --git a/packages/image_picker/LICENSE b/packages/image_picker/LICENSE index 282a0f51aa4a..a12803666d6d 100755 --- a/packages/image_picker/LICENSE +++ b/packages/image_picker/LICENSE @@ -24,3 +24,206 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +-------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2011 - 2013 Paul Burke + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/packages/image_picker/README.md b/packages/image_picker/README.md index c9415b7aaee6..9ae87af68121 100755 --- a/packages/image_picker/README.md +++ b/packages/image_picker/README.md @@ -38,7 +38,7 @@ class _MyHomePageState extends State { File imageFile; getImage() async { - var _fileName = await ImagePicker.pickImage(); + var _fileName = await ImagePicker.pickImage(source: ImageSource.camera); setState(() { imageFile = _fileName; }); diff --git a/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java new file mode 100644 index 000000000000..ce199295cc19 --- /dev/null +++ b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ExifDataCopier.java @@ -0,0 +1,55 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.imagepicker; + +import android.media.ExifInterface; +import android.util.Log; +import java.util.Arrays; +import java.util.List; + +class ExifDataCopier { + void copyExif(String filePathOri, String filePathDest) { + try { + ExifInterface oldExif = new ExifInterface(filePathOri); + ExifInterface newExif = new ExifInterface(filePathDest); + + List 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(oldExif, newExif, attribute); + } + + newExif.saveAttributes(); + + } catch (Exception ex) { + Log.e("ExifDataCopier", "Error preserving Exif data on selected image: " + ex); + } + } + + private static void setIfNotNull(ExifInterface oldExif, ExifInterface newExif, String property) { + if (oldExif.getAttribute(property) != null) { + newExif.setAttribute(property, oldExif.getAttribute(property)); + } + } +} diff --git a/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java new file mode 100644 index 000000000000..2c2916f75fe6 --- /dev/null +++ b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/FileUtils.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2007-2008 OpenIntents.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file was modified by the Flutter authors from the following original file: + * https://raw.githubusercontent.com/iPaulPro/aFileChooser/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java + */ + +package io.flutter.plugins.imagepicker; + +import android.annotation.SuppressLint; +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.DocumentsContract; +import android.provider.MediaStore; +import android.text.TextUtils; + +class FileUtils { + private FileUtils() {} + + @SuppressLint("NewApi") + static String getPathFromUri(final Context context, final Uri uri) { + final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; + + if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { + if (isExternalStorageDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + if ("primary".equalsIgnoreCase(type)) { + return Environment.getExternalStorageDirectory() + "/" + split[1]; + } + } else if (isDownloadsDocument(uri)) { + final String id = DocumentsContract.getDocumentId(uri); + + if (!TextUtils.isEmpty(id)) { + try { + final Uri contentUri = + ContentUris.withAppendedId( + Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); + return getDataColumn(context, contentUri, null, null); + } catch (NumberFormatException e) { + return null; + } + } + + } else if (isMediaDocument(uri)) { + final String docId = DocumentsContract.getDocumentId(uri); + final String[] split = docId.split(":"); + final String type = split[0]; + + Uri contentUri = null; + if ("image".equals(type)) { + contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; + } else if ("video".equals(type)) { + contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; + } else if ("audio".equals(type)) { + contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; + } + + final String selection = "_id=?"; + final String[] selectionArgs = new String[] {split[1]}; + + return getDataColumn(context, contentUri, selection, selectionArgs); + } + } else if ("content".equalsIgnoreCase(uri.getScheme())) { + + // Return the remote address + if (isGooglePhotosUri(uri)) { + return uri.getLastPathSegment(); + } + + return getDataColumn(context, uri, null, null); + } else if ("file".equalsIgnoreCase(uri.getScheme())) { + return uri.getPath(); + } + + return null; + } + + private static String getDataColumn( + Context context, Uri uri, String selection, String[] selectionArgs) { + Cursor cursor = null; + + final String column = "_data"; + final String[] projection = {column}; + + try { + cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); + if (cursor != null && cursor.moveToFirst()) { + final int column_index = cursor.getColumnIndexOrThrow(column); + return cursor.getString(column_index); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return null; + } + + private static boolean isExternalStorageDocument(Uri uri) { + return "com.android.externalstorage.documents".equals(uri.getAuthority()); + } + + private static boolean isDownloadsDocument(Uri uri) { + return "com.android.providers.downloads.documents".equals(uri.getAuthority()); + } + + private static boolean isMediaDocument(Uri uri) { + return "com.android.providers.media.documents".equals(uri.getAuthority()); + } + + private static boolean isGooglePhotosUri(Uri uri) { + return "com.google.android.apps.photos.content".equals(uri.getAuthority()); + } +} diff --git a/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java index 6b1811f67628..5330fe6d5bde 100644 --- a/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java +++ b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerPlugin.java @@ -8,67 +8,65 @@ import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.media.ExifInterface; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; -import android.util.Log; -import com.esafirm.imagepicker.features.ImagePicker; import com.esafirm.imagepicker.features.camera.DefaultCameraModule; import com.esafirm.imagepicker.features.camera.OnImageReadyListener; import com.esafirm.imagepicker.model.Image; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry; -import io.flutter.plugin.common.PluginRegistry.ActivityResultListener; -import io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -/** ImagePicker Plugin */ public class ImagePickerPlugin - implements MethodCallHandler, ActivityResultListener, RequestPermissionsResultListener { - private static String TAG = "ImagePicker"; - private static final String CHANNEL = "image_picker"; + implements MethodChannel.MethodCallHandler, + PluginRegistry.ActivityResultListener, + PluginRegistry.RequestPermissionsResultListener { + private static final String CHANNEL = "plugins.flutter.io/image_picker"; - public static final int REQUEST_CODE_PICK = 2342; - public static final int REQUEST_CODE_CAMERA = 2343; - public static final int REQUEST_PERMISSIONS = 2345; + private static final int REQUEST_CODE_PICK = 2342; + private static final int REQUEST_CODE_CAMERA = 2343; - private static final int SOURCE_ASK_USER = 0; - private static final int SOURCE_CAMERA = 1; - private static final int SOURCE_GALLERY = 2; + private static final int REQUEST_EXTERNAL_STORAGE_PERMISSIONS = 2344; + private static final int REQUEST_CAMERA_PERMISSIONS = 2345; + + private static final int SOURCE_CAMERA = 0; + private static final int SOURCE_GALLERY = 1; private static final DefaultCameraModule cameraModule = new DefaultCameraModule(); private final PluginRegistry.Registrar registrar; + private final ImageResizer imageResizer; + private final ExifDataCopier exifDataCopier; // Pending method call to obtain an image - private Result pendingResult; + private MethodChannel.Result pendingResult; private MethodCall methodCall; public static void registerWith(PluginRegistry.Registrar registrar) { final MethodChannel channel = new MethodChannel(registrar.messenger(), CHANNEL); - final ImagePickerPlugin instance = new ImagePickerPlugin(registrar); + final ImagePickerPlugin instance = + new ImagePickerPlugin(registrar, new ImageResizer(), new ExifDataCopier()); + registrar.addActivityResultListener(instance); registrar.addRequestPermissionsResultListener(instance); + channel.setMethodCallHandler(instance); } - private ImagePickerPlugin(PluginRegistry.Registrar registrar) { + private ImagePickerPlugin( + PluginRegistry.Registrar registrar, + ImageResizer imageResizer, + ExifDataCopier exifDataCopier) { this.registrar = registrar; + this.imageResizer = imageResizer; + this.exifDataCopier = exifDataCopier; } @Override - public void onMethodCall(MethodCall call, Result result) { + public void onMethodCall(MethodCall call, MethodChannel.Result result) { if (pendingResult != null) { result.error("ALREADY_ACTIVE", "Image picker is already active", null); return; @@ -87,11 +85,8 @@ public void onMethodCall(MethodCall call, Result result) { int imageSource = call.argument("source"); switch (imageSource) { - case SOURCE_ASK_USER: - ImagePicker.create(activity).single().start(REQUEST_CODE_PICK); - break; case SOURCE_GALLERY: - ImagePicker.create(activity).single().showCamera(false).start(REQUEST_CODE_PICK); + pickImageFromGallery(activity); break; case SOURCE_CAMERA: if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) @@ -104,10 +99,12 @@ public void onMethodCall(MethodCall call, Result result) { new String[] { Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE }, - REQUEST_PERMISSIONS); + REQUEST_CAMERA_PERMISSIONS); break; } activity.startActivityForResult( + // TODO: Refactor to use the native camera. After that, remove the + // com.esafirm.imagepicker depency. cameraModule.getCameraIntent(activity), REQUEST_CODE_CAMERA); break; default: @@ -122,8 +119,8 @@ public void onMethodCall(MethodCall call, Result result) { public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_PICK) { if (resultCode == Activity.RESULT_OK && data != null) { - ArrayList images = (ArrayList) ImagePicker.getImages(data); - handleResult(images.get(0)); + String path = FileUtils.getPathFromUri(registrar.activity(), data.getData()); + handleResult(path); return true; } else if (resultCode != Activity.RESULT_CANCELED) { pendingResult.error("PICK_ERROR", "Error picking image", null); @@ -141,7 +138,7 @@ public boolean onActivityResult(int requestCode, int resultCode, Intent data) { new OnImageReadyListener() { @Override public void onImageReady(List images) { - handleResult(images.get(0)); + handleResult(images.get(0).getPath()); } }); return true; @@ -156,10 +153,35 @@ public void onImageReady(List images) { return false; } + private void pickImageFromGallery(Activity activity) { + boolean hasPermission = + ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) + == PackageManager.PERMISSION_GRANTED; + + if (hasPermission) { + Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT); + pickImageIntent.setType("image/*"); + + activity.startActivityForResult(pickImageIntent, REQUEST_CODE_PICK); + } else { + requestReadExternalStoragePermission(); + } + } + + private void requestReadExternalStoragePermission() { + ActivityCompat.requestPermissions( + registrar.activity(), + new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, + REQUEST_EXTERNAL_STORAGE_PERMISSIONS); + } + @Override public boolean onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults) { - if (requestCode == REQUEST_PERMISSIONS) { + if (requestCode == REQUEST_EXTERNAL_STORAGE_PERMISSIONS + && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + pickImageFromGallery(registrar.activity()); + } else if (requestCode == REQUEST_CAMERA_PERMISSIONS) { if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { @@ -181,18 +203,19 @@ public boolean onRequestPermissionsResult( return false; } - private void handleResult(Image image) { + private void handleResult(String path) { if (pendingResult != null) { Double maxWidth = methodCall.argument("maxWidth"); Double maxHeight = methodCall.argument("maxHeight"); boolean shouldScale = maxWidth != null || maxHeight != null; if (!shouldScale) { - pendingResult.success(image.getPath()); + pendingResult.success(path); } else { try { - File imageFile = scaleImage(image, maxWidth, maxHeight); - pendingResult.success(imageFile.getPath()); + File scaledImage = imageResizer.resizedImage(path, maxWidth, maxHeight); + exifDataCopier.copyExif(path, scaledImage.getPath()); + pendingResult.success(scaledImage.getPath()); } catch (IOException e) { throw new RuntimeException(e); } @@ -204,105 +227,4 @@ private void handleResult(Image image) { throw new IllegalStateException("Received images from picker that were not requested"); } } - - private File scaleImage(Image image, Double maxWidth, Double maxHeight) throws IOException { - Bitmap bmp = BitmapFactory.decodeFile(image.getPath()); - double originalWidth = bmp.getWidth() * 1.0; - double originalHeight = bmp.getHeight() * 1.0; - - boolean hasMaxWidth = maxWidth != null; - boolean hasMaxHeight = maxHeight != null; - - Double width = hasMaxWidth ? Math.min(originalWidth, maxWidth) : originalWidth; - Double height = hasMaxHeight ? Math.min(originalHeight, maxHeight) : originalHeight; - - boolean shouldDownscaleWidth = hasMaxWidth && maxWidth < originalWidth; - boolean shouldDownscaleHeight = hasMaxHeight && maxHeight < originalHeight; - boolean shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight; - - if (shouldDownscale) { - double downscaledWidth = (height / originalHeight) * originalWidth; - double downscaledHeight = (width / originalWidth) * originalHeight; - - if (width < height) { - if (!hasMaxWidth) { - width = downscaledWidth; - } else { - height = downscaledHeight; - } - } else if (height < width) { - if (!hasMaxHeight) { - height = downscaledHeight; - } else { - width = downscaledWidth; - } - } else { - if (originalWidth < originalHeight) { - width = downscaledWidth; - } else if (originalHeight < originalWidth) { - height = downscaledHeight; - } - } - } - - Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, width.intValue(), height.intValue(), false); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - scaledBmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); - - String scaledCopyPath = image.getPath().replace(image.getName(), "scaled_" + image.getName()); - File imageFile = new File(scaledCopyPath); - - FileOutputStream fileOutput = new FileOutputStream(imageFile); - fileOutput.write(outputStream.toByteArray()); - fileOutput.close(); - - if (shouldDownscale) { - copyExif(image.getPath(), scaledCopyPath); - } - - return imageFile; - } - - private void copyExif(String filePathOri, String filePathDest) { - try { - ExifInterface oldExif = new ExifInterface(filePathOri); - ExifInterface newExif = new ExifInterface(filePathDest); - - List 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(oldExif, newExif, attribute); - } - - newExif.saveAttributes(); - - } catch (Exception ex) { - Log.e(TAG, "Error preserving Exif data on selected image: " + ex); - } - } - - private void setIfNotNull(ExifInterface oldExif, ExifInterface newExif, String property) { - if (oldExif.getAttribute(property) != null) { - newExif.setAttribute(property, oldExif.getAttribute(property)); - } - } } diff --git a/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImageResizer.java b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImageResizer.java new file mode 100644 index 000000000000..b8f6b1ed5126 --- /dev/null +++ b/packages/image_picker/android/src/main/java/io/flutter/plugins/imagepicker/ImageResizer.java @@ -0,0 +1,70 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.imagepicker; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +class ImageResizer { + File resizedImage(String path, Double maxWidth, Double maxHeight) throws IOException { + Bitmap bmp = BitmapFactory.decodeFile(path); + double originalWidth = bmp.getWidth() * 1.0; + double originalHeight = bmp.getHeight() * 1.0; + + boolean hasMaxWidth = maxWidth != null; + boolean hasMaxHeight = maxHeight != null; + + Double width = hasMaxWidth ? Math.min(originalWidth, maxWidth) : originalWidth; + Double height = hasMaxHeight ? Math.min(originalHeight, maxHeight) : originalHeight; + + boolean shouldDownscaleWidth = hasMaxWidth && maxWidth < originalWidth; + boolean shouldDownscaleHeight = hasMaxHeight && maxHeight < originalHeight; + boolean shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight; + + if (shouldDownscale) { + double downscaledWidth = (height / originalHeight) * originalWidth; + double downscaledHeight = (width / originalWidth) * originalHeight; + + if (width < height) { + if (!hasMaxWidth) { + width = downscaledWidth; + } else { + height = downscaledHeight; + } + } else if (height < width) { + if (!hasMaxHeight) { + height = downscaledHeight; + } else { + width = downscaledWidth; + } + } else { + if (originalWidth < originalHeight) { + width = downscaledWidth; + } else if (originalHeight < originalWidth) { + height = downscaledHeight; + } + } + } + + Bitmap scaledBmp = Bitmap.createScaledBitmap(bmp, width.intValue(), height.intValue(), false); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + scaledBmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); + + String[] pathParts = path.split("/"); + String imageName = pathParts[pathParts.length - 1]; + String scaledCopyPath = path.replace(imageName, "scaled_" + imageName); + + File imageFile = new File(scaledCopyPath); + FileOutputStream fileOutput = new FileOutputStream(imageFile); + fileOutput.write(outputStream.toByteArray()); + fileOutput.close(); + + return imageFile; + } +} diff --git a/packages/image_picker/example/lib/main.dart b/packages/image_picker/example/lib/main.dart index 7756d9dc579e..d95042fa345b 100755 --- a/packages/image_picker/example/lib/main.dart +++ b/packages/image_picker/example/lib/main.dart @@ -34,6 +34,12 @@ class MyHomePage extends StatefulWidget { class _MyHomePageState extends State { Future _imageFile; + void _onImageButtonPressed(ImageSource source) { + setState(() { + _imageFile = ImagePicker.pickImage(source: source); + }); + } + @override Widget build(BuildContext context) { return new Scaffold( @@ -41,26 +47,37 @@ class _MyHomePageState extends State { title: const Text('Image Picker Example'), ), body: new Center( - child: new FutureBuilder( - future: _imageFile, - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.done && - snapshot.error == null) { - return new Image.file(snapshot.data); - } else if (snapshot.error != null) { - return const Text('error picking image.'); - } else { - return const Text('You have not yet picked an image.'); - } - })), - floatingActionButton: new FloatingActionButton( - onPressed: () { - setState(() { - _imageFile = ImagePicker.pickImage(); - }); - }, - tooltip: 'Pick Image', - child: new Icon(Icons.add_a_photo), + child: new FutureBuilder( + future: _imageFile, + builder: (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.connectionState == ConnectionState.done && + snapshot.error == null) { + return new Image.file(snapshot.data); + } else if (snapshot.error != null) { + return const Text('error picking image.'); + } else { + return const Text('You have not yet picked an image.'); + } + }, + ), + ), + floatingActionButton: new Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + new FloatingActionButton( + onPressed: () => _onImageButtonPressed(ImageSource.gallery), + tooltip: 'Pick Image from gallery', + child: new Icon(Icons.photo_library), + ), + new Padding( + padding: const EdgeInsets.only(top: 16.0), + child: new FloatingActionButton( + onPressed: () => _onImageButtonPressed(ImageSource.camera), + tooltip: 'Take a Photo', + child: new Icon(Icons.camera_alt), + ), + ), + ], ), ); } diff --git a/packages/image_picker/ios/Classes/ImagePickerPlugin.m b/packages/image_picker/ios/Classes/ImagePickerPlugin.m index 9680a718d938..ef6106b8fcc7 100644 --- a/packages/image_picker/ios/Classes/ImagePickerPlugin.m +++ b/packages/image_picker/ios/Classes/ImagePickerPlugin.m @@ -9,9 +9,8 @@ @interface FLTImagePickerPlugin () @end -static const int SOURCE_ASK_USER = 0; -static const int SOURCE_CAMERA = 1; -static const int SOURCE_GALLERY = 2; +static const int SOURCE_CAMERA = 0; +static const int SOURCE_GALLERY = 1; @implementation FLTImagePickerPlugin { FlutterResult _result; @@ -22,7 +21,7 @@ @implementation FLTImagePickerPlugin { + (void)registerWithRegistrar:(NSObject *)registrar { FlutterMethodChannel *channel = - [FlutterMethodChannel methodChannelWithName:@"image_picker" + [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/image_picker" binaryMessenger:[registrar messenger]]; UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController; @@ -58,9 +57,6 @@ - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result int imageSource = [[_arguments objectForKey:@"source"] intValue]; switch (imageSource) { - case SOURCE_ASK_USER: - [self showImageSourceSelector]; - break; case SOURCE_CAMERA: [self showCamera]; break; @@ -78,31 +74,6 @@ - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result } } -- (void)showImageSourceSelector { - UIAlertControllerStyle style = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad - ? UIAlertControllerStyleAlert - : UIAlertControllerStyleActionSheet; - - UIAlertController *alert = - [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:style]; - UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Take Photo" - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action) { - [self showCamera]; - }]; - UIAlertAction *library = [UIAlertAction actionWithTitle:@"Choose Photo" - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action) { - [self showPhotoLibrary]; - }]; - UIAlertAction *cancel = - [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]; - [alert addAction:camera]; - [alert addAction:library]; - [alert addAction:cancel]; - [_viewController presentViewController:alert animated:YES completion:nil]; -} - - (void)showCamera { // Camera is not available on simulators if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { diff --git a/packages/image_picker/lib/image_picker.dart b/packages/image_picker/lib/image_picker.dart index 65d71a57ca5c..e93912163259 100755 --- a/packages/image_picker/lib/image_picker.dart +++ b/packages/image_picker/lib/image_picker.dart @@ -6,47 +6,31 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart'; /// Specifies the source where the picked image should come from. enum ImageSource { - /// Let the user choose an image from a source they prefer. - /// - /// On Android, opens a new screen with a grid of images (from the users - /// gallery) and a camera icon on the top right corner. The user can - /// either pick an image from the image grid, or tap the camera icon - /// to take a picture using the device camera. - /// - /// On iOS, the user is presented with an alert box with options to - /// either take a photo using the device camera or pick an image from - /// the photo library. - askUser, - - /// Opens up the device camera on both Android and iOS. + /// Opens up the device camera, letting the user to take a new picture. camera, - /// On Android, presents a grid of images from the users gallery. On iOS, - /// opens the users photo library. + /// Opens the user's photo gallery. gallery, } class ImagePicker { - static const MethodChannel _channel = const MethodChannel('image_picker'); + static const MethodChannel _channel = + const MethodChannel('plugins.flutter.io/image_picker'); /// Returns a [File] object pointing to the image that was picked. /// - /// On both Android & iOS, the user can choose to either: - /// - /// * pick an image from the gallery - /// * take a photo using the device camera. - /// - /// Use the [source] argument for controlling where the image comes from. - /// By default, the user can choose the image from either camera or gallery. + /// The [source] argument controls where the image comes from. This can + /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// If specified, the image will be at most [maxWidth] wide and /// [maxHeight] tall. Otherwise the image will be returned at it's /// original width and height. static Future pickImage({ - ImageSource source = ImageSource.askUser, + @required ImageSource source, double maxWidth, double maxHeight, }) async { diff --git a/packages/image_picker/pubspec.yaml b/packages/image_picker/pubspec.yaml index 8860ae1fb3d2..6b56c4843cb9 100755 --- a/packages/image_picker/pubspec.yaml +++ b/packages/image_picker/pubspec.yaml @@ -3,7 +3,7 @@ description: Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera. author: Flutter Team homepage: https://github.com/flutter/plugins/tree/master/packages/image_picker -version: 0.3.1 +version: 0.4.0 flutter: plugin: diff --git a/packages/image_picker/test/image_picker_test.dart b/packages/image_picker/test/image_picker_test.dart index ebb3717232df..efbfa48de31c 100644 --- a/packages/image_picker/test/image_picker_test.dart +++ b/packages/image_picker/test/image_picker_test.dart @@ -8,7 +8,8 @@ import 'package:image_picker/image_picker.dart'; void main() { group('$ImagePicker', () { - const MethodChannel channel = const MethodChannel('image_picker'); + const MethodChannel channel = + const MethodChannel('plugins.flutter.io/image_picker'); final List log = []; @@ -22,23 +23,7 @@ void main() { }); group('#pickImage', () { - test('ImageSource.askUser is the default image source', () async { - await ImagePicker.pickImage(); - - expect( - log, - [ - isMethodCall('pickImage', arguments: { - 'source': 0, - 'maxWidth': null, - 'maxHeight': null, - }), - ], - ); - }); - test('passes the image source argument correctly', () async { - await ImagePicker.pickImage(source: ImageSource.askUser); await ImagePicker.pickImage(source: ImageSource.camera); await ImagePicker.pickImage(source: ImageSource.gallery); @@ -55,20 +40,22 @@ void main() { 'maxWidth': null, 'maxHeight': null, }), - isMethodCall('pickImage', arguments: { - 'source': 2, - 'maxWidth': null, - 'maxHeight': null, - }), ], ); }); test('passes the width and height arguments correctly', () async { - await ImagePicker.pickImage(); - await ImagePicker.pickImage(maxWidth: 10.0); - await ImagePicker.pickImage(maxHeight: 10.0); + await ImagePicker.pickImage(source: ImageSource.camera); + await ImagePicker.pickImage( + source: ImageSource.camera, + maxWidth: 10.0, + ); await ImagePicker.pickImage( + source: ImageSource.camera, + maxHeight: 10.0, + ); + await ImagePicker.pickImage( + source: ImageSource.camera, maxWidth: 10.0, maxHeight: 20.0, ); @@ -101,8 +88,15 @@ void main() { }); test('does not accept a negative width or height argument', () { - expect(ImagePicker.pickImage(maxWidth: -1.0), throwsArgumentError); - expect(ImagePicker.pickImage(maxHeight: -1.0), throwsArgumentError); + expect( + ImagePicker.pickImage(source: ImageSource.camera, maxWidth: -1.0), + throwsArgumentError, + ); + + expect( + ImagePicker.pickImage(source: ImageSource.camera, maxHeight: -1.0), + throwsArgumentError, + ); }); }); });