如何在android中使用filepath将图像设置为imageView

Man*_*olu 14 android

我通过使用浏览按钮获取图像的文件路径....之后我想使用文件路径将此图像设置为图像视图

rci*_*ati 37

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

File file = ....
Uri uri = Uri.fromFile(file);
imageView.setImageURI(uri);
Run Code Online (Sandbox Code Playgroud)


Ufu*_*ici 10

您可以试试这段代码:

imageView.setImageBitmap(BitmapFactory.decodeFile(yourFilePath));
Run Code Online (Sandbox Code Playgroud)

BitmapFactory会将给定的图像文件解码为Bitmap对象,然后将其设置为imageView对象.

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

Emi*_*Adz 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));
Run Code Online (Sandbox Code Playgroud)

时间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);
  }
Run Code Online (Sandbox Code Playgroud)

您可以使用数字(在这种情况下为500和250)来更改位图的质量ImageView.