2016-08-24 1 views
0

Я выбор изображения для использования в качестве изображения пользователя в моем приложении, как это:Выберите изображение из средств массовой информации или облака, и поворот правильно

Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
startActivityForResult(pickPhoto, IMAGE_GALLERY); 

В onActivityResult()

if(requestCode == IMAGE_GALLERY && resultCode == RESULT_OK) { 
    Uri uri = intent.getData(); 
    if(uri != null) { 
     this.picture = Utils.ScaleBitmap(context, uri, 640); 
     userPic.setScaleType(ImageView.ScaleType.CENTER_CROP); 
     userPic.setPadding(0,0,0,0); 
     userPic.setImageBitmap(picture); 
    } 
} 

Где мой метод Utils.ScaleBitmap заключается в следующем:

try { 
     //Getting file path from URI 
     String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
     Cursor cursor = context.getContentResolver().query(imageURI, filePathColumn, null, null, null); 
     cursor.moveToFirst(); 
     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     String picturePath = cursor.getString(columnIndex); 
     cursor.close(); 

     Bitmap bitmap = BitmapFactory.decodeFile(picturePath); 

     //Getting EXIF info to rotate image 
     ExifInterface exif = null; 
     try { 
      File pictureFile = new File(picturePath); 
      exif = new ExifInterface(pictureFile.getAbsolutePath()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     int orientation = ExifInterface.ORIENTATION_NORMAL; 

     if (exif != null) 
      orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 

     switch (orientation) { 
      case ExifInterface.ORIENTATION_ROTATE_90: 
       bitmap = rotateBitmap(bitmap, 90); 
       break; 
      case ExifInterface.ORIENTATION_ROTATE_180: 
       bitmap = rotateBitmap(bitmap, 180); 
       break; 

      case ExifInterface.ORIENTATION_ROTATE_270: 
       bitmap = rotateBitmap(bitmap, 270); 
       break; 
     } 

     //Compressing image 
     int w = bitmap.getWidth(), h = bitmap.getHeight(); 
     int width, height; 
     if (w > max || h > max) { 
      if (w == h) { 
       width = height = max; 
      } else if (w < h) { 
       height = max; 
       width = max * w/h; 
      } else { 
       width = max; 
       height = max * h/w; 
      } 
     } else { 
      width = w; 
      height = h; 
     } 
     //Bitmap bitmap = ((BitmapDrawable) commentImage.getDrawable()).getBitmap(); 
     Bitmap scaledphoto = Bitmap.createScaledBitmap(bitmap, width, height, true); 
     return scaledphoto; 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

Проблема заключается в том, что этот код не работает с изображениями, которые я выбираю п как Google Диск, Picasa и т. д.

Он работал, когда я не делал все вращающиеся вещи. Это было только

Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageURI); 

И я мог выбрать любое изображение и работал. Но изображения с моей камеры ошибочно ориентировались. Теперь я исправил поворот, но не смог получить изображения из облака.

Кто-нибудь знает, как я могу заставить обе вещи работать?

Я хочу, чтобы иметь возможность выбирать изображения из облачного хранилища, а также иметь возможность вращать изображения с неправильной ориентацией.

+0

"этот код не работает с изображениями, которые я выбираю из облака, lik Google Диске, Picasa и т. д. " - в этом коде нет ничего, что связано с облаком. Вы выбираете изображения из «MediaStore», которые будут локальными. Как вы выбираете изображения из облака? – CommonsWare

+0

Когда я открываю галерею, появляется папка Picasa. И если я выполняю намерение с помощью приложения «Фото». Я могу выбрать фотографии photos.google.com. Таким образом, ACTION_PICK предназначен не только для локальных изображений. –

+0

'Файл pictureFile = new File (picturePath)' - это работает только для 'Uri' с помощью схемы' file'. Возможно, вы получаете разные схемы, такие как 'content'. Разработчики, которые используют библиотеки, такие как Picasso или Glide, получают поворот изображения, масштабирование и все это как часть библиотеки. Если вы не хотите использовать такую ​​библиотеку, используйте [exifInterface], который работает с потоками, а не с файлами] (https://commonsware.com/blog/2016/05/31/tale-two-exifinterfaces.html). – CommonsWare

ответ

0

Ваша проблема заключается в получении изображений из облака. На это уже был дан ответ. For an example look here

Я до сих пор получать растровые изображения с

bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);

мне нужны данные EXIF, а также, и ниже мой код, основанный на коде @paulburke

/** 
* Get a file path from a Uri. This will get the the path for Storage Access 
* Framework Documents, as well as the _data field for the MediaStore and 
* other file-based ContentProviders.<br> 
* <br> 
* Callers should check whether the path is local before assuming it 
* represents a local file. 
* 
* @param context The context. 
* @param uri The Uri to query. 
* @author paulburke 
*/ 
public static String getPathFromURI(final Context context, final Uri uri) { 

    if (BuildConfig.DEBUG) 
     Log.d(TAG, "Authority: " + uri.getAuthority() + 
         ", Fragment: " + uri.getFragment() + 
         ", Port: " + uri.getPort() + 
         ", Query: " + uri.getQuery() + 
         ", Scheme: " + uri.getScheme() + 
         ", Host: " + uri.getHost() + 
         ", Segments: " + uri.getPathSegments().toString()); 

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 

    // DocumentProvider 
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 
     // ExternalStorageProvider 
     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]; 
      } 

      // TODO handle non-primary volumes 
     } else if (isDownloadsDocument(uri)) { 
      // DownloadsProvider 
      final String id = DocumentsContract.getDocumentId(uri); 
      final Uri contentUri = ContentUris.withAppendedId(
        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); 

      return getDataColumn(context, contentUri, null, null); 
     } else if (isMediaDocument(uri)) { 
      // MediaProvider 
      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())) { 
     // MediaStore (and general) 

     String res = getDataColumn(context, uri, null, null); 
     // Return the remote address 
     if (res == null && isGooglePhotosUri(uri)) 
      return uri.getLastPathSegment(); 
     else 
      return res; 

    } else if ("file".equalsIgnoreCase(uri.getScheme())) { 
     // File 
     return uri.getPath(); 
    } 

    return null; 
} 

    /** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is ExternalStorageProvider. 
*/ 
public static boolean isExternalStorageDocument(Uri uri) { 
    return "com.android.externalstorage.documents".equals(uri.getAuthority()); 
} 

