2016-06-27 6 views
5

У меня есть метод, чтобы повернуть изображение, но я всегда получать OutMemoryError, но мои изображения в галерее iare взяты из камеры и размера ширина 5000 ~ с телефонаAndroid изображения размера памяти ошибок

Я с измененным размером фото к ширине 1280 и высота 960

мой первый способ показать и изменить размер изображения

public static Boolean ShowImagesCapture(Context context, Uri PATH_IMAGE, ImageCropView view,int width, int height){ 

    int orientation=0; 
    Boolean success = true; 
    try { 
     Bitmap bitmap =null; 

     if (Build.VERSION.SDK_INT < 19) { 
      String selectedImagePath = getPath(PATH_IMAGE,context); 
      bitmap = BitmapFactory.decodeFile(selectedImagePath); 
      orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE)); 
     } 

     else { 
      ParcelFileDescriptor parcelFileDescriptor; 

      try { 
       parcelFileDescriptor = context.getContentResolver().openFileDescriptor(PATH_IMAGE, "r"); 
       FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); 
       bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor); 
       parcelFileDescriptor.close(); 
       orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE)); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     switch (orientation) { 

      case ExifInterface.ORIENTATION_ROTATE_180: 
       bitmap=rotateBitmap(bitmap,3,width,height); 
       view.setImageBitmap(bitmap); 

       break; 
     break; 
      case ExifInterface.ORIENTATION_ROTATE_90: 
       bitmap=rotateBitmap(bitmap,8,width,height); 
       view.setImageBitmap(bitmap); 
       break; 

      case ExifInterface.ORIENTATION_TRANSVERSE: 
       break; 

      case ExifInterface.ORIENTATION_ROTATE_270: 
       bitmap=rotateBitmap(bitmap,6,width,height); 
       view.setImageBitmap(bitmap); 
       break; 

      default: 
       view.setImageBitmap(bitmap); 

     } 

     bitmap = null; 

    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     success= false; 
    } 
    System.gc(); 
    return success; 
} 

и мой метод разворота изображения

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation,int width,int height) { 

    try { 
     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); 
       //    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(-270); 
       break; 
      default: 
       return bitmap; 
     } 



     Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false); 
     bitmap.recycle(); 
     return bmRotated; 

    } 
    catch (OutOfMemoryError e) { 
     Log.e(TAG,"Out memory Error"); 
     return null; 
    }catch (Exception e){ 
     e.printStackTrace(); 
     return null; 
    } 
} 

где моя ошибка?

* ------------------- ** ОБНОВЛЕНИЕ 27 июня 2016 года ** ------------------ - *

МОЕГО КОДА есть лучшая версия работать нормально

public static Bitmap rotateBitmap(Bitmap bitmap, int orientation,int width,int height) { 

    try { 
     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); 
       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(-270); 
       break; 
      default: 
       return bitmap; 
     } 
     Bitmap bmRotated= null; 
     try { 
      Bitmap tmp_bitmap= Bitmap.createScaledBitmap(bitmap,width,height,true); 

      bmRotated = Bitmap.createBitmap(tmp_bitmap, 0, 0, tmp_bitmap.getWidth(),tmp_bitmap.getHeight(), matrix, true); 

      bitmap.recycle(); 
     }catch (OutOfMemoryError e){ 
      e.printStackTrace(); 
     } 
     return bmRotated; 

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


public static Bitmap decodefilebitmap(String selectedImagePath, int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(selectedImagePath, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(selectedImagePath, options); 
} 

public static int calculateInSampleSize(
     BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     final int halfHeight = height/2; 
     final int halfWidth = width/2; 

     // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
     // height and width larger than the requested height and width. 
     while ((halfHeight/inSampleSize) > reqHeight 
       && (halfWidth/inSampleSize) > reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 

//METODO PARA MOSTRAR LA IMAGEN DESDE LA GALERIA 
public static Boolean ShowImagesCapture(Context context, Uri PATH_IMAGE, ImageCropView view,int width, int height){ 

    int orientation=0; 
    Boolean success = true; 
    try { 
     Bitmap bitmap =null; 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 

     if (Build.VERSION.SDK_INT < 19) { 
      String selectedImagePath = getPath(PATH_IMAGE,context); 
      bitmap = decodefilebitmap(selectedImagePath,bitmap.getWidth(),bitmap.getHeight()); 
      orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE)); 
     } 

     else { 
      ParcelFileDescriptor parcelFileDescriptor; 

      try { 
       parcelFileDescriptor = context.getContentResolver().openFileDescriptor(PATH_IMAGE, "r"); 
       FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); 
       bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor); 
       parcelFileDescriptor.close(); 
       orientation=GetPhotoOrientation(context,getRealPathFromURI(context,PATH_IMAGE)); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     switch (orientation) { 


      case ExifInterface.ORIENTATION_ROTATE_180: 
       bitmap=rotateBitmap(bitmap,3,width,height); 
       view.setImageBitmap(bitmap); 

       break; 

      case ExifInterface.ORIENTATION_ROTATE_90: 
       bitmap=rotateBitmap(bitmap,8,width,height); 
       view.setImageBitmap(bitmap); 
       break; 

      case ExifInterface.ORIENTATION_TRANSVERSE: 
       break; 

      case ExifInterface.ORIENTATION_ROTATE_270: 
       bitmap=rotateBitmap(bitmap,6,width,height); 
       view.setImageBitmap(bitmap); 
       break; 

      default: 
       view.setImageBitmap(bitmap); 

     } 

     bitmap = null; 

    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     success= false; 
    } 
    System.gc(); 
    return success; 
} 

ответ

3

Это потому, что вы загружаете все растровое изображение в память bitmap = BitmapFactory.decodeFile(selectedImagePath);, а затем показывая уменьшенную версию в ImageView (но тратить память, потому что у вас есть полные в ОЗУ). Вам нужно загрузить уменьшенную версию. Не то же самое, чтобы загружать все растровые изображения, а затем выполнять операции с ним (масштабировать, поворачивать, помещать их в изображение), чем загружать уменьшенную версию этого растрового изображения в память. Например, если у вас есть изображение размером 5000 на 5000 пикселей, предположим, что в формате JPEG его размер составляет около 1 МБ. Но когда вы загружаете его в память, вы распаковываете его и загружаете всю несжатую версию этого изображения. Предположим, что вы загружаете его в 32 бит на пиксель, тогда его размер в ОЗУ будет 5000x5000x32 бит, то есть около 95 МБ! Поэтому вам нужно загрузить уменьшенную версию. Ознакомьтесь с этим документом разработчиков Android about loading a scaled down bitmap version into memory. Это поможет вам лучше понять проблему. Вы также можете использовать библиотеки загрузки изображений, такие как Glide. Эти библиотеки делают все это и многое другое.

+0

есть и ... способ поворот изображение сначала изменение размера изображение для низкого изображения ширина и высота и после поворота изображение спасибо! – pedroooo

+0

Я обновляю решение для кода! привет – pedroooo

+0

@pedroooo Без проблем, рад, что я вам помог =). – josemgu91

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