private static String CompressPngFile(InputStream is, BitmapFactory.Options newOpts, String filePath) {
newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap destBm = BitmapFactory.decodeStream(is, null, newOpts);
if (destBm == null) {
return null;
} else {
File destFile = createNewFile(filePath);
// 创建文件输出流
OutputStream os = null;
try {
os = new FileOutputStream(destFile);
// 存储
int rate = 100;
destBm.compress(CompressFormat.PNG, rate, os);
} catch (Exception e) {
filePath = null;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
return filePath;
}
}
public static String compressImage(Context context, String srcPath, String destPath, int maxW, int maxH) {
InputStream is = null;
try {
File f = new File(srcPath);
BitmapFactory.Options newOpts = getSizeOpt(f, maxW, maxH);
is = new FileInputStream(f);
return CompressPngFile(is, newOpts, destPath);
} catch (Exception e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return null;
}
/**
* 先压缩图片大小
* @param is
* @param maxSize
* @return
* @throws IOException
*/
public static BitmapFactory.Options getSizeOpt(File file, int maxWidth, int maxHeight) throws IOException {
// 对图片进行压缩,是在读取的过程中进行压缩,而不是把图片读进了内存再进行压缩
BitmapFactory.Options newOpts = new BitmapFactory.Options();
InputStream is = new FileInputStream(file);
double ratio = getOptRatio(is, maxWidth, maxHeight);
is.close();
newOpts.inSampleSize = (int) ratio;
newOpts.inJustDecodeBounds = true;
is = new FileInputStream(file);
BitmapFactory.decodeStream(is, null, newOpts);
is.close();
int loopcnt = 0;
while (newOpts.outWidth > maxWidth) {
newOpts.inSampleSize += 1;
is = new FileInputStream(file);
BitmapFactory.decodeStream(is, null, newOpts);
is.close();
if(loopcnt>3) break;
loopcnt++;
}
newOpts.inJustDecodeBounds = false;
return newOpts;
}
/**
* 计算起始压缩比例
* 先根据实际图片大小估算出最接近目标大小的压缩比例
* 减少循环压缩的次数
* @param is
* @param maxLength
* @return
*/
public static double getOptRatio(InputStream is, int maxWidth, int maxHeight) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, opts);
int srcWidth = opts.outWidth;
int srcHeight = opts.outHeight;
int destWidth = 0;
int destHeight = 0;
// 缩放的比例
double ratio = 1.0;
double ratio_w = 0.0;
double ratio_h = 0.0;
// 按比例计算缩放后的图片大小,maxLength是长或宽允许的最大长度
if (srcWidth <= maxWidth && srcHeight <= maxHeight) {
return ratio; //小于屏幕尺寸时,不压缩
}
if (srcWidth > srcHeight) {
ratio_w = srcWidth / maxWidth;
ratio_h = srcHeight / maxHeight;
} else {
ratio_w = srcHeight / maxWidth;
ratio_h = srcWidth / maxHeight;
}
if (ratio_w > ratio_h) {
ratio = ratio_w;
} else {
ratio = ratio_h;
}
return ratio;
}