Android从路径获取图像(图库,图片等)

时间:2016-11-23 15:24:46

标签: android image

需要从路径获取图像。我尝试了所有的东西,但似乎没有得到图像。

我的两个图像路径:

/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);

提前致谢

2 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:0)

我发现了我的问题。我使用的是Android SDK 23.

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

希望这有助于其他人

相关问题