/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is DownloadsProvider. 
* @author paulburke 
*/ 
public static boolean isDownloadsDocument(Uri uri) { 
    return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 
} 

/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is MediaProvider. 
* @author paulburke 
*/ 
public static boolean isMediaDocument(Uri uri) { 
    return "com.android.providers.media.documents".equals(uri.getAuthority()); 
} 

/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is Google Photos. 
* @author paulburke 
*/ 
public static boolean isGooglePhotosUri(Uri uri) { 
    return "com.google.android.apps.photos.content".equals(uri.getAuthority()) || 
      "com.google.android.apps.photos.contentprovider".equals(uri.getAuthority()); 
} 

/** 
* Get the value of the data column for this Uri. This is useful for 
* MediaStore Uris, and other file-based ContentProviders. 
* 
* @param context The context. 
* @param uri The Uri to query. 
* @param selection (Optional) Filter used in the query. 
* @param selectionArgs (Optional) Selection arguments used in the query. 
* @return The value of the _data column, which is typically a file path. 
* @author paulburke 
*/ 
public static String getDataColumn(Context context, Uri uri, String selection, 
            String[] selectionArgs) { 

    final String column = "_data"; 
    final String[] projection = { column }; 

    try (Cursor cursor = 
      context.getContentResolver().query(uri, projection, selection, selectionArgs, null)) { 
     if (cursor != null && cursor.moveToFirst()) { 
      if (BuildConfig.DEBUG) 
       DatabaseUtils.dumpCursor(cursor); 

      final int column_index = cursor.getColumnIndexOrThrow(column); 
      return cursor.getString(column_index); 
     } 
    } 
    return null; 
} 

Насколько я помню Главное было выяснить, исправить его isGooglePhotosUri() метод

+0

Я уже пробовал это и не работал для облачных изображений. –

+0

Этот ответ относится к его проекту на github, я использовал код оттуда, это потребовало некоторой незначительной настройки, но в конечном итоге сработало для меня. –

+0

Не могли бы вы объяснить мне, какие у вас были настройки. –

Смежные вопросы