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 p_w_picpath

* @return

*/

public static Bitmap compressBmpFromBmp(Bitmap p_w_picpath)

{

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int options = 100;

p_w_picpath.compress(Bitmap.CompressFormat.JPEG, 100, baos);

// 压缩到刚好小于100kb为止

while (baos.toByteArray().length / 1024 > 100)

{

baos.reset();

options -= 10;

p_w_picpath.compress(Bitmap.CompressFormat.JPEG, options, baos);

}

ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());

Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);

return bitmap;

}

}