【发布时间】:2013-06-01 23:46:04
【问题描述】:
我想将位图的大小精确地减小到 200kb。我从 sdcard 中获取图像,将其压缩并再次以不同的名称将其保存到 sdcard 到不同的目录中。压缩效果很好(3 mb 像图像被压缩到大约 100 kb)。为此,我编写了以下代码行:
String imagefile ="/sdcard/DCIM/100ANDRO/DSC_0530.jpg";
Bitmap bm = ShrinkBitmap(imagefile, 300, 300);
//this method compresses the image and saves into a location in sdcard
Bitmap ShrinkBitmap(String file, int width, int height){
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
//this gives the size of the compressed image in kb
long lengthbmp = imageInByte.length / 1024;
try {
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/sdcard/mediaAppPhotos/compressed_new.jpg"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
【问题讨论】:
-
更改该图像的宽度和高度..
-
你的意思是让图像变成 200x200?
-
是的,根据你想要的 200kb .. 尝试直到你得到你的结果..
-
好的,如果我给定一个恒定的宽度和高度,图像是否总是相同的大小?我已经这样做了:ShrinkBitmap(imagefile, 300, 300)
-
不,根据你的尺寸改变宽度和高度。如果你在 300*300 上得到 100kb,那么为了使尺寸为 200kb,把宽度和高度都调高。。
标签: android bitmap bitmapimage image-compression