Android-Bitmap操作工具類

package com.cwang.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;

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

/**
 * @author: cwang
 * @time: 2018/5/21 10:37
 * @Description:Bitmap操作工具類
 */
public class BmpUtils {
    private static int imageMaxSize = 1024;// 圖片最大大小(寬和高)
    private static int imageMixSize = 64;// 圖片最小大小(寬和高)
    private static int imageMaxBytes = 2 * 1024 * 1024;// 圖片最小大小(寬和高)

    /**
     * 將Bmp保存成jpg圖片到本地
     *
     * @param mBitmap  bmp位圖
     * @param savaPath 保存路徑,例如:sdcard/Img/
     * @param bmpName  保存的jpg文件名
     */
    public static void saveBmpToJpg(Bitmap mBitmap, String savaPath, String bmpName) {
        if (mBitmap == null) return;
        File savaFile = new File(savaPath);
        if (!savaFile.exists()) savaFile.mkdir();
        File f = new File(savaPath + bmpName + ".jpg");
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * bitmap轉爲base64
     *
     * @param bitmap bitmap圖
     * @return base64編碼後字符串
     */
    public static String bmpToBase64(Bitmap bitmap) {
        if (bitmap == null) return "";
        ByteArrayOutputStream baos = null;
        try {
            int imageSize = getBmpSize(bitmap);
            if (imageSize > imageMaxBytes) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
            }
            if (baos != null) {
                baos = null;
            }
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
            baos.flush();
            baos.close();
            byte[] bitmapBytes = baos.toByteArray();
            return Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * base64轉爲bitmap
     *
     * @param base64Data base64數據
     * @return bitmap圖
     */
    public static Bitmap base64ToBmp(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * bitmap圖片轉成string
     *
     * @param bitmap bitmap圖
     * @return 圖片數據字符串
     */
    public static String convertBmpToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// 轉爲byte數組
        return Base64.encodeToString(appicon, Base64.DEFAULT);
    }

    /**
     * string轉成bitmap
     *
     * @param str 圖片數據字符串
     * @return bitmap圖
     */
    public static Bitmap convertStringToBmp(String str) {
        // OutputStream out;
        Bitmap bitma = null;
        try {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(str, Base64.DEFAULT);
            bitma = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitma;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * uri轉化爲bitmap
     *
     * @param context 上下文
     * @param uri     路徑
     * @return bitmap bitmap圖
     */
    public static Bitmap getBmpFromUri(Context context, Uri uri) {
        try {
            // 讀取uri所在的圖片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                    context.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            String err = e.getMessage();
            Log.e("[getBmpFromUri]", err);
            Log.e("[getBmpFromUri]", "目錄爲:" + uri);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根據文件路徑轉換爲bitmap
     *
     * @param path 文件路徑
     * @return bitmap圖
     */
    public static Bitmap getDiskBmp(String path) {
        Bitmap bitmap = null;
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inPreferredConfig = Bitmap.Config.RGB_565;
            opt.inPurgeable = true;
            opt.inInputShareable = true;
            opt.inSampleSize = 8;// 容量變爲以前容量的1/8
            File file = new File(path);
            if (file.exists())
                bitmap = BitmapFactory.decodeFile(path, opt);
            return bitmap;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 根據path得到適當的inSampleSize,縮略圖
     *
     * @param filePath 文件路徑
     * @return bitmap圖
     */
    public static Bitmap createBmpThumbnail(String filePath) {
        Bitmap bitmap = null;
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, opts);

        opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128);
        opts.inJustDecodeBounds = false;

        try {
            bitmap = BitmapFactory.decodeFile(filePath, opts);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 縮放圖片
     *
     * @param bm       原bitmap
     * @param newWidth 新的寬度
     * @return 新的bitmap
     */
    public static Bitmap zoomBmp(Bitmap bm, int newWidth) {
        // 獲得圖片的寬高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 計算縮放比例
        float scale = ((float) newWidth) / width;

        // 取得想要縮放的matrix參數
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        // 得到新的圖片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        return newbm;
    }

    /**
     * 計算樣本大小
     *
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);
        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }
        return roundedSize;
    }

    /**
     * 計算初始樣本大小
     *
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;
        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));
        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }
        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 縮小圖片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getLessBmp(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        Bitmap resizeBmp = null;
        float ratio = 0;// 縮小的比例
        if (bitmap == null)
            return null;
        int bmpW = bitmap.getWidth();
        int bmpH = bitmap.getHeight();
        if (bmpW > imageMaxSize || bmpH > imageMaxSize) {
            if (bmpW <= bmpH) {
                ratio = (float) imageMaxSize / (float) bmpH;
            } else {
                ratio = (float) imageMaxSize / (float) bmpW;
            }
            matrix.postScale(ratio, ratio);// 長和寬放大縮小的比例
            resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bmpW, bmpH, matrix,
                    true);
            return resizeBmp;
        }
        return bitmap;
    }

    /**
     * 得到bitmap的大小,單位byte
     *
     * @param bitmap Bitmap圖
     * @return bitmap的大小,單位byte
     */
    public static int getBmpSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // API 19
            return bitmap.getAllocationByteCount();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {// API
            // 12
            return bitmap.getByteCount();
        }
        // 在低版本中用一行的字節x高度
        return bitmap.getRowBytes() * bitmap.getHeight(); // earlier version
    }

    /**
     * 判斷Bitmap圖是否太小(寬高都不得小於64像素)
     *
     * @param bitmap Bitmap圖
     * @return 小於64像素返回true,否則返回false
     */
    public static boolean judgeBmpIsTooSmall(Bitmap bitmap) {
        int bmpW = bitmap.getWidth();
        int bmpH = bitmap.getHeight();
        if (bmpW < imageMixSize || bmpH < imageMixSize) {
            return true;
        }
        return false;
    }

    /***
     * 對圖像進行偏色矯正處理
     * @param bmp Bitmap圖
     * @param rRateValue 紅色偏色率
     * @param gRateValue 綠色偏色率
     * @param bRateValue 藍色偏色率
     * @return 進行偏色矯正後的Bitmap圖
     */
    public static Bitmap changePicRGB(Bitmap bmp, float rRateValue, float gRateValue,
                                      float bRateValue) {
        int bmpWidth = 0;
        int bmpHeight = 0;

        int mArrayColor[] = null;
        int mArrayColorLengh = 0;
        bmpWidth = bmp.getWidth();
        bmpHeight = bmp.getHeight();

        mArrayColorLengh = bmpWidth * bmpHeight;
        mArrayColor = new int[mArrayColorLengh];
        int count = 0;
        for (int i = 0; i < bmpHeight; i++) {
            for (int j = 0; j < bmpWidth; j++) {
                // 獲得Bitmap 圖片中每一個點的color顏色值
                int color = bmp.getPixel(j, i);

                int r = Color.red(color);
                int g = Color.green(color);
                int b = Color.blue(color);
                if (rRateValue != 1) {
                    float rFloat = (float) (r * 1.0) * rRateValue + (float) 0.5;
                    r = (int) rFloat;
                }

                if (gRateValue != 1) {
                    float gFloat = (float) (g * 1.0) * gRateValue + (float) 0.5;
                    g = (int) gFloat;
                }
                if (bRateValue != 1) {
                    float bFloat = (float) (b * 1.0) * bRateValue + (float) 0.5;
                    b = (int) bFloat;
                }
                mArrayColor[count] = Color.rgb(r, g, b);
                count++;
            }
        }

        Bitmap newBmp = Bitmap.createBitmap(mArrayColor, bmpWidth, bmpHeight,
                Bitmap.Config.ARGB_4444);
        return newBmp;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章