由于某些图片的过大,需要上传的图片需要进行处理在进行上传,上传图片既要保证质量又要对大小进行控制:
实现步骤:
指定图片的后的最大大小和宽高;
int maxSize = 500;
float maxHeight = 1200.0f;
float maxWidth = 800.0f;
根据指定打最大宽高,保留原有比例来记性获取采样率进行压缩;
Bitmap scaledBitmap;
File imageFile = new File(filePath);
if (!imageFile.exists()) {
return null;
}
// 只解析图片的基本尺寸信息
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath,options);
// 计算图片比例 (Ratio : 比例)
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// 实际图片比例
float imgRatio = (float)actualWidth / actualHeight;
// 想要的最大图片比例
float maxRatio = maxWidth / maxHeight;
if(actualHeight == -1 || actualWidth == -1){
try {
ExifInterface exifInterface = new ExifInterface(filePath);
actualHeight = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的高度
actualWidth = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的宽度
options.outWidth = actualWidth;
options.outHeight = actualHeight;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 如果图片真实宽高里的某一个比设定的最大宽高大,才进行比例压缩
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// 计算 inSampleSize 的值
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inTempStorage = new byte[16*1024];
Bitmap bmp;
// 根据计算的 inSampleSize 的值从图片文件中提取Bitmap
try{
bmp = BitmapFactory.decodeFile(filePath,options);
}
catch(OutOfMemoryError exception){
exception.printStackTrace();
return null;
}
构建Matrix实现图片方向调整、和使用Canvas画到根据上面算出图片压缩后宽高构建的bitmap中;
// 根据实际需要的图片尺寸创建新Bitmap
try{
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
}
catch(OutOfMemoryError exception){
exception.printStackTrace();
return null;
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float)options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
// 将从图片文件中提取的Bitmap画到新创建的Bitmap中
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// 解析图片的Exif旋转信息,用于摆正图片
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
matrix.postRotate(270);
}
// 如果图片是歪的,调整方向
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
return null;
}
使用bitmap.compress进行质量压缩以控制最大大小 ,压缩的质量误差在规定最大质量的15%左右。
ByteArrayOutputStream baos = null;
FileOutputStream out = null;
try {
baos = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// 压缩比例
int compressRatio = 100;
while (approachTo(maxSize, baos.toByteArray().length) > 0) {
baos.reset();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, compressRatio,baos);
compressRatio -= 3;
}
if(compressRatio != 100)
compressRatio += 3;
if(compressRatio != 100 && approachTo(maxSize, baos.toByteArray().length) < 0){
baos.reset();
compressRatio += 1;
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, compressRatio,baos);
}
out = new FileOutputStream(outPutFilename);
baos.writeTo(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}finally {
// 关闭各种流
try {
if (out != null) out.close();
if (baos != null) baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
完整代码如下:
/**
* @param filePath 输入路径
* @param outPutFilename 输出路径
*/
public static String compressImage(String filePath, String outPutFilename) {
// 指定最大大小和最大宽高
int maxSize = 500;
float maxHeight = 1200.0f;
float maxWidth = 800.0f;
Bitmap scaledBitmap;
File imageFile = new File(filePath);
if (!imageFile.exists()) {
return null;
}
// 只解析图片的基本尺寸信息
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath,options);
// 计算图片比例 (Ratio : 比例)
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// 实际图片比例
float imgRatio = (float)actualWidth / actualHeight;
// 想要的最大图片比例
float maxRatio = maxWidth / maxHeight;
if(actualHeight == -1 || actualWidth == -1){
try {
ExifInterface exifInterface = new ExifInterface(filePath);
actualHeight = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的高度
actualWidth = exifInterface.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, ExifInterface.ORIENTATION_NORMAL);//获取图片的宽度
options.outWidth = actualWidth;
options.outHeight = actualHeight;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 如果图片真实宽高里的某一个比设定的最大宽高大,才进行比例压缩
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// 计算 inSampleSize 的值
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inTempStorage = new byte[16*1024];
Bitmap bmp;
// 根据计算的 inSampleSize 的值从图片文件中提取Bitmap
try{
bmp = BitmapFactory.decodeFile(filePath,options);
}
catch(OutOfMemoryError exception){
exception.printStackTrace();
return null;
}
// 根据实际需要的图片尺寸创建新Bitmap
try{
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
}
catch(OutOfMemoryError exception){
exception.printStackTrace();
return null;
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float)options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
// 将从图片文件中提取的Bitmap画到新创建的Bitmap中
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth()/2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// 解析图片的Exif旋转信息,用于摆正图片
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
matrix.postRotate(270);
}
// 如果图片是歪的,调整方向
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
return null;
}
ByteArrayOutputStream baos = null;
FileOutputStream out = null;
try {
baos = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// 压缩比例
int compressRatio = 100;
while (approachTo(maxSize, baos.toByteArray().length) > 0) {
baos.reset();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, compressRatio,baos);
compressRatio -= 3;
}
if(compressRatio != 100)
compressRatio += 3;
if(compressRatio != 100 && approachTo(maxSize, baos.toByteArray().length) < 0){
baos.reset();
compressRatio += 1;
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, compressRatio,baos);
}
out = new FileOutputStream(outPutFilename);
baos.writeTo(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}finally {
// 关闭各种流
try {
if (out != null) out.close();
if (baos != null) baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return outPutFilename;
}
//计算采样率
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
//因为图片压缩不能精确压缩,所以实际文件大小约等于规定大小就不压缩了, 这里默认误差 15%
private static int approachTo(int maxSize, long realSize){
double approachTopSize = maxSize * 1.15 * 1024;
double approachBottomSize = maxSize * 0.85 * 1024;
if(realSize > approachTopSize){
return 1;
}else if(realSize < approachBottomSize){
return -1;
}else{
return 0;
}
}