如何在android中加载url后减小图像大小?

时间:2011-11-07 07:32:57

标签: android

当图像尺寸很大时,我从网上获取图像,我收到以下错误

java.lang.OutOfMemoryError: bitmap size exceeds VM budget

我的代码如下:我正在使用LoadImageFromWebOperatins方法加载图像。

animation.addFrame(LoadImageFromWebOperations(feed.getItem(i).getImage()), 2500);
animation.addFrame(LoadImageFromWebOperations(feed.getItem(i).getImage1()), 2500); animation.setOneShot(false);

iv.setBackgroundDrawable(animation);
iv.post(new Starter());
private Drawable LoadImageFromWebOperations(String url) {
    try {

        InputStream is = (InputStream) new URL(url).getContent();

        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        System.out.println("Exc=" + e);
        return null;

    }
}

在这种情况下,我该如何解决这个错误?请为此提供解决方案。

3 个答案:

答案 0 :(得分:2)

我做了类似的事情:

private static final float MAX_IMAGE_SIZE = 800;
private static final String CURRENTLY_PROCESSED_IMAGE = "currentlyProcessedImage.jpg";
InputStream stream;
String filePath = null;
try {
    //set stream and prepare image
    stream = getContentResolver().openInputStream(data.getData());
    Uri imagePath = data.getData();
    Bitmap realImage = BitmapFactory.decodeStream(stream);

    //resize to 800x800 (proportionally)
    float ratio = Math.min( (float)MAX_IMAGE_SIZE / realImage.getWidth(), (float)MAX_IMAGE_SIZE / realImage.getHeight() );
    Log.i("PixMe", "Ratio: " + String.valueOf(ratio));
    int width = Math.round((float)ratio * realImage.getWidth());
    int height = Math.round((float)ratio * realImage.getHeight());

    //scale down the image
    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width, height, true);

    //prepare cache dir
    filePath = getFilesDir().getAbsolutePath()
        + File.separator + CURRENTLY_PROCESSED_IMAGE;
    // String filePath = Environment.getExternalStorageDirectory()
    // + File.separator + bufferPath;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    //save scaled down image to cache dir
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    File imageFile = new File(filePath);

    // write the bytes in file
    FileOutputStream fo = new FileOutputStream(imageFile);
    fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

答案 1 :(得分:2)

你可以这样实现:

   BitmapFactory.Options o = new BitmapFactory.Options();
   o.inSampleSize = 2;
   Bitmap bit = BitmapFactory.decodeStream(inputStream,null,o);
   Bitmap scaled = Bitmap.createScaledBitmap(bit, width, height, true);
   bit.recycle();

答案 2 :(得分:0)

您使用了大量图片吗?在这种情况下,请确保在每个不再可见的ImageView的每个Bitmap上调用recycle()。这为我解决了很多OOM-Exceptions。