*******************************圖片壓縮三種方式*******************************************
三圖片按像素進行壓縮
一.圖片的存在形式
2.流的形式(即以二進制形式存在於內存中)
3.Bitmap形式
二.常見的壓縮方式
- public static void compressBmpToFile(Bitmap bmp,File file){
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int options = 80;//個人喜歡從80開始,
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
- while (baos.toByteArray().length / 1024 > 100) {
- baos.reset();
- options -= 10;
- bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
- }
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(baos.toByteArray());
- fos.flush();
- fos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private Bitmap compressBmpFromBmp(Bitmap image) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- int options = 100;
- image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
- while (baos.toByteArray().length / 1024 > 100) {
- baos.reset();
- options -= 10;
- image.compress(Bitmap.CompressFormat.JPEG, options, baos);
- }
- ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
- Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
- return bitmap;
- }
- private Bitmap compressImageFromFile(String srcPath) {
- BitmapFactory.Options newOpts = new BitmapFactory.Options();
- newOpts.inJustDecodeBounds = true;//只讀邊,不讀內容
- Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
- newOpts.inJustDecodeBounds = false;
- int w = newOpts.outWidth;
- int h = newOpts.outHeight;
- float hh = 800f;//
- float ww = 480f;//
- int 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;//設置採樣率
- newOpts.inPreferredConfig = Config.ARGB_8888;//該模式是默認的,可不設
- newOpts.inPurgeable = true;// 同時設置纔會有效
- newOpts.inInputShareable = true;//。當系統內存不夠時候圖片自動被回收
- bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
- // return compressBmpFromBmp(bitmap);//原來的方法調用了這個方法企圖進行二次壓縮
- //其實是無效的,大家儘管嘗試
- return bitmap;
- }