public class ImageUtils
{
/**
* 從SDCard讀取圖片時壓縮
*
* @param srcPath
* @return
*/
public static Bitmap compressImageFromFile(String srcPath,
float ww, float hh )
{
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = true;// 只讀邊,不讀內容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// float hh = 800f;//
// float ww = 480f;//
int be = 1;
// 縮放到可以在480x800的屏幕上完整顯示圖片
if (w >= h && w >= ww)
{
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh)
{
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 設置採樣率
newOpts.inPreferredConfig = Config.ARGB_8888;// 該模式是默認的,可不設
newOpts.inPurgeable = true;// 同時設置纔會有效
newOpts.inInputShareable = true;// 。當系統內存不夠時候圖片自動被回收
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return bitmap;
}
/**
* 將圖片在內存中壓縮
*
* @param image
* @return
*/
public static Bitmap compressBmpFromBmp(Bitmap image)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// 壓縮到剛好小於100kb爲止
while (baos.toByteArray().length / 1024 > 100)
{
baos.reset();
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
return bitmap;
}
}