简体   繁体   中英

How to set an image to imageView using filepath in android

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

If with File you mean a File object, I would try:

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

You can give a try to this code:

imageView.setImageBitmap(BitmapFactory.decodeFile(yourFilePath));

BitmapFactory will decode the given image file into a Bitmap object, which you will then set into the imageView object.

To set an image from a file you need to do this:

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

When 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);
  }

You can play with the numbers (500 and 250 in this case) to change the quality of the bitmap for the ImageView .

To load an image from a file:

Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);

Assuming that your pathToPicture is correct, you can then add this bitmap image to an ImageView like

ImageView imageView = (ImageView) getActivity().findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(pathToPicture));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM