Toni
Toni

Reputation: 33

Loading same image in jpg and png results in different bitmap size

I'm loading two bitmaps, one in jpg and the other in png format. The image is exactly the same and saved with the same resolution: 3461x2480.

When I load the images using BitmapFactory.decodeFile() with the same scale in InSampleSize I get memory bitmaps with different sizes, jpg is slightly greater than the png. I am displaying both in a Gallery and the difference is obvious. I have printed the bitmap sizes in LogCat and verified that they have different sizes once loaded. Both images are in external storage and in the same directory.

Anyone knows why their size once loaded differ? How can I control that?

The code I'm using is:

public static Bitmap loadImageScaled(String fileName, int width, int height){

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(fileName, bmOptions);

    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    Log.d(TAG, "Image w= " + photoW + " h=" + photoH + " " + fileName);
    Log.d(TAG, "In    w= " + width + " h=" + height);

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW/width, photoH/height);
    Log.d(TAG, "scaleFactor = " + scaleFactor);

    // Decode the image file into a Bitmap
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(fileName, bmOptions);

    Log.d(TAG, "Out   w= " + bitmap.getWidth() + " h=" + bitmap.getHeight());

    return bitmap;
}

In LogCat I get this messages:

Image w= 3461 h=2480 Img09.jpg
In    w= 173 h=124
scaleFactor = 20
Out   w= 216 h=155

Image w= 3461 h=2480 Img10.png
In    w= 173 h=124
scaleFactor = 20
Out   w= 173 h=124

Any idea?

Upvotes: 3

Views: 1405

Answers (1)

zoki
zoki

Reputation: 615

Yes, it's okay i guess:) If you look in documentation (http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize) there is a note on how it works.

And if you calculate numbers you can see that 3461/216 = 16 and 3461/173 = 20. That means that png is using desired sample size, but jpg is rounding to the nearest power of 2.

Upvotes: 3

Related Questions