2015-07-27 4 views
0

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

Примечание: Я проверил путь изображения он существует, и я получил следующее в LogCat /data/data/mypackagename/files/foldername/Images/MDSs2LJgLP.png

Код:

if(catVo.getImage_path() != null) 

{ 

    File location = new File(catVo.getImage_path()); 

          FileInputStream fi = new FileInputStream(location.getAbsoluteFile()); 

    Bitmap bitmap = BitmapFactory.decodeStream(fi);           
    //Bitmap bitmap = BitmapFactory.decodeFile(path); 
    categoryImage.setImageBitmap(Utils.getRoundedBitmap(bitmap)); 

} 

ответ

0

Вы можете достичь Тхи с помощью простого метода

Bitmap bitmap = BitmapFactory.decodeFile(filePath); 
mImageView.setImageBitmap(bitmap); 

Некоторые из времен BitmapFactory.decodeFile(filePath) создадут OutOfMemory ошибки вам нужно справиться с этим.

+0

Я пробовал этот метод, но значение объекта bitmap равно null – GPW

+0

Хорошо, вы проверили этот catVo.getImage_path()? Распечатайте этот путь в журнале. – Amsheer

+0

yes путь: /data/data/mypackagename/files/ имя_файла /Images/MDSs2LJgLP.png – GPW

0

Пользователь следующий метод:

public static Bitmap decodeSampledBitmap(String filePath) 
{ 

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

// Calculate inSampleSize 
options.inSampleSize = calculateInSampleSize(options, options.outWidth, 
    options.outHeight); 

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

старались не работать. – GPW

+0

Вы проверили свой путь к изображению? есть изображение есть? – chandil03

+0

Думаю, вам следует тщательно отлаживать ваш код. Это рабочий код. – chandil03

0

Используйте этот универсальный метод: - вращение, OutOfMemoryError, Желаемая выпуск Размер фиксированного/

private Bitmap getBitmap(String imagePath,int... desiredSize){ 
    try { 
     ExifInterface exif = new ExifInterface(imagePath); 
     int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL); 
     int angle = 0; 
     if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { 
      angle = 90; 
     } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) { 
      angle = 180; 
     } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) { 
      angle = 270; 
     }else if (orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL) { 
      angle=360; 
     } 
     Matrix mat = new Matrix(); 
     mat.postRotate(angle); 

     InputStream in = new FileInputStream(imagePath); 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(in, null, options); 
     in.close(); 
     in = null; 

     int inWidth = options.outWidth; 
     int inHeight = options.outHeight; 

     in = new FileInputStream(imagePath); 
     options = new BitmapFactory.Options(); 
     if(desiredSize.length>0){ 
      int desiredWidth=desiredSize[0]; 
      int desiredHeight=desiredSize[1]; 
      float tempDesiredSize[] = getScaleStr(inHeight, inWidth, desiredWidth, desiredHeight); 
      desiredWidth=(int)tempDesiredSize[0]; 
      desiredHeight=(int)tempDesiredSize[1]; 
      options.inSampleSize = Math.max(inWidth/desiredWidth, inHeight/desiredHeight); 
     }else{ 
      final int REQUIRED_SIZE = 1024; 
      int scale = 1; 
      while (true) { 
       if (inWidth/2 < REQUIRED_SIZE || inHeight/2 < REQUIRED_SIZE) { 
        break; 
       } 
       inWidth /= 2; 
       inHeight /= 2; 
       scale *= 2; 
      } 
      options.inSampleSize = scale; 
     } 
     options.inDither=true;      //Disable Dithering mode 
     options.inPurgeable=true;     //Tell to gc that whether it needs free memory, the Bitmap can be cleared 
     options.inInputShareable=true;    //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future 
     options.inTempStorage=new byte[15 * 1024 * 1024]; 
     options.inJustDecodeBounds=false; 
     options.inPreferredConfig = Config.RGB_565; 
     Bitmap srcBitmap = BitmapFactory.decodeStream(in, null, options); 
     int w = srcBitmap.getWidth(); 
     int h = srcBitmap.getHeight(); 
     srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, w, h, mat, true); 
     return srcBitmap; 
    } catch(FileNotFoundException e){ 

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