uu467 图片选择修改点
com.imagepicker.ImagePickerModule
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | package com.imagepicker; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.module.annotations.ReactModule; import java.io.File; import java.util.Collections; import java.util.List; import static com.imagepicker.Utils.*; @ReactModule (name = ImagePickerModule.NAME) public class ImagePickerModule extends ReactContextBaseJavaModule implements ActivityEventListener { static final String NAME = "ImagePickerManager" ; // Public to let consuming apps hook into the image picker response public static final int REQUEST_LAUNCH_IMAGE_CAPTURE = 13001 ; public static final int REQUEST_LAUNCH_VIDEO_CAPTURE = 13002 ; public static final int REQUEST_LAUNCH_LIBRARY = 13003 ; private Uri fileUri; final ReactApplicationContext reactContext; Callback callback; Options options; Uri cameraCaptureURI; public ImagePickerModule(ReactApplicationContext reactContext) { super (reactContext); this .reactContext = reactContext; this .reactContext.addActivityEventListener( this ); } @Override public String getName() { return NAME; } @ReactMethod public void launchCamera( final ReadableMap options, final Callback callback) { if (!isCameraAvailable(reactContext)) { callback.invoke(getErrorMap(errCameraUnavailable, null )); return ; } final Activity currentActivity = getCurrentActivity(); if (currentActivity == null ) { callback.invoke(getErrorMap(errOthers, "Activity error" )); return ; } if (!isCameraPermissionFulfilled(reactContext, currentActivity)) { callback.invoke(getErrorMap(errOthers, cameraPermissionDescription)); return ; } this .callback = callback; this .options = new Options(options); if ( this .options.saveToPhotos && Build.VERSION.SDK_INT <= Build.VERSION_CODES.P && !hasPermission(currentActivity)) { callback.invoke(getErrorMap(errPermission, null )); return ; } int requestCode; File file; Intent cameraIntent; if ( this .options.mediaType.equals(mediaTypeVideo)) { requestCode = REQUEST_LAUNCH_VIDEO_CAPTURE; cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, this .options.videoQuality); if ( this .options.durationLimit > 0 ) { cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, this .options.durationLimit); } file = createFile(reactContext, "mp4" ); cameraCaptureURI = createUri(file, reactContext); } else { requestCode = REQUEST_LAUNCH_IMAGE_CAPTURE; cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); file = createFile(reactContext, "jpg" ); cameraCaptureURI = createUri(file, reactContext); } if ( this .options.useFrontCamera) { System.err.println( "aaa 设置前置摄像头" ); setBackCamera(cameraIntent); } else { System.err.println( "aaa 设置后置摄像头" ); setFrontCamera(cameraIntent); } fileUri = Uri.fromFile(file); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraCaptureURI); cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); try { currentActivity.startActivityForResult(cameraIntent, requestCode); } catch (ActivityNotFoundException e) { callback.invoke(getErrorMap(errOthers, e.getMessage())); this .callback = null ; } } @ReactMethod public void launchImageLibrary( final ReadableMap options, final Callback callback) { final Activity currentActivity = getCurrentActivity(); if (currentActivity == null ) { callback.invoke(getErrorMap(errOthers, "Activity error" )); return ; } this .callback = callback; this .options = new Options(options); int requestCode; Intent libraryIntent; requestCode = REQUEST_LAUNCH_LIBRARY; boolean isSingleSelect = this .options.selectionLimit == 1 ; boolean isPhoto = this .options.mediaType.equals(mediaTypePhoto); boolean isVideo = this .options.mediaType.equals(mediaTypeVideo); if (isSingleSelect && (isPhoto || isVideo)) { libraryIntent = new Intent(Intent.ACTION_PICK); } else { libraryIntent = new Intent(Intent.ACTION_GET_CONTENT); libraryIntent.addCategory(Intent.CATEGORY_OPENABLE); } if (!isSingleSelect) { libraryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true ); } if (isPhoto) { libraryIntent.setType( "image/*" ); } else if (isVideo) { libraryIntent.setType( "video/*" ); } else { libraryIntent.setType( "*/*" ); libraryIntent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{ "image/*" , "video/*" }); } try { currentActivity.startActivityForResult(libraryIntent, requestCode); } catch (ActivityNotFoundException e) { callback.invoke(getErrorMap(errOthers, e.getMessage())); this .callback = null ; } } void onAssetsObtained(List<Uri> fileUris) { try { callback.invoke(getResponseMap(fileUris, options, reactContext)); } catch (RuntimeException exception) { callback.invoke(getErrorMap(errOthers, exception.getMessage())); } finally { callback = null ; } } @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { // onActivityResult is called even when ActivityNotFoundException occurs if (!isValidRequestCode(requestCode) || ( this .callback == null )) { return ; } if (resultCode != Activity.RESULT_OK) { if (requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE) { deleteFile(fileUri); } callback.invoke(getCancelMap()); return ; } switch (requestCode) { case REQUEST_LAUNCH_IMAGE_CAPTURE: if (options.saveToPhotos) { saveToPublicDirectory(cameraCaptureURI, reactContext, "photo" ); } onAssetsObtained(Collections.singletonList(fileUri)); break ; case REQUEST_LAUNCH_LIBRARY: onAssetsObtained(collectUrisFromData(data)); break ; case REQUEST_LAUNCH_VIDEO_CAPTURE: if (options.saveToPhotos) { saveToPublicDirectory(cameraCaptureURI, reactContext, "video" ); } onAssetsObtained(Collections.singletonList(fileUri)); break ; } } @Override public void onNewIntent(Intent intent) { } } |
if (this.options.useFrontCamera) {
System.err.println("aaa 设置前置摄像头");
setBackCamera(cameraIntent);
} else {
System.err.println("aaa 设置后置摄像头");
setFrontCamera(cameraIntent);
}
com.imagepicker.Utils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 | package com.imagepicker; import android.Manifest; import android.app.Activity; import android.content.ClipData; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.camera2.CameraCharacteristics; import android.net.Uri; import android.os.Build; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.util.Base64; import android.webkit.MimeTypeMap; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import androidx.exifinterface.media.ExifInterface; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; import static com.imagepicker.ImagePickerModule.*; public class Utils { public static String fileNamePrefix = "rn_image_picker_lib_temp_" ; public static String errCameraUnavailable = "camera_unavailable" ; public static String errPermission = "permission" ; public static String errOthers = "others" ; public static String mediaTypePhoto = "photo" ; public static String mediaTypeVideo = "video" ; public static String cameraPermissionDescription = "This library does not require Manifest.permission.CAMERA, if you add this permission in manifest then you have to obtain the same." ; public static File createFile(Context reactContext, String fileType) { try { String filename = fileNamePrefix + UUID.randomUUID() + "." + fileType; // getCacheDir will auto-clean according to android docs File fileDir = reactContext.getCacheDir(); File file = new File(fileDir, filename); file.createNewFile(); return file; } catch (Exception e) { e.printStackTrace(); return null ; } } public static Uri createUri(File file, Context reactContext) { String authority = reactContext.getApplicationContext().getPackageName() + ".imagepickerprovider" ; return FileProvider.getUriForFile(reactContext, authority, file); } public static void saveToPublicDirectory(Uri uri, Context context, String mediaType) { ContentResolver resolver = context.getContentResolver(); Uri mediaStoreUri; ContentValues fileDetails = new ContentValues(); if (mediaType.equals( "video" )) { fileDetails.put(MediaStore.Video.Media.DISPLAY_NAME, UUID.randomUUID().toString()); fileDetails.put(MediaStore.Video.Media.MIME_TYPE, resolver.getType(uri)); mediaStoreUri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, fileDetails); } else { fileDetails.put(MediaStore.Images.Media.DISPLAY_NAME, UUID.randomUUID().toString()); fileDetails.put(MediaStore.Images.Media.MIME_TYPE, resolver.getType(uri)); mediaStoreUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, fileDetails); } copyUri(uri, mediaStoreUri, resolver); } public static void copyUri(Uri fromUri, Uri toUri, ContentResolver resolver) { try { OutputStream os = resolver.openOutputStream(toUri); InputStream is = resolver.openInputStream(fromUri); byte [] buffer = new byte [ 8192 ]; int bytesRead; while ((bytesRead = is.read(buffer)) != - 1 ) { os.write(buffer, 0 , bytesRead); } } catch (IOException e) { e.printStackTrace(); } } // Make a copy of shared storage files inside app specific storage so that users can access it later. public static Uri getAppSpecificStorageUri(Uri sharedStorageUri, Context context) { if (sharedStorageUri == null ) { return null ; } ContentResolver contentResolver = context.getContentResolver(); String fileType = getFileTypeFromMime(contentResolver.getType(sharedStorageUri)); Uri toUri = Uri.fromFile(createFile(context, fileType)); copyUri(sharedStorageUri, toUri, contentResolver); return toUri; } public static boolean isCameraAvailable(Context reactContext) { return reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) || reactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY); } // Opening front camera is not officially supported in android, the below hack is obtained from various online sources public static void setFrontCamera(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra( "android.intent.extras.CAMERA_FACING" , CameraCharacteristics.LENS_FACING_FRONT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent.putExtra( "android.intent.extra.USE_FRONT_CAMERA" , true ); } } else { intent.putExtra( "android.intent.extras.CAMERA_FACING" , 1 ); } } // back public static void setBackCamera(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra( "android.intent.extras.CAMERA_FACING" , CameraCharacteristics.LENS_FACING_BACK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent.putExtra( "android.intent.extra.USE_FRONT_CAMERA" , false ); } } else { intent.putExtra( "android.intent.extras.CAMERA_FACING" , 0 ); } } public static int [] getImageDimensions(Uri uri, Context reactContext) { InputStream inputStream; try { inputStream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); return new int []{ 0 , 0 }; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true ; BitmapFactory.decodeStream(inputStream, null , options); return new int []{options.outWidth, options.outHeight}; } static boolean hasPermission( final Activity activity) { final int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); return writePermission == PackageManager.PERMISSION_GRANTED ? true : false ; } static String getBase64String(Uri uri, Context reactContext) { InputStream inputStream; try { inputStream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); return null ; } byte [] bytes; byte [] buffer = new byte [ 8192 ]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); try { while ((bytesRead = inputStream.read(buffer)) != - 1 ) { output.write(buffer, 0 , bytesRead); } } catch (IOException e) { e.printStackTrace(); } bytes = output.toByteArray(); return Base64.encodeToString(bytes, Base64.NO_WRAP); } // Resize image // When decoding a jpg to bitmap all exif meta data will be lost, so make sure to copy orientation exif to new file else image might have wrong orientations public static Uri resizeImage(Uri uri, Context context, Options options) { try { int [] origDimens = getImageDimensions(uri, context); if (!shouldResizeImage(origDimens[ 0 ], origDimens[ 1 ], options)) { return uri; } int [] newDimens = getImageDimensBasedOnConstraints(origDimens[ 0 ], origDimens[ 1 ], options); InputStream imageStream = context.getContentResolver().openInputStream(uri); String mimeType = getMimeTypeFromFileUri(uri); Bitmap b = BitmapFactory.decodeStream(imageStream); b = Bitmap.createScaledBitmap(b, newDimens[ 0 ], newDimens[ 1 ], true ); String originalOrientation = getOrientation(uri, context); File file = createFile(context, getFileTypeFromMime(mimeType)); OutputStream os = context.getContentResolver().openOutputStream(Uri.fromFile(file)); b.compress(getBitmapCompressFormat(mimeType), options.quality, os); setOrientation(file, originalOrientation, context); return Uri.fromFile(file); } catch (Exception e) { e.printStackTrace(); return uri; // cannot resize the image, return the original uri } } static String getOrientation(Uri uri, Context context) throws IOException { ExifInterface exifInterface = new ExifInterface(context.getContentResolver().openInputStream(uri)); return exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION); } // ExifInterface.saveAttributes is costly operation so don't set exif for unnecessary orientations static void setOrientation(File file, String orientation, Context context) throws IOException { if (orientation.equals(String.valueOf(ExifInterface.ORIENTATION_NORMAL)) || orientation.equals(String.valueOf(ExifInterface.ORIENTATION_UNDEFINED))) { return ; } ExifInterface exifInterface = new ExifInterface(file); exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exifInterface.saveAttributes(); } static int [] getImageDimensBasedOnConstraints( int origWidth, int origHeight, Options options) { int width = origWidth; int height = origHeight; if (options.maxWidth == 0 || options.maxHeight == 0 ) { return new int []{width, height}; } if (options.maxWidth < width) { height = ( int ) ((( float ) options.maxWidth / width) * height); width = options.maxWidth; } if (options.maxHeight < height) { width = ( int ) ((( float ) options.maxHeight / height) * width); height = options.maxHeight; } return new int []{width, height}; } static double getFileSize(Uri uri, Context context) { try { ParcelFileDescriptor f = context.getContentResolver().openFileDescriptor(uri, "r" ); return f.getStatSize(); } catch (Exception e) { e.printStackTrace(); return 0 ; } } static boolean shouldResizeImage( int origWidth, int origHeight, Options options) { if ((options.maxWidth == 0 || options.maxHeight == 0 ) && options.quality == 100 ) { return false ; } if (options.maxWidth >= origWidth && options.maxHeight >= origHeight && options.quality == 100 ) { return false ; } return true ; } static Bitmap.CompressFormat getBitmapCompressFormat(String mimeType) { switch (mimeType) { case "image/jpeg" : return Bitmap.CompressFormat.JPEG; case "image/png" : return Bitmap.CompressFormat.PNG; } return Bitmap.CompressFormat.JPEG; } static String getFileTypeFromMime(String mimeType) { if (mimeType == null ) { return "jpg" ; } switch (mimeType) { case "image/jpeg" : return "jpg" ; case "image/png" : return "png" ; case "image/gif" : return "gif" ; } return "jpg" ; } static void deleteFile(Uri uri) { new File(uri.getPath()).delete(); } static String getMimeTypeFromFileUri(Uri uri) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); } // Since library users can have many modules in their project, we should respond to onActivityResult only for our request. static boolean isValidRequestCode( int requestCode) { switch (requestCode) { case REQUEST_LAUNCH_IMAGE_CAPTURE: case REQUEST_LAUNCH_VIDEO_CAPTURE: case REQUEST_LAUNCH_LIBRARY: return true ; default : return false ; } } // This library does not require Manifest.permission.CAMERA permission, but if user app declares as using this permission which is not granted, then attempting to use ACTION_IMAGE_CAPTURE|ACTION_VIDEO_CAPTURE will result in a SecurityException. // https://issuetracker.google.com/issues/37063818 public static boolean isCameraPermissionFulfilled(Context context, Activity activity) { try { String[] declaredPermissions = context.getPackageManager() .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS) .requestedPermissions; if (declaredPermissions == null ) { return true ; } if (Arrays.asList(declaredPermissions).contains(Manifest.permission.CAMERA) && ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { return false ; } return true ; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return true ; } } static boolean isImageType(Uri uri, Context context) { return Utils.isContentType( "image/" , uri, context); } static boolean isVideoType(Uri uri, Context context) { return Utils.isContentType( "video/" , uri, context); } /** * Verifies the content typs of a file URI. A helper function * for isVideoType and isImageType * * @param contentMimeType - "video/" or "image/" * @param uri - file uri * @param context - react context * @return a boolean to determine if file is of specified content type i.e. image or video */ static boolean isContentType(String contentMimeType, Uri uri, Context context) { final String mimeType = getMimeType(uri, context); if (mimeType != null ) { return mimeType.contains(contentMimeType); } return false ; } static @Nullable String getMimeType(Uri uri, Context context) { if (uri.getScheme().equals( "file" )) { return getMimeTypeFromFileUri(uri); } ContentResolver contentResolver = context.getContentResolver(); return contentResolver.getType(uri); } static List<Uri> collectUrisFromData(Intent data) { // Default Gallery app on older Android versions doesn't support multiple image // picking and thus never uses clip data. if (data.getClipData() == null ) { return Collections.singletonList(data.getData()); } ClipData clipData = data.getClipData(); List<Uri> fileUris = new ArrayList<>(clipData.getItemCount()); for ( int i = 0 ; i < clipData.getItemCount(); ++i) { fileUris.add(clipData.getItemAt(i).getUri()); } return fileUris; } static ReadableMap getImageResponseMap(Uri uri, Options options, Context context) { String fileName = uri.getLastPathSegment(); ImageMetadata imageMetadata = new ImageMetadata(uri, context); int [] dimensions = getImageDimensions(uri, context); WritableMap map = Arguments.createMap(); map.putString( "uri" , uri.toString()); map.putDouble( "fileSize" , getFileSize(uri, context)); map.putString( "fileName" , fileName); map.putString( "type" , getMimeTypeFromFileUri(uri)); map.putInt( "width" , dimensions[ 0 ]); map.putInt( "height" , dimensions[ 1 ]); map.putString( "type" , getMimeType(uri, context)); if (options.includeBase64) { map.putString( "base64" , getBase64String(uri, context)); } if (options.includeExtra) { // Add more extra data here ... map.putString( "timestamp" , imageMetadata.getDateTime()); map.putString( "id" , fileName); } return map; } static ReadableMap getVideoResponseMap(Uri uri, Options options, Context context) { String fileName = uri.getLastPathSegment(); WritableMap map = Arguments.createMap(); VideoMetadata videoMetadata = new VideoMetadata(uri, context); map.putString( "uri" , uri.toString()); map.putDouble( "fileSize" , getFileSize(uri, context)); map.putInt( "duration" , videoMetadata.getDuration()); map.putInt( "bitrate" , videoMetadata.getBitrate()); map.putString( "fileName" , fileName); map.putString( "type" , getMimeType(uri, context)); map.putInt( "width" , videoMetadata.getWidth()); map.putInt( "height" , videoMetadata.getHeight()); if (options.includeExtra) { // Add more extra data here ... map.putString( "timestamp" , videoMetadata.getDateTime()); map.putString( "id" , fileName); } return map; } static ReadableMap getResponseMap(List<Uri> fileUris, Options options, Context context) throws RuntimeException { WritableArray assets = Arguments.createArray(); for ( int i = 0 ; i < fileUris.size(); ++i) { Uri uri = fileUris.get(i); if (isImageType(uri, context)) { if (uri.getScheme().contains( "content" )) { uri = getAppSpecificStorageUri(uri, context); } uri = resizeImage(uri, context, options); assets.pushMap(getImageResponseMap(uri, options, context)); } else if (isVideoType(uri, context)) { assets.pushMap(getVideoResponseMap(uri, options, context)); } else { throw new RuntimeException( "Unsupported file type" ); } } WritableMap response = Arguments.createMap(); response.putArray( "assets" , assets); return response; } static ReadableMap getErrorMap(String errCode, String errMsg) { WritableMap map = Arguments.createMap(); map.putString( "errorCode" , errCode); if (errMsg != null ) { map.putString( "errorMessage" , errMsg); } return map; } static ReadableMap getCancelMap() { WritableMap map = Arguments.createMap(); map.putBoolean( "didCancel" , true ); return map; } } |
// Opening front camera is not officially supported in android, the below hack is obtained from various online sources
public static void setFrontCamera(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
intent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true);
}
} else {
intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
}
}
// back
public static void setBackCamera(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
intent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_BACK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", false);
}
} else {
intent.putExtra("android.intent.extras.CAMERA_FACING", 0);
}
}
权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.front"
android:required="false" />
时刻怀有一颗虔诚之心,乐于分享。知识才更有意义。
分类:
Android_常用代码片
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决