2

我正在尝试显示具有绝对路径的图像。我在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);

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

4

2 回答 2

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() 。)

于 2013-01-21T05:37:01.763 回答
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);

于 2013-01-21T05:51:01.040 回答