1
votes

I've created a function that scales a bitmap directly to a specific surface area. The function first gets the width and height of the bitmap and then finds the sample size closest to the required size. Lastly the image is scaled to the exact size. This is the only way I could find to decode a scaled bitmap. The problem is that the bitmap returned from BitmapFactory.createScaledBitmap(src,width,height,filter) always comes back with a width and height of -1. I've already implemented other functions that use the createScaledBitmap() method with out this error and I can not find any reason why creating a scaled bitmap would produce invalid output. I've also found that if I create a copy of the image bitmap that is mutable causes the same error. Thanks

public static Bitmap load_scaled_image( String file_name, int area) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file_name, options);
    double ratio = (float)options.outWidth / (float)options.outHeight;
    int width, height;
    if( options.outWidth > options.outHeight ) {
        width = (int)Math.sqrt(area/ratio);
        height = (int)(width*ratio);
    }
    else {
        height = (int)Math.sqrt(area/ratio);
        width = (int)(height*ratio);
    }
    BitmapFactory.Options new_options = new BitmapFactory.Options();
    new_options.inSampleSize = Math.max( (options.outWidth/width), (options.outHeight/height) );
    Bitmap image = BitmapFactory.decodeFile(file_name, new_options);
    return Bitmap.createScaledBitmap(image, width, height, true);
}

I added this function to scale large camera images to a specific number of mega pixels. So a typical area passed in would be 1000000 for 1 megapixel. The camera image after being decoded yields a outWidth of 1952 and a outHieght of 3264. I then calculate the ratio this way I can keep the same height to width ratio with the scaled image, in this case the ratio is 0.598... Using the ratio and the new surface area I can find the new width which is 773 and a height of 1293. 773x1293=999489 which is just about 1 megapixel. Next I calculate the sample size for which to decode the new image, in this case the sample size is 4 and the image is decoded to 976x1632. So I'm passing in a width of 773 a height of 1293.

1
What are typical values for inSampleSize and for width and height?EboMike

1 Answers

1
votes

I was having a similar problem (getting -1 for height and width of the scaled bitmap). Following this stackOverflow thread: Android how to create runtime thumbnail I've tried to use the same bitmap twice while calling the function:

imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, 
                                        THUMBNAIL_SIZE, false);

For some reason, this solved my problem, perhaps it would solve yours too.