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

标签 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);

提前致谢

最佳答案

一般情况下,你可以只写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;
    }

关于Android 从路径获取图像(图库、图片等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40768268/

相关文章:

Flutter 检查 Uint8List 是否有效 Image

android 构建 splash.9.png 错误

javascript - Android 上的初始 pageYOffset 值(是否已缓存?)

android - Android Studio 4.1 中的文件模板在哪里?

php - 从 base64_encode 调整图像大小

javascript - 向其添加 img 时 Div 改变大小

java - 在每个“回收者” View 中添加自定义布局的问题

java - Android Croperino - 裁剪副本而不是原始内容

android - 除了比较像素和字节之外,还有其他方法可以在 Android 中比较位图吗?

r - 量化灰度图像