Issue
I load a png file from the sdcard. I alter it in someway and then save it again. I have noticed that the saved file is much larger than the original.
At first I thought it was because of modifying the file. Then I tested with the code below and still happens.
I just load a png file and then save it with another name.
The Original file is 32Kb and the Saved file is 300Kb. Any ideas?
try
{ Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/Original.png");
FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Saved.png");
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
}
catch (Exception e)
{ //Never gets here
}
Solution
You can control the size of your Bitmap
by the compress factor (quality):
Bitmap.compress(Bitmap.CompressFormat format, int quality, FileOutputStream out);
100 = maximum quality, 0 = low quality.
Try like "10" or something to keep your image smaller. It could also be that you are loading a Bitmap that is in 16-Bit color and than later save it in 32-Bit color, increasing its size.
Check BitmapConfig.RGB_565
, BitmapConfig.ARGB_4444
and BitmapConfig.ARGB_8888
respectively.
EDIT:
Here is how to load Bitmaps correctly:
public abstract class BitmapResLoader {
public static Bitmap decodeBitmapFromResource(Bitmap.Config config, Resources res, int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.inPreferredConfig = config;
return BitmapFactory.decodeResource(res, resId, options);
}
private static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
}
In code:
// Bitmap.Config.RGB_565 = 16 Bit
Bitmap b = BitmapResLoader.decodeBitmapFromResource(Bitmap.Config.RGB_565, getResources(), width, height);
That way, you can control how your Bitmap
is loaded into Memory (see Bitmap.Config
).
Answered By - Philipp Jahoda
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.