Android壓縮工具類

jopen 9年前發布 | 2K 次閱讀 Java Android

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List;

import utils.ImageRotateUtil;

/**

  • Created by pengkv on 15/12/2.
  • 圖片壓縮工具類 */ public class ImageCompressUtil {

    private static List<String> mImageList = new ArrayList<>();// 臨時圖片集合 private static String mImagePath = ""; // 單個臨時圖片 public static String cachePath = ""; public static int reqWidth = 320; public static int reqHeight = 480;

    //壓縮單張圖片方法 public static void compressImage(final Context ctx, final String filePath, final ProcessImgCallBack callBack) {

     mImagePath = "";//清空路徑
    
     new Thread(new Runnable() {
         @Override
         public void run() {
             //如果路徑是圖片,則進行壓縮
             if (isImage(filePath)) {
                 mImagePath = compress(ctx, filePath);
             }
             callBack.compressSuccess(mImagePath);
         }
     }).start();
    

    }

    //壓縮圖片集合方法 public static void compressImageList(final Context ctx, final List<String> fileList, final ProcessImgListCallBack callBack) {

     mImageList.clear();//清空集合
     if (fileList == null || fileList.isEmpty()) {
         callBack.compressSuccess(mImageList);
         return;
     }
     new Thread(new Runnable() {
         @Override
         public void run() {
             String tempPath = "";
             for (String imagePath : fileList) {
                 if (isImage(imagePath)) {
                     tempPath = compress(ctx, imagePath);
                     mImageList.add(tempPath);
                 }
             }
             callBack.compressSuccess(mImageList);
         }
     }).start();
    
    

    }

    //圖片壓縮的方法 public static String compress(Context ctx, String filePath) {

     if (TextUtils.isEmpty(filePath))
         return filePath;
    
     File file = new File(filePath);
     if (!file.exists())//判斷路徑是否存在
         return filePath;
    
     if (file.length() < 1)//文件是否為空
         return null;
    
     File tempFile = getDiskCacheDir(ctx);
     String outImagePath = tempFile.getAbsolutePath(); // 輸出圖片文件路徑
    int degree = ImageRotateUtil.getBitmapDegree(filePath); // 檢查圖片的旋轉角度

    //谷歌官網壓縮圖片
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

    // 旋轉:這步處理主要是為了處理三星手機拍的照片
    if (degree > 0) {
        bitmap = ImageRotateUtil.rotateBitmapByDegree(bitmap, degree);
    }

    // 寫入文件
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(tempFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
        fos.flush();
        fos.close();
        bitmap.recycle();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return filePath;
    } catch (Exception e) {
        e.printStackTrace();
        return filePath;
    }

    return outImagePath;
}


/**
 * 計算壓縮比例值
 * 按照2、3、4...倍壓縮
 *
 * @param options   解析圖片的配置信息
 * @param reqWidth  所需圖片壓縮尺寸最小寬度
 * @param reqHeight 所需圖片壓縮尺寸最小高度
 * @return
 */
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int picheight = options.outHeight;
    final int picwidth = options.outWidth;
    Log.i("--->", "原尺寸:" + picwidth + "*" + picheight);

    int targetheight = picheight;
    int targetwidth = picwidth;
    int inSampleSize = 1;

    if (targetheight > reqHeight || targetwidth > reqWidth) {
        while (targetheight >= reqHeight && targetwidth >= reqWidth) {
            inSampleSize += 1;
            targetheight = picheight / inSampleSize;
            targetwidth = picwidth / inSampleSize;
        }
    }

    Log.i("--->", "最終壓縮比例:" + inSampleSize + "倍/新尺寸:" + targetwidth + "*" + targetheight);
    return inSampleSize;
}


//圖片集合壓縮成功后的回調接口
public interface ProcessImgListCallBack {
    void compressSuccess(List<String> imgList);
}

//單張圖片壓縮成功后的回調接口
public interface ProcessImgCallBack {
    void compressSuccess(String imgPath);
}


/**
 * 獲取文件后綴名
 *
 * @param fileName
 * @return 文件后綴名
 */
public static String getFileType(String fileName) {
    if (!TextUtils.isEmpty(fileName)) {
        int typeIndex = fileName.lastIndexOf(".");
        if (typeIndex != -1) {
            String fileType = fileName.substring(typeIndex + 1).toLowerCase();
            return fileType;
        }
    }
    return "";
}

/**
 * 判斷是否是圖片
 *
 * @param fileName
 * @return 是否是圖片類型
 */
public static boolean isImage(String fileName) {
    String type = getFileType(fileName);
    if (!TextUtils.isEmpty(type) && (type.equals("jpg") || type.equals("gif")
            || type.equals("png") || type.equals("jpeg")
            || type.equals("bmp") || type.equals("wbmp")
            || type.equals("ico") || type.equals("jpe"))) {
        return true;
    }
    return false;
}

/**
 * 將壓縮后的圖片存儲在緩存中
 */
public static File getDiskCacheDir(Context ctx) {
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable()) {
        cachePath = ctx.getExternalCacheDir().getPath();
    } else {
        cachePath = ctx.getCacheDir().getPath();
    }
    String uniqueName = System.currentTimeMillis() + "_tmp.jpg";
    return new File(cachePath + File.separator + uniqueName);
}

/**
 * 清理緩存文件夾
 */
public static void clearCache(Context ctx) {
    File file = new File(cachePath);
    File[] childFile = file.listFiles();
    if (childFile == null || childFile.length == 0) {
        return;
    }

    for (File f : childFile) {
        f.delete(); // 循環刪除子文件
    }
}


/**
 * 從圖片路徑讀取出圖片
 *
 * @param imagePath
 * @return
 */
private Bitmap decodeFile(String imagePath) {
    Bitmap bitmap = null;
    try {
        File file = new File(imagePath);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        FileInputStream fis = new FileInputStream(file);
        bitmap = BitmapFactory.decodeStream(fis, null, options);
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bitmap;
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!