繁体   English   中英

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

[英]How to reduce image size after loading from url in 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;

    }
}

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

我做了这样的事情:

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

你可以像这样实现:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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