1、将得到的图片path转换成Bitmap
public static Bitmap getBitmap(String filePath) {
Bitmap bitmap = null;
File file = new File(filePath);
if (file.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inPurgeable = true;
options.inInputShareable = true;
try {
bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap == null) {
file.delete();
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
bitmap = null;
}
System.gc();
}
}
return bitmap;
}
2、压缩
/**
* 压缩图片大小直至其小于100kb
* 注意:该方法是压缩图片的质量,它不会减少图片的像素,一般可用于上传大图前的处理,
* 这样就可以节省一定的流量.
* 另外它会让图片重新构造, 但是有可能图像的位深(即色深)和每个像素的透明度会变化,
* 也就是说以jpeg格式压缩后, 原来图片中透明的元素将消失.所以这种格式很可能造成失真。
* 图片确实被压缩了, 但是当重新读取压缩后的file为 Bitmap时,它占用的内存并没有改变
* <p>
* 即:(因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,
* 并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,
* 但你做成file时,它确实变小了)
*
* @param image 源Bitmap
* @return 压缩后的Bitmap
*/
public static Bitmap compressByQuality(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 90;
while (baos.toByteArray().length / 1024 > 100 && options >= 10) { //
// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//
// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//
// 把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
return bitmap;
}
public static File compressByPath(String imgPath) {
Bitmap bitmap = compressByQuality(getBitmap(imgPath));
File file = new File(imgPath);
if (bitmap != null && file.exists()) {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}