/**
* 压缩图片
* @param inFile 输入文件 到文件
* @param outFile 输出目录 到目录
*/
private void compressImage(String inFile,String outFile){
int limt = 400;//最大宽高限制
String[] splitIn = inFile.split(File.separator);
String[] splitinFile = splitIn[splitIn.length-1].split("\\.");
String fileName = splitinFile[splitinFile.length-2];
String fileFormat = splitinFile[splitinFile.length-1];
Bitmap inBitmap = getBitmap(inFile, inFile.endsWith("png"));
int height = inBitmap.getHeight();
int width = inBitmap.getWidth();
boolean isNeedCompress = Math.max(height, width) > limt;
if(isNeedCompress){
//压缩
float ration = (float)limt / Math.max(height, width);
Bitmap outBitmap = zoomImg(inBitmap, ration);
inBitmap.recycle();
inBitmap = null;
System.gc();
String outImage = saveBitmap(outBitmap, outFile + fileName + "." + fileFormat, inFile.endsWith("png"));
Log.e(TAG, "compressImage: "+outImage );
}else{
//输出保存
String outImage = saveBitmap(inBitmap, outFile + fileName + "." + fileFormat, inFile.endsWith("png"));
Log.e(TAG, "compressImage: "+outImage );
}
}
/**
* 获得Bitmap
* @param imgPath
* @param isPng
* @return
*/
public Bitmap getBitmap(String imgPath,boolean isPng) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;
newOpts.inPurgeable = true;
newOpts.inInputShareable = true;
newOpts.inSampleSize = 1;
newOpts.inPreferredConfig = isPng ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
return BitmapFactory.decodeFile(imgPath, newOpts);
}
/**
* 压缩Bitmap
* @param bm
* @param f
* @return
*/
public Bitmap zoomImg(Bitmap bm, float f) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = f;
float scaleHeight = f;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
return newbm;
}
/**
* 保存Bitmap
* @param bm
* @param savePath
* @param isPng
* @return
*/
public String saveBitmap(Bitmap bm, String savePath,boolean isPng) {
Log.e(TAG, "saveBitmap: ispng"+ isPng );
File f = new File(savePath);
if (f.exists()) {
f.delete();
}
try {
FileOutputStream out = new FileOutputStream(f);
bm.compress(isPng ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
bm.recycle();
bm = null;
System.gc();
return savePath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
网友评论