ImageCompress.java 6.65 KB
Newer Older
konghaorui committed
1 2 3 4 5
package com.yidianling.dynamic.common.tool;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
konghaorui committed
6
import android.support.v4.app.FragmentActivity;
konghaorui committed
7 8
import android.util.Log;

konghaorui committed
9
import com.miracle.view.imageeditor.utils.FileUtils;
konghaorui committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import com.yidianling.common.tools.RxFileTool;

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.text.SimpleDateFormat;
import java.util.Date;


public class ImageCompress {
    public static File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );
        return image;
    }

konghaorui committed
35
    public static File scal(FragmentActivity activity, String path, int size) {
konghaorui committed
36
//		String path = fileUri.getPath();
konghaorui committed
37
        File outputFile = FileUtils.INSTANCE.getFileByUri(activity,path);
konghaorui committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        if (!outputFile.exists()){
            return null;
        }
        long fileSize = outputFile.length();
        final long fileMaxSize = size * 1024;
        if (fileSize >= fileMaxSize) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            int height = options.outHeight;
            int width = options.outWidth;

            double scale = Math.sqrt((float) fileSize / fileMaxSize);
            options.outHeight = (int) (height / scale);
            options.outWidth = (int) (width / scale);
            options.inSampleSize = (int) (scale + 0.5);
            options.inJustDecodeBounds = false;

            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            outputFile = new File(PhotoUtil.createImageFile().getPath());
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d("", "sss ok " + outputFile.length());
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            } else {
                File tempFile = outputFile;
                outputFile = new File(PhotoUtil.createImageFile().getPath());
                PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
            }

        }
        return outputFile;

    }

    public static File scaln(String path, int size) {
//		String path = fileUri.getPath();
        File outputFile = new File(path);
//		long fileSize = outputFile.length();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap imagebm = BitmapFactory.decodeFile(path);
        imagebm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//		final long fileMaxSize = size * 1024;
        // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > size) {
            // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            imagebm.compress(Bitmap.CompressFormat.JPEG, options, baos);
            // 这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
            if (options <= 0) {
                break;
            }
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        // 把ByteArrayInputStream数据生成图片
        imagebm = BitmapFactory.decodeStream(isBm, null, null);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outputFile);
            imagebm.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!imagebm.isRecycled()) {
            imagebm.recycle();
        } else {
            File tempFile = outputFile;
            outputFile = new File(PhotoUtil.createImageFile().getPath());
            PhotoUtil.copyFileUsingFileChannels(tempFile, outputFile);
        }

        return outputFile;

    }

    public static File scaln2(String path, int size) {
        Bitmap bm = BitmapFactory.decodeFile(path);
        bm=cQuality(bm,size);
        File outputFile = null;
        try {
            outputFile = SaveBitmap(bm,path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputFile;

    }
    public static File SaveBitmap(Bitmap mBitmap, String path) throws IOException {
        File file;
        RxFileTool.fileExists(path);
        File f = new File(path);
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file=new File(path);
        return file;
    }

    /**
     * 根据bitmap压缩图片质量
     *
     * @param bitmap 未压缩的bitmap
     * @return 压缩后的bitmap
     */
    public static Bitmap cQuality(Bitmap bitmap,int size) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        int beginRate = 100;
        //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差  ,第三个参数:保存压缩后的数据的流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
        while (bOut.size() / 1024 / 1024 > size) {  //如果压缩后大于100Kb,则提高压缩率,重新压缩
            beginRate -= 10;
            bOut.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
        }
        ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
        Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
        if (newBitmap != null) {
            return newBitmap;
        } else {
            return bitmap;
        }
    }
}