Android 圖片壓縮 多種方式組合壓縮 不失真

由于某些圖片的過大,需要上傳的圖片需要進(jìn)行處理在進(jìn)行上傳,上傳圖片既要保證質(zhì)量又要對大小進(jìn)行控制:

實(shí)現(xiàn)步驟:

? ??指定圖片的后的最大大小和寬高;

? ? ? ? int maxSize = 500;

? ? ? ? float maxHeight = 1200.0f;

? ? ? ? float maxWidth = 800.0f;

? ??根據(jù)指定打最大寬高,保留原有比例來記性獲取采樣率進(jìn)行壓縮;

????????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);

? ? ? ? // 計(jì)算圖片比例? (Ratio : 比例)

? ? ? ? int actualHeight = options.outHeight;

? ? ? ? int actualWidth = options.outWidth;

? ? ? ? // 實(shí)際圖片比例

? ? ? ? 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;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? // 如果圖片真實(shí)寬高里的某一個(gè)比設(shè)定的最大寬高大,才進(jìn)行比例壓縮

? ? ? ? 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;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? // 計(jì)算 inSampleSize 的值

? ? ? ? options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

? ? ? ? options.inJustDecodeBounds = false;

? ? ? ? options.inDither = false;

? ? ? ? options.inTempStorage = new byte[16*1024];

? ? ? ? Bitmap bmp;

? ? ? ? // 根據(jù)計(jì)算的 inSampleSize 的值從圖片文件中提取Bitmap

? ? ? ? try{

? ? ? ? ? ? bmp = BitmapFactory.decodeFile(filePath,options);

? ? ? ? }

? ? ? ? catch(OutOfMemoryError exception){

? ? ? ? ? ? exception.printStackTrace();

? ? ? ? ? ? return null;

? ? ? ? }

? ??構(gòu)建Matrix實(shí)現(xiàn)圖片方向調(diào)整、和使用Canvas畫到根據(jù)上面算出圖片壓縮后寬高構(gòu)建的bitmap中;

? ? ? ?// 根據(jù)實(shí)際需要的圖片尺寸創(chuàng)建新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畫到新創(chuàng)建的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旋轉(zhuǎn)信息,用于擺正圖片

? ? ? ? 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);

? ? ? ? ? ? }

? ? ? ? ? ? // 如果圖片是歪的,調(diào)整方向

? ? ? ? ? ? scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

? ? ? ? } catch (IOException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? return null;

? ? ? ? }

????使用bitmap.compress進(jìn)行質(zhì)量壓縮以控制最大大小 ,壓縮的質(zhì)量誤差在規(guī)定最大質(zhì)量的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 {

? ? ? ? ? ? // 關(guān)閉各種流

? ? ? ? ? ? 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);

? ? ? ? // 計(jì)算圖片比例? (Ratio : 比例)

? ? ? ? int actualHeight = options.outHeight;

? ? ? ? int actualWidth = options.outWidth;

? ? ? ? // 實(shí)際圖片比例

? ? ? ? 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;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? // 如果圖片真實(shí)寬高里的某一個(gè)比設(shè)定的最大寬高大,才進(jìn)行比例壓縮

? ? ? ? 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;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? // 計(jì)算 inSampleSize 的值

? ? ? ? options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

? ? ? ? options.inJustDecodeBounds = false;

? ? ? ? options.inDither = false;

? ? ? ? options.inTempStorage = new byte[16*1024];

? ? ? ? Bitmap bmp;

? ? ? ? // 根據(jù)計(jì)算的 inSampleSize 的值從圖片文件中提取Bitmap

? ? ? ? try{

? ? ? ? ? ? bmp = BitmapFactory.decodeFile(filePath,options);

? ? ? ? }

? ? ? ? catch(OutOfMemoryError exception){

? ? ? ? ? ? exception.printStackTrace();

? ? ? ? ? ? return null;

? ? ? ? }

?????????// 根據(jù)實(shí)際需要的圖片尺寸創(chuàng)建新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畫到新創(chuàng)建的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旋轉(zhuǎn)信息,用于擺正圖片

? ? ? ? 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);

? ? ? ? ? ? }

? ? ? ? ? ? // 如果圖片是歪的,調(diào)整方向

? ? ? ? ? ? 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 {

? ? ? ? ? ? // 關(guān)閉各種流

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? if (out != null) out.close();

? ? ? ? ? ? ? ? if (baos != null) baos.close();

? ? ? ? ? ? } catch (IOException e) {

? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return outPutFilename;

? ? }


? ? //計(jì)算采樣率

? ? 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;

? ? }


? //因?yàn)閳D片壓縮不能精確壓縮,所以實(shí)際文件大小約等于規(guī)定大小就不壓縮了, 這里默認(rèn)誤差 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;

? ? ? ? }

? ? }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容