国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android圖片壓縮工具類分享

2019-10-22 18:18:53
字體:
來源:轉載
供稿:網友

本文實例為大家分享了android圖片壓縮工具類的具體代碼,供大家參考,具體內容如下

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 {    /**    * 我們先看下質量壓縮方法    *    * @param image    * @return    */   public static Bitmap compressImage(Bitmap image) {      ByteArrayOutputStream baos = new ByteArrayOutputStream();     image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中     int options = 100;     while (baos.toByteArray().length / 1024 > 100) { // 循環判斷如果壓縮后圖片是否大于100kb,大于繼續壓縮       baos.reset();// 重置baos即清空baos       image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數據存放到baos中       options -= 10;// 每次都減少10     }     ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮后的數據baos存放到ByteArrayInputStream中     Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片     return bitmap;   }    /**    * 圖片按比例大小壓縮方法(根據路徑獲取圖片并壓縮)    *    * @param srcPath    * @return    */   public static Bitmap getimage(String srcPath) {     BitmapFactory.Options newOpts = new BitmapFactory.Options();     // 開始讀入圖片,此時把options.inJustDecodeBounds 設回true了     newOpts.inJustDecodeBounds = true;     Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此時返回bm為空      newOpts.inJustDecodeBounds = false;     int w = newOpts.outWidth;     int h = newOpts.outHeight;     // 現在主流手機比較多是800*480分辨率,所以高和寬我們設置為     float hh = 800f;// 這里設置高度為800f     float ww = 480f;// 這里設置寬度為480f     // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數據進行計算即可     int be = 1;// be=1表示不縮放     if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放       be = (int) (newOpts.outWidth / ww);     } else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放       be = (int) (newOpts.outHeight / hh);     }     if (be <= 0)       be = 1;     newOpts.inSampleSize = be;// 設置縮放比例     // 重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了     bitmap = BitmapFactory.decodeFile(srcPath, newOpts);     return compressImage(bitmap);// 壓縮好比例大小后再進行質量壓縮   }    /**    * 圖片按比例大小壓縮方法(根據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%,把壓縮后的數據存放到baos中     }     ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());     BitmapFactory.Options newOpts = new BitmapFactory.Options();     // 開始讀入圖片,此時把options.inJustDecodeBounds 設回true了     newOpts.inJustDecodeBounds = true;     Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);     newOpts.inJustDecodeBounds = false;     int w = newOpts.outWidth;     int h = newOpts.outHeight;     // 現在主流手機比較多是800*480分辨率,所以高和寬我們設置為     float hh = 150f;// 這里設置高度為800f     float ww = 150f;// 這里設置寬度為480f     // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數據進行計算即可     int be = 1;// be=1表示不縮放     if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放       be = (int) (newOpts.outWidth / ww);     } else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放       be = (int) (newOpts.outHeight / hh);     }     if (be <= 0)       be = 1;     newOpts.inSampleSize = be;// 設置縮放比例     // 重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了     isBm = new ByteArrayInputStream(baos.toByteArray());     bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);     return compressImage(bitmap);// 壓縮好比例大小后再進行質量壓縮   }    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);       // 如果尺寸不變會返回本身,所以需要判斷是否是統一引用來確定是否需要回收       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);   }    /**    * 壓縮圖片(質量壓縮)    *    * @param bitmap    */   public static File compressImage(Bitmap bitmap) {     ByteArrayOutputStream baos = new ByteArrayOutputStream();     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中     int options = 100;     while (baos.toByteArray().length / 1024 > 500) { // 循環判斷如果壓縮后圖片是否大于500kb,大于繼續壓縮       baos.reset();// 重置baos即清空baos       options -= 10;// 每次都減少10       bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這里壓縮options%,把壓縮后的數據存放到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 設回true,即只讀邊不讀內容     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;// 設置高度為240f時,可以明顯看到圖片縮小了     float ww = pixelW;// 設置寬度為120f,可以明顯看到圖片縮小了     // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數據進行計算即可     int be = 1;// be=1表示不縮放     if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放       be = (int) (newOpts.outWidth / ww);     } else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放       be = (int) (newOpts.outHeight / hh);     }     if (be <= 0)       be = 1;     newOpts.inSampleSize = be;// 設置縮放比例     // 開始壓縮圖片,注意此時已經把options.inJustDecodeBounds 設回false了     bitmap = BitmapFactory.decodeFile(imgPath, newOpts);     // 壓縮好比例大小后再進行質量壓縮     // return compress(bitmap, maxSize); // 這里再進行質量壓縮的意義不大,反而耗資源,刪除     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%,把壓縮后的數據存放到baos中     }     ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());     BitmapFactory.Options newOpts = new BitmapFactory.Options();     // 開始讀入圖片,此時把options.inJustDecodeBounds 設回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;// 設置高度為240f時,可以明顯看到圖片縮小了     float ww = pixelW;// 設置寬度為120f,可以明顯看到圖片縮小了     // 縮放比。由于是固定比例縮放,只用高或者寬其中一個數據進行計算即可     int be = 1;// be=1表示不縮放     if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放       be = (int) (newOpts.outWidth / ww);     } else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放       be = (int) (newOpts.outHeight / hh);     }     if (be <= 0)       be = 1;     newOpts.inSampleSize = be;// 設置縮放比例     // 重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了     is = new ByteArrayInputStream(os.toByteArray());     bitmap = BitmapFactory.decodeStream(is, null, newOpts);     // 壓縮好比例大小后再進行質量壓縮     // return compress(bitmap, maxSize); // 這里再進行質量壓縮的意義不大,反而耗資源,刪除     return bitmap;   }    /**    * 按質量壓縮,并將圖像生成指定的路徑    *    * @param image    * @param outPath    * @param maxSize    *      目標將被壓縮到小于這個大小(KB)。    * @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();   }    /**    * 按質量壓縮,并將圖像生成指定的路徑    *    * @param imgPath    * @param outPath    * @param maxSize    *      目標將被壓縮到小于這個大小(KB)。    * @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();       }     }   }  } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 开原市| 西林县| 青海省| 深泽县| 邯郸市| 即墨市| 潼南县| 班戈县| 无锡市| 清水县| 普兰县| 舟曲县| 九龙县| 太康县| 瑞安市| 怀安县| 江口县| 龙井市| 磴口县| 桂东县| 宕昌县| 夏邑县| 东城区| 郓城县| 商南县| 巩留县| 酒泉市| 新疆| 斗六市| 宝山区| 华坪县| 肇庆市| 五河县| 台中市| 饶平县| 扶余县| 当涂县| 定南县| 庆安县| 万全县| 都安|