android圖片壓縮工具類分享
本文實例為大家分享了android圖片壓縮工具類的具體代碼,供大家參考,具體內(nèi)容如下
import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.Matrix; import android.net.Uri; import android.widget.Toast; /** * 圓形圖片工具類 * * @author SKLM * */ public class ImageViewTool { /** * 我們先看下質(zhì)量壓縮方法 * * @param image * @return */ public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 100) { // 循環(huán)判斷如果壓縮后圖片是否大于100kb,大于繼續(xù)壓縮 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數(shù)據(jù)存放到baos中 options -= 10;// 每次都減少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮后的數(shù)據(jù)baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數(shù)據(jù)生成圖片 return bitmap; } /** * 圖片按比例大小壓縮方法(根據(jù)路徑獲取圖片并壓縮) * * @param srcPath * @return */ public static Bitmap getimage(String srcPath) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 開始讀入圖片,此時把options.inJustDecodeBounds 設(shè)回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此時返回bm為空 newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; // 現(xiàn)在主流手機比較多是800*480分辨率,所以高和寬我們設(shè)置為 float hh = 800f;// 這里設(shè)置高度為800f float ww = 480f;// 這里設(shè)置寬度為480f // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數(shù)據(jù)進行計算即可 int be = 1;// be=1表示不縮放 if (w > h && w > ww) {// 如果寬度大的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 設(shè)置縮放比例 // 重新讀入圖片,注意此時已經(jīng)把options.inJustDecodeBounds 設(shè)回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); return compressImage(bitmap);// 壓縮好比例大小后再進行質(zhì)量壓縮 } /** * 圖片按比例大小壓縮方法(根據(jù)Bitmap圖片壓縮) * * @param image * @return */ public static Bitmap comp(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos); if (baos.toByteArray().length / 1024 > 1024) {// 判斷如果圖片大于1M,進行壓縮避免在生成圖片(BitmapFactory.decodeStream)時溢出 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, 30, baos);// 這里壓縮50%,把壓縮后的數(shù)據(jù)存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 開始讀入圖片,此時把options.inJustDecodeBounds 設(shè)回true了 newOpts.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; // 現(xiàn)在主流手機比較多是800*480分辨率,所以高和寬我們設(shè)置為 float hh = 150f;// 這里設(shè)置高度為800f float ww = 150f;// 這里設(shè)置寬度為480f // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數(shù)據(jù)進行計算即可 int be = 1;// be=1表示不縮放 if (w > h && w > ww) {// 如果寬度大的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 設(shè)置縮放比例 // 重新讀入圖片,注意此時已經(jīng)把options.inJustDecodeBounds 設(shè)回false了 isBm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); return compressImage(bitmap);// 壓縮好比例大小后再進行質(zhì)量壓縮 } public static byte[] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } /** * 按原比例壓縮圖片到指定尺寸 * * @param context * @param inputUri * @param outputUri * @param maxLenth * 最長邊長 */ public static void reducePicture(Context context, Uri inputUri, Uri outputUri, int maxLenth, int compress) { Options options = new Options(); options.inJustDecodeBounds = true; InputStream is = null; try { is = context.getContentResolver().openInputStream(inputUri); BitmapFactory.decodeStream(is, null, options); is.close(); int sampleSize = 1; int longestSide = 0; int longestSideLenth = 0; if (options.outWidth > options.outHeight) { longestSideLenth = options.outWidth; longestSide = 0; } else { longestSideLenth = options.outHeight; longestSide = 1; } if (longestSideLenth > maxLenth) { sampleSize = longestSideLenth / maxLenth; } options.inJustDecodeBounds = false; options.inSampleSize = sampleSize; is = context.getContentResolver().openInputStream(inputUri); Bitmap bitmap = BitmapFactory.decodeStream(is, null, options); is.close(); if (bitmap == null) { Toast.makeText(context, "圖片獲取失敗,請確認您的存儲卡是否正常", Toast.LENGTH_SHORT).show(); return; } Bitmap srcBitmap = bitmap; float scale = 0; if (longestSide == 0) { scale = (float) maxLenth / (float) (srcBitmap.getWidth()); } else { scale = (float) maxLenth / (float) (srcBitmap.getHeight()); } Matrix matrix = new Matrix(); matrix.postScale(scale, scale); bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); // 如果尺寸不變會返回本身,所以需要判斷是否是統(tǒng)一引用來確定是否需要回收 if (srcBitmap != bitmap) { srcBitmap.recycle(); srcBitmap = null; } saveBitmapToUri(bitmap, outputUri, compress); bitmap.recycle(); bitmap = null; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static boolean saveBitmapToUri(Bitmap bitmap, Uri uri, int compress) throws IOException { File file = new File(uri.getPath()); if (file.exists()) { if (file.delete()) { if (!file.createNewFile()) { return false; } } } BufferedOutputStream outStream = new BufferedOutputStream( new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, compress, outStream); outStream.flush(); outStream.close(); return true; } }
接下來看看第二個寫法壓縮圖片的工具類,如下
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Date; import java.text.SimpleDateFormat; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.os.Environment; /** * 圖像壓縮工廠類 * * @author * */ public class ImageFactory { /** * 從指定的圖像路徑獲取位圖 * * @param imgPath * @return */ public Bitmap getBitmap(String imgPath) { // Get bitmap through image path BitmapFactory.Options newOpts = new BitmapFactory.Options(); newOpts.inJustDecodeBounds = false; newOpts.inPurgeable = true; newOpts.inInputShareable = true; // Do not compress newOpts.inSampleSize = 1; newOpts.inPreferredConfig = Config.RGB_565; return BitmapFactory.decodeFile(imgPath, newOpts); } /** * 壓縮圖片(質(zhì)量壓縮) * * @param bitmap */ public static File compressImage(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質(zhì)量壓縮方法,這里100表示不壓縮,把壓縮后的數(shù)據(jù)存放到baos中 int options = 100; while (baos.toByteArray().length / 1024 > 500) { // 循環(huán)判斷如果壓縮后圖片是否大于500kb,大于繼續(xù)壓縮 baos.reset();// 重置baos即清空baos options -= 10;// 每次都減少10 bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數(shù)據(jù)存放到baos中 long length = baos.toByteArray().length; } SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = new Date(System.currentTimeMillis()); String filename = format.format(date); File file = new File(Environment.getExternalStorageDirectory(), filename + ".png"); try { FileOutputStream fos = new FileOutputStream(file); try { fos.write(baos.toByteArray()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } recycleBitmap(bitmap); return file; } public static void recycleBitmap(Bitmap... bitmaps) { if (bitmaps == null) { return; } for (Bitmap bm : bitmaps) { if (null != bm && !bm.isRecycled()) { bm.recycle(); } } } /** * 將位圖存儲到指定的圖像路徑中 * * @param bitmap * @param outPath * @throws FileNotFoundException */ public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException { FileOutputStream os = new FileOutputStream(outPath); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); } /** * 通過像素壓縮圖像,這將改變圖像的寬度/高度。用于獲取縮略圖 * * * @param imgPath * image path * @param pixelW * 目標寬度像素 * @param pixelH * 高度目標像素 * @return */ public Bitmap ratio(String imgPath, float pixelW, float pixelH) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 開始讀入圖片,此時把options.inJustDecodeBounds 設(shè)回true,即只讀邊不讀內(nèi)容 newOpts.inJustDecodeBounds = true; newOpts.inPreferredConfig = Config.RGB_565; // Get bitmap info, but notice that bitmap is null now Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; // 想要縮放的目標尺寸 float hh = pixelH;// 設(shè)置高度為240f時,可以明顯看到圖片縮小了 float ww = pixelW;// 設(shè)置寬度為120f,可以明顯看到圖片縮小了 // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數(shù)據(jù)進行計算即可 int be = 1;// be=1表示不縮放 if (w > h && w > ww) {// 如果寬度大的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 設(shè)置縮放比例 // 開始壓縮圖片,注意此時已經(jīng)把options.inJustDecodeBounds 設(shè)回false了 bitmap = BitmapFactory.decodeFile(imgPath, newOpts); // 壓縮好比例大小后再進行質(zhì)量壓縮 // return compress(bitmap, maxSize); // 這里再進行質(zhì)量壓縮的意義不大,反而耗資源,刪除 return bitmap; } /** * 壓縮圖像的大小,這將修改圖像寬度/高度。用于獲取縮略圖 * * * @param image * @param pixelW * target pixel of width * @param pixelH * target pixel of height * @return */ public Bitmap ratio(Bitmap image, float pixelW, float pixelH) { ByteArrayOutputStream os = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, os); if (os.toByteArray().length / 1024 > 1024) {// 判斷如果圖片大于1M,進行壓縮避免在生成圖片(BitmapFactory.decodeStream)時溢出 os.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, 50, os);// 這里壓縮50%,把壓縮后的數(shù)據(jù)存放到baos中 } ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 開始讀入圖片,此時把options.inJustDecodeBounds 設(shè)回true了 newOpts.inJustDecodeBounds = true; newOpts.inPreferredConfig = Config.RGB_565; Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts); newOpts.inJustDecodeBounds = false; int w = newOpts.outWidth; int h = newOpts.outHeight; float hh = pixelH;// 設(shè)置高度為240f時,可以明顯看到圖片縮小了 float ww = pixelW;// 設(shè)置寬度為120f,可以明顯看到圖片縮小了 // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數(shù)據(jù)進行計算即可 int be = 1;// be=1表示不縮放 if (w > h && w > ww) {// 如果寬度大的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outWidth / ww); } else if (w < h && h > hh) {// 如果高度高的話根據(jù)寬度固定大小縮放 be = (int) (newOpts.outHeight / hh); } if (be <= 0) be = 1; newOpts.inSampleSize = be;// 設(shè)置縮放比例 // 重新讀入圖片,注意此時已經(jīng)把options.inJustDecodeBounds 設(shè)回false了 is = new ByteArrayInputStream(os.toByteArray()); bitmap = BitmapFactory.decodeStream(is, null, newOpts); // 壓縮好比例大小后再進行質(zhì)量壓縮 // return compress(bitmap, maxSize); // 這里再進行質(zhì)量壓縮的意義不大,反而耗資源,刪除 return bitmap; } /** * 按質(zhì)量壓縮,并將圖像生成指定的路徑 * * @param image * @param outPath * @param maxSize * 目標將被壓縮到小于這個大?。↘B)。 * @throws IOException */ public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); // scale int options = 100; // Store the bitmap into output stream(no compress) image.compress(Bitmap.CompressFormat.JPEG, options, os); // Compress by loop while (os.toByteArray().length / 1024 > maxSize) { // Clean up os os.reset(); // interval 10 options -= 10; image.compress(Bitmap.CompressFormat.JPEG, options, os); } // Generate compressed image file FileOutputStream fos = new FileOutputStream(outPath); fos.write(os.toByteArray()); fos.flush(); fos.close(); } /** * 按質(zhì)量壓縮,并將圖像生成指定的路徑 * * @param imgPath * @param outPath * @param maxSize * 目標將被壓縮到小于這個大?。↘B)。 * @param needsDelete * 是否壓縮后刪除原始文件 * @throws IOException */ public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException { compressAndGenImage(getBitmap(imgPath), outPath, maxSize); // Delete original file if (needsDelete) { File file = new File(imgPath); if (file.exists()) { file.delete(); } } } /** * 比例和生成拇指的路徑指定 * * @param image * @param outPath * @param pixelW * 目標寬度像素 * @param pixelH * 高度目標像素 * @throws FileNotFoundException */ public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException { Bitmap bitmap = ratio(image, pixelW, pixelH); storeImage(bitmap, outPath); } /** * 比例和生成拇指的路徑指定 * * @param image * @param outPath * @param pixelW * 目標寬度像素 * @param pixelH * 高度目標像素 * @param needsDelete * 是否壓縮后刪除原始文件 * @throws FileNotFoundException */ public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException { Bitmap bitmap = ratio(imgPath, pixelW, pixelH); storeImage(bitmap, outPath); // Delete original file if (needsDelete) { File file = new File(imgPath); if (file.exists()) { file.delete(); } } } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
設(shè)置界面開發(fā)Preference Library數(shù)據(jù)重建機制詳解
這篇文章主要為大家介紹了設(shè)置界面開發(fā)利器Preference Library數(shù)據(jù)重建機制詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10Android Drawerlayout實現(xiàn)側(cè)滑菜單效果
這篇文章主要為大家詳細介紹了Android Drawerlayout實現(xiàn)側(cè)滑菜單效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10android開發(fā)修改狀態(tài)欄背景色和圖標顏色的示例
本篇文章主要介紹了android開發(fā)修改狀態(tài)欄背景色和圖標顏色的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01Android性能優(yōu)化之plt?hook與native線程監(jiān)控詳解
這篇文章主要為大家介紹了Android性能優(yōu)化之plt?hook與native線程監(jiān)控詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09Android RecyclerView詳解之實現(xiàn) ListView GridView瀑布流效果
RecyclerView 是Android L版本中新添加的一個用來取代ListView的SDK,它的靈活性與可替代性比listview更好2016-07-07HorizontalScrollView水平滾動控件使用方法詳解
這篇文章主要為大家詳細介紹了HorizontalScrollView水平滾動控件的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08