开发者

Measure the Size(memory) of a Drawable

My original problem was that I was downloading a 1.3MB jpeg file and setting this as an image. This resulted in out of memory exceptions. Apparently now the server resizes the photo before I download it. However I am still getting the OOM expections. What is the easiest way to measure the size of the file that I download?

EDIT I should also mention that this runs fine on an emulator but is falling over when running on a G1

    public Drawable getImage() throws IOException, MalformedURLException {
        InputStream is = (InputStream) new java.net.URL(url).getContent();


        retu开发者_开发知识库rn Drawable.createFromStream(is, "name");


}


What matters are the dimensions of the image your are downloading/loading. The memory usage will be roughly width*height*2 bytes (or *4 bytes if the image is loaded in 32 bits.) BitmapFactory provides a way to read an image's dimensions without loading the entire image. You could use this to see how big the image is going to be in memory before loading it.


If you're doing this via streams, every Stream child (InputStream, for example) has a read method, that returns the number of read bytes. Just count those bytes and you get the size of your image. Here's a little code example:

while ((count = is.read(data)) != -1) { out.write(data, 0 , count); }

Good luck!


The OOM exceptions are probably happening because you are not recycling the Bitmap objects you're creating. When you render the image (I'm assuming in an ImageView) you probably want to do something like this:

  ImageView iv;

  // before you update the imageview with the image from the server
  if(iv.getDrawable() != null) ((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