如何在安卓中使用文件路径将图像设置到imageView?

16

我正在使用浏览按钮获取图片文件路径……之后,我想使用该文件路径将该图像设置到图像视图中

4个回答

42

如果你指的是一个File对象,我会尝试:

File file = ....
Uri uri = Uri.fromFile(file);
imageView.setImageURI(uri);

Uri imageUri = Uri.parse(ImagePath); imageView.setImageURI(imageUri); ...这对我来说在除了小米Mi4之外的所有设备上都有效,你有什么想法为什么会这样。 - Avijeet
我的设备无法处理大图片(例如:1.5MB或2MB)。有没有办法压缩它(我只想显示缩略图)? - user5395084
它没有设置正确的图像尺寸,Lakshay Sharma的答案在图像尺寸方面是完美的。 - Naveen Kumar M

9
你可以尝试这段代码:
imageView.setImageBitmap(BitmapFactory.decodeFile(yourFilePath));

BitmapFactory会将给定的图像文件解码成一个Bitmap对象,然后您将该对象设置到imageView对象中。


2
这是最简单的方法。显然,如果你只返回文件而不是路径,请使用 file.getPath() 而不是 yourFilePath - user2052706

8
要从文件中设置图片,需要执行以下操作:
 File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg"); //your image file path
 mImage = (ImageView) findViewById(R.id.imageView1);
 mImage.setImageBitmap(decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250));

当调用decodeSampledBitmapFromFile函数时:

    public static Bitmap decodeSampledBitmapFromFile(String path,
        int reqWidth, int reqHeight) { // BEST QUALITY MATCH

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

    // Calculate inSampleSize
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        }

        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }


    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);
  }

您可以更改数字(在此示例中为500和250)以更改 ImageView 的位图质量。


2
从文件加载图像:
Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);

假设您的pathToPicture路径正确,您可以将此位图图像添加到ImageView中,如下所示:
ImageView imageView = (ImageView) getActivity().findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(pathToPicture));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接