1

I'm looking for a way of decoding a bitmap from file rotated (0,90,180,270 degrees). I need that because the image is big and if I decode the bitmap and then use something like

Bitmap rotatedBitmap=Bitmap.createBitmap(source, x, y, width, height, m, filter)

There is a moment when both bitmap are in memory and there is risk of running out of memory.

Any ideas? Thanks.

Addev
  • 31,819
  • 51
  • 183
  • 302

2 Answers2

1

Perhaps this is what you are looking for?

    //decodes image and scales it to reduce memory consumption
    //NOTE: if the image has dimensions which exceed int width and int height
    //its dimensions will be altered.
    private Bitmap decodeToLowResImage(byte [] b, int width, int height) {
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new ByteArrayInputStream(b), null, o);

            //The new size we want to scale to
            final int REQUIRED_SIZE_WIDTH=(int)(width*0.7);
            final int REQUIRED_SIZE_HEIGHT=(int)(height*0.7);

            //Find the correct scale value. It should be the power of 2.
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE_WIDTH || height_tmp/2<REQUIRED_SIZE_HEIGHT)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new ByteArrayInputStream(b), null, o2);
        } catch (OutOfMemoryError e) {
            //handle this
        }
        return null;
    }
Dhruv Gairola
  • 9,102
  • 5
  • 39
  • 43
  • Thanks for your answer, I dont want to reduce its size, just rotate it – Addev Mar 12 '12 at 15:23
  • If you want to rotate an image, you will have to extend ImageView class, override its onDraw method, get the canvas, apply the rotate method on the canvas, and finally use the draw method on the drawable. – Dhruv Gairola Mar 13 '12 at 04:33
0

If you wish to use an NDK based solution, I've created one here, and i've made a github project here .

this will avoid OOM by putting the data into the native C "world", recycle the old data, and return the result back, after rotation.

it doesn't require any downsampling.

Community
  • 1
  • 1
android developer
  • 114,585
  • 152
  • 739
  • 1,270