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;
    }
}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读