如何显示具有该路径的图像?

时间:2013-01-21 05:18:07

标签: java android

我正在尝试显示具有绝对路径的图像。我在stackoverflow上遇到了这个代码,这在理论上应该可行,但是我在大多数图像上得到错误Bitmap too big to be uploaded into a texture所以我正在寻找另一种方法来做到这一点。令人惊讶的是,除此之外没有任何关于如何做的例子。

这就是我的尝试:

Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);                  
ImageView image = new ImageView(context);
image.setImageBitmap(myBitmap);
layout.addView(image);

顺便说一下,我正在使用的图像是使用默认的相机应用程序拍摄的,因此它们没有任何不常见的格式或大小(并且可以在图库应用程序中看到没有问题)。如何将它们添加到我的布局中?

2 个答案:

答案 0 :(得分:0)

您可能希望使用适合堆

的较小样本大小(inSampleSize

首先,创建一个适合堆的位图,可能略大于您需要的位图

BitmapFactory.Options bounds = new BitmapFactory.Options();
this.bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, bounds);
if (bounds.outWidth == -1) { // TODO: Error }
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= maxWidth && height <= maxHeight;
if (!withinBounds) {
    int newWidth = calculateNewWidth(int width, int height);
    float sampleSizeF = (float) width / (float) newWidth;
    int sampleSize = Math.round(sampleSizeF);
    BitmapFactory.Options resample = new BitmapFactory.Options();
    resample.inSampleSize = sampleSize;
    bitmap = BitmapFactory.decodeFile(filePath, resample);
}

第二步是调用Bitmap.createScaledBitmap()创建一个新的位图,以达到所需的精确分辨率。

确保在临时位图之后清理以回收其内存。 (要么让变量超出范围,让GC处理它,或者如果要加载大量图像并且在内存上运行紧张,请在其上调用.recycle()。)

答案 1 :(得分:0)

首先尝试使用下面的代码调整图片大小,然后将其设置为ImageView

 public static Drawable GetDrawable(String newFileName)
{
    File f;
    BitmapFactory.Options o2;
    Bitmap drawImage = null;
    Drawable d = null;
    try
    {           
        f = new File(newFileName);          
        //decodes image and scales it to reduce memory consumption
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;            
        o.inTempStorage = new byte[16 * 1024];          
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);            
        //The new size we want to scale to
        final int REQUIRED_SIZE = 150;          
        //Find the correct scale value. It should be the power of 2.
        int scale = 1;
        while ((o.outWidth / scale / 2 >= REQUIRED_SIZE) && (o.outHeight / scale / 2 >= REQUIRED_SIZE))
            scale *= 2;         
        //Decode with inSampleSize
        o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;            
        drawImage = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        //Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);         
        d = new BitmapDrawable(drawImage);
        //drawImage.recycle();
        //new BitmapWorkerTask          
    }
    catch (FileNotFoundException e)
    {
    }
    return d;
}

使用以下方法:

  

imageView.setImageBitmap(MYBITMAP);