我从SD卡加载了一个PNG文件。我用某种方法改变它,然后再保存它。我注意到保存的文件比原始文件大得多。
起初我以为是因为修改了文件。然后我用下面的代码进行了测试,结果仍然是这样。
我只是加载一个png文件,然后用另一个名称保存它。
原始文件为32KB,保存的文件为300KB。
有什么想法吗?
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
}
最佳答案
您可以通过压缩因子(质量)控制Bitmap
的大小:
Bitmap.compress(Bitmap.CompressFormat format, int quality, FileOutputStream out);
100=最大质量,0=低质量。
试着像“10”之类的来保持你的形象。
也可能是加载16位颜色的位图,然后将其保存为32位颜色,从而增大其大小。
分别检查
BitmapConfig.RGB_565
、BitmapConfig.ARGB_4444
和BitmapConfig.ARGB_8888
。编辑:
以下是如何正确加载位图:
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;
}
}
代码中:
// Bitmap.Config.RGB_565 = 16 Bit
Bitmap b = BitmapResLoader.decodeBitmapFromResource(Bitmap.Config.RGB_565, getResources(), width, height);
这样,您就可以控制如何将
Bitmap
加载到内存中(请参见Bitmap.Config
)。