jiduvah
jiduvah

Reputation: 5168

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


        return Drawable.createFromStream(is, "name");


}

Upvotes: 1

Views: 2860

Answers (3)

Romain Guy
Romain Guy

Reputation: 98501

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.

Upvotes: 4

Femi
Femi

Reputation: 64700

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

Upvotes: 0

Egor
Egor

Reputation: 40203

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!

Upvotes: 0

Related Questions