Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to improve speed of BitmapFactory.decodeStream()?

Tags:

android

Obviously this is an expensive/time-consuming operation. Any way to improve this?

Bitmap bm = BitmapFactory.decodeStream((InputStream) new URL(
                                            someUrl).getContent());

I'm guessing there's really no way to avoid this relatively intense operation, but wanted to see if anyone had any tweaks they could recommend (aside from caching the actual bitmap, which for whatever reasons simply isn't relevant here)

like image 604
LuxuryMode Avatar asked Jan 10 '12 15:01

LuxuryMode


1 Answers

If you don't need the full resolution you can have it only read ever nth pixel, where n is a power of 2. You do this by setting inSampleSize on an Options object which you pass to BitmapFactory.decodeFile. You can find the sample size by just reading the meta-data from the file in a first pass by setting inJustDecodeBounds on the Options object. Aside from that - no, I don't think there's an easy way to make to go any faster than it already does.

Edit, example:

    Options opts = new Options();
    // Get bitmap dimensions before reading...
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, opts);
    int width = opts.outWidth;
    int height = opts.outHeight;
    int largerSide = Math.max(width, height);
    opts.inJustDecodeBounds = false; // This time it's for real!
    int sampleSize = ??; // Calculate your sampleSize here
    opts.inSampleSize = sampleSize;
    Bitmap bmp = BitmapFactory.decodeFile(path, opts);
like image 80
Mark Gjøl Avatar answered Oct 23 '22 05:10

Mark Gjøl