package com.itant.shiwushu.tool;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by Jason on 2018/10/11.
 */

public class PhotoTool {
    public static void compressAndSavePhoto(File sourcePhoto, File targetFile, int targetSize) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true，即只读边不读内容
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        // Get bitmap info, but notice that bitmap is null now
        newOpts.inJustDecodeBounds = false;
        // 原分辨率宽高
        //int sourceWidth = newOpts.outWidth;
        //int sourceHeight = newOpts.outHeight;

        // 目标文件路径
        String targetFilePath = targetFile.getAbsolutePath();
        if (targetFile.exists()) {
            targetFile.delete();
        }
        //设置缩放比例，每次压缩为原先的二分之一
        newOpts.inSampleSize = 2;
        // 开始压缩图片，注意此时已经把options.inJustDecodeBounds 设回false了
        Bitmap bitmap = BitmapFactory.decodeFile(sourcePhoto.getAbsolutePath(), newOpts);

        FileOutputStream os;
        try {
            os = new FileOutputStream(targetFilePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        File outFile = new File(targetFilePath);
        if (outFile.exists() && outFile.length() > targetSize) {
            compressAndSavePhoto(outFile, outFile, targetSize);
        }
    }
}
