2016-11-23 130 views
1

需要从路径中获取图像。我尝试了一切,但似乎没有得到图像。

我的两个图像路径:
Android从路径中获取图像(图库,图片等)

/storage/emulated/0/DCIM/Camera/20161025_081413.jpg 
content://media/external/images/media/4828 

如何设置我的形象从这些路径?
我正在使用ImageView来显示我的图像。

我的代码:

File imgFile = new File("/storage/emulated/0/DCIM/Camera/20161025_081413.jpg"); 
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 
holder.myimage.setImageBitmap(myBitmap); 

在此先感谢

+0

你收到的一些错误,是文件存在于这条道路?检查此:http://stackoverflow.com/questions/4181774/show-image-view-from-file-path –

+0

我没有得到任何错误。路径是正确的。我没有得到图像。不知道,如果我设置正确的方式 –

+0

确保您有阅读权限:<使用权限android:name =“android.permission.READ_EXTERNAL_STORAGE”/>,也请确保文件不是很大 –

回答

0

我发现我的问题。我正在使用Android SDK 23.

来自Android文档。
如果设备运行的是Android 6.0或更高版本,并且您的应用的目标SDK为23或更高:应用必须列出清单中的权限,并且它必须在应用运行时请求所需的每个危险权限。用户可以授予或拒绝每个权限,并且即使用户拒绝权限请求,应用也可以继续以有限的功能运行。 https://developer.android.com/training/permissions/requesting.html

希望这有助于别人

+0

今天刚碰到这个! – RexSplode

1

定期,你可以只写BitmapFactory.decodeBitmap(....)等,但该文件可以是巨大的,你可以得到的OutOfMemoryError很快,特别是,如果你在一行中解码几次。因此,您需要在将图像设置为查看前压缩图像,以免内存不足。这是做到这一点的正确方法。

File f = new File(path); 
if(file.exists()){ 
Bitmap myBitmap = ImageHelper.getCompressedBitmap(photoView.getMaxWidth(), photoView.getMaxHeight(), f); 
        photoView.setImageBitmap(myBitmap); 
} 

//////////////

/** 
    * Compresses the file to make a bitmap of size, passed in arguments 
    * @param width width you want your bitmap to have 
    * @param height hight you want your bitmap to have. 
    * @param f file with image 
    * @return bitmap object of sizes, passed in arguments 
    */ 
    public static Bitmap getCompressedBitmap(int width, int height, File f) { 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(f.getAbsolutePath(), options); 

     options.inSampleSize = calculateInSampleSize(options, width, height); 
     options.inJustDecodeBounds = false; 

     return BitmapFactory.decodeFile(f.getAbsolutePath(), 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; 
    } 
+0

嗨,谢谢你的例子。我尝试过,但我仍然有同样的问题。没有图像 –

+0

您计算或使用了哪种样本量?你要求哪个宽度和高度? – greenapps

+0

我的问题是Android SDK 23有它的权限。当我解决这个问题时,我使用了你的压缩代码,它完美的工作。谢谢。你为我节省了很多工作。希望我能给你更多的赞扬。 –