图片处理工具类

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Base64;
import android.util.Log;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;


public class PictureUtil {
    private static final String TAG = "PictureUtil";
    private static final String fileDirectory = Environment.getExternalStorageDirectory() + File.separator + "photo";

    public static String getMyFileDir() {
        return fileDirectory;
    }


    private static String getImagePath(Context context, Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    public static void mkdirMyPetRootDirectory() {
        boolean isSdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);// 判断sdcard是否存在
        if (isSdCardExist) {
            File MyPetRoot = new File(getMyFileDir());
            if (!MyPetRoot.exists()) {
                try {
                    MyPetRoot.mkdir();
                    Log.d(TAG, "mkdir success");
                } catch (Exception e) {
                    Log.e(TAG, "exception->" + e.toString());
                }
            }
        }
    }

    /**
     * 将bitmap转为Base64字符串
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
        byte[] bytes = outputStream.toByteArray();
        //Base64算法加密,当字符串过长(一般超过76)时会自动在中间加一个换行符,字符串最后也会加一个换行符。
        // 导致和其他模块对接时结果不一致。所以不能用默认Base64.DEFAULT,而是Base64.NO_WRAP不换行
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    /**
     * 将base64字符串转为bitmap
     *
     * @param base64String
     * @return
     */
    public static Bitmap base64ToBitmap(String base64String) {
        byte[] bytes = Base64.decode(base64String, Base64.NO_WRAP);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;
    }

    public static File compress(String path) {

        File outputFile = new File(path);
        long fileSize = outputFile.length();
        final long fileMaxSize = 200 * 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(saveMyBitmap(outputFile.getName()));
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
                fos.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            /*if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }else{
                File tempFile = outputFile;
                outputFile = new File(outputFile.getPath());
                copyFileUsingFileChannels(tempFile, outputFile);
            }*/

        }
        return outputFile;

    }


    private static String saveMyBitmap(String filename) {
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zhwj/";
        String filePath = baseDir + filename;
        File dir = new File(baseDir);
        if (!dir.exists()) {
            dir.mkdir();
        }

        File f = new File(filePath);
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return filePath;
    }

    /**
     * 保存图片到本地
     *
     * @param
     * @return
     */
    public static String saveBitmap(Bitmap bitmap, String name) {
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/kqxt/banner/";
        File filePic;
        try {
            filePic = new File(savePath + name + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("xxx", "saveBitmap: 2return");
            return null;
        }
        return filePic.getAbsolutePath();
    }

    /**
     * 保存图片到本地
     *
     * @param bitmap 图片
     * @param name   图片名字
     * @return 返回图片在本地地址
     */
    public static String saveBitmapPng(Bitmap bitmap, String name) {
//        String savePath;
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zfzd/";
        File filePic;
        try {
            filePic = new File(savePath + name + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("xxx", "saveBitmap: 2return");
            return null;
        }
        return filePic.getAbsolutePath();
    }

    /**
     * 根据本地地址得到bitmap图片
     *
     * @param filePath 图片的本地路径
     * @return 返回显示的bitmap
     */
    public static Bitmap getBitmap(String filePath) {
        Bitmap cardBitmap = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            cardBitmap = BitmapFactory.decodeStream(fis);
            return cardBitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return cardBitmap;
    }

    //图片添加水印
    public static Bitmap AddTimeWatermark(Bitmap mBitmap, String str) {
        //获取原始图片与水印图片的宽与高
        int mBitmapWidth = mBitmap.getWidth();
        int mBitmapHeight = mBitmap.getHeight();
        Bitmap mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mNewBitmap);
        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
        //添加文字
        TextPaint mPaint = new TextPaint();
        String mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //String mFormat = TingUtils.getTime()+"\n"+" 纬度:"+GpsService.latitude+"  经度:"+GpsService.longitude;
        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(30);
        //水印的位置坐标
//        String userName = SharedPreferenceUtil.getString(Constants.USERNAME, "");
//        String project_name = SharedPreferenceUtil.getString(Constants.PROJECT_NAME, "");
//        String org_name = SharedPreferenceUtil.getString(Constants.ORG_NAME, "");
//        String waterStr =
//                "所在项目:" + project_name + "\n" +
//                        "所在组织:" + org_name + "\n" +
//                        "打卡时间:" + str + "\n"
//                        + "考勤机编号:" + userName;
//        mCanvas.drawText(waterStr, (mBitmapWidth * 1) / 10, (mBitmapHeight * 14) / 15, mPaint);
        StaticLayout layoutopen = new StaticLayout(mFormat, mPaint, (int) 800, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
        mCanvas.save();
        mCanvas.translate((mBitmapWidth * 1) / 10, (mBitmapHeight * 13) / 15);
        layoutopen.draw(mCanvas);

        mCanvas.restore();

        return mNewBitmap;
    }

    //去掉身份证空格
    public static String getLocalCard(String card) {
        byte bysIdCode[] = new byte[36];
        bysIdCode = card.getBytes();
        String cardStr = null;
        try {
            cardStr = new String(bysIdCode, "UTF-16LE");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return cardStr;
    }

    //判定文件是否存在
    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    //url转bitmap
    public static Bitmap getUrlBitmap(String imgUrl) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        URL url = null;
        try {
            url = new URL(imgUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) {
                //网络连接成功
                inputStream = httpURLConnection.getInputStream();
                outputStream = new ByteArrayOutputStream();
                byte buffer[] = new byte[1024 * 8];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
//                inputStream.close();


                byte[] bu = outputStream.toByteArray();
                BitmapFactory.Options option = new BitmapFactory.Options();
                option.inSampleSize = 2;
                InputStream input = null;
                input = new ByteArrayInputStream(bu);
                SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
                        input, null, option));
                Bitmap bitmap = (Bitmap) softRef.get();
                if (bu != null) {
                    bu = null;
                }
                if (input != null) {
                    input.close();
                }

//                Bitmap bitmap = BitmapFactory.decodeByteArray(bu, 0, bu.length);
//                ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                int options = 70;
//                //压缩图片到100kb
//                while (baos.toByteArray().length / 1024 > 100) {
//                    baos.reset();
//                    options -= 10;
//                    bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
//                }
//                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
//                byte[] bytes = baos.toByteArray();
//
//                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//                Log.d(TAG, "getUrlBitmap: size "+bytes.length);
                return bitmap;
            } else {
                Log.d(TAG, "网络连接失败----" + httpURLConnection.getResponseCode());
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 根据图片要显示的宽和高,对图片进行压缩,避免OOM
     *
     * @param path
     * @param width  要显示的imageview的宽度
     * @param height 要显示的imageview的高度
     * @return
     */
    public static Bitmap decodeSampledBitmapFromPath(String path, int width, int height) {

//      获取图片的宽和高,并不把他加载到内存当中
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = caculateInSampleSize(options, width, height);
//      使用获取到的inSampleSize再次解析图片(此时options里已经含有压缩比 options.inSampleSize,再次解析会得到压缩后的图片,不会oom了 )
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;

    }

    /**
     * 根据需求的宽和高以及图片实际的宽和高计算SampleSize
     *
     * @param options
     * @param reqWidth  要显示的imageview的宽度
     * @param reqHeight 要显示的imageview的高度
     * @return
     * @compressExpand 这个值是为了像预览图片这样的需求,他要比所要显示的imageview高宽要大一点,放大才能清晰
     */
    private static int caculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int height = options.outHeight;

        int inSampleSize = 1;

        if (width >= reqWidth || height >= reqHeight) {

            int widthRadio = Math.round(width * 1.0f / reqWidth);
            int heightRadio = Math.round(width * 1.0f / reqHeight);

            inSampleSize = Math.max(widthRadio, heightRadio);

        }

        return inSampleSize;
    }

    /**
     * 将图片转换成十六进制字符串
     *
     * @param
     * @return
     */
    public static String bitmapTo16(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件
        byte[] bt = stream.toByteArray();
        String photoStr = byte2hex(bt);
        Log.d("lll", "bitmapTo16: " + photoStr);
        return photoStr;
    }

    /**
     * 二进制转字符串
     *
     * @param b
     * @return
     */
    public static String byte2hex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append("0" + stmp);
            } else {
                sb.append(stmp);
            }


        }
        return sb.toString().toUpperCase();
    }

    /**
     * 保存bitmap到文件夹
     *
     * @param bmp
     * @param username 保存图片名字
     * @param time     当前时间
     * @return
     */
    public static String compressBmpToFile(Bitmap bmp, String username, String time) {
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zfzd/";
        String name = username;

        bmp = AddTimeWatermark(bmp, time);
        boolean dirExists = true;
        File imgDir = new File(savePath);

        if (!imgDir.exists()) {
            dirExists = imgDir.mkdirs();
        }
        if (!dirExists) {
            return "";
        }
        File filePic;
        filePic = new File(savePath + name + ".jpg");
        if (!filePic.exists()) {
            filePic.getParentFile().mkdirs();
            try {
                filePic.createNewFile();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int options = 80;
                bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
                while (baos.toByteArray().length / 1024 > 40) {
                    baos.reset();
                    options -= 10;
                    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
                }
                FileOutputStream fos = new FileOutputStream(filePic);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePic.getAbsolutePath();

    }

    /**
     * 保存打卡图片并压缩到40kb一下
     *
     * @param image
     * @param username
     * @return
     */
    public static String saveAttendBitmap(Bitmap image, String username) {
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zfzd/";
        String name = username;
        boolean dirExists = true;
        File imgDir = new File(savePath);
        if (!imgDir.exists()) {
            dirExists = imgDir.mkdirs();
        }
        if (!dirExists) {
            return "";
        }
        File filePic;
        try {
            filePic = new File(savePath + name + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            if (baos == null) {
                return "";
            }
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
            int options = 90;

            while (baos.toByteArray().length / 1024 > 50) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                baos.reset(); // 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);//
// 这里压缩options%,把压缩后的数据存放到baos中
                if (options > 10) {//设置最小值,防止低于0时出异常
                    options -= 10;// 每次都减少10
                    Log.d(TAG, "saveAttendBitmap: option " + options);
                }
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//
// 把压缩后的数据baos存放到ByteArrayInputStream中
            Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//
            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            Log.d(TAG, "saveAttendBitmap:  " + filePic.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("xxx", "saveBitmap: 2return");
            return null;
        }

        return filePic.getAbsolutePath();
    }

    //删除文件或文件夹
    public static boolean delete(String delFile) {
        File file = new File(delFile);
        if (!file.exists()) {
//            Toast.makeText(getApplicationContext(), "删除文件失败:" + delFile + "不存在!", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "delete: 删除文件夹失败 " + delFile + "不存在");
            return false;
        } else {
            if (file.isFile()) {
                return deleteSingleFile(delFile);
            } else {
                return deleteDirectory(delFile);
            }
        }
    }


    /**
     * 删除单个文件
     *
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功!");
                return true;
            } else {
//                Toast.makeText(getApplicationContext(), "删除单个文件" + filePath$Name + "失败!", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "deleteSingleFile: 删除单个文件" + filePath$Name + "失败");
                return false;
            }
        } else {
            Log.e(TAG, "deleteSingleFile: 删除单个文件" + filePath$Name + "不存在");
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param filePath 要删除的目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!filePath.endsWith(File.separator))
            filePath = filePath + File.separator;
        File dirFile = new File(filePath);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            Log.d(TAG, "deleteDirectory: 删除目录失败:" + filePath + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (File file : files) {
            // 删除子文件
            if (file.isFile()) {
                flag = deleteSingleFile(file.getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (file.isDirectory()) {
                flag = deleteDirectory(file
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            Log.d(TAG, "deleteDirectory: 删除目录失败:");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            Log.e("--Method--", "Copy_Delete.deleteDirectory: 删除目录" + filePath + "成功!");
            return true;
        } else {
            Log.d(TAG, "deleteDirectory: 删除目录:" + filePath + "失败!");
            return false;
        }
    }

    //camera 返回nv21数据转bitmap
    public static Bitmap NV21ToBitmap(byte[] nv21, Camera.Size size) {
        YuvImage image = new YuvImage(nv21, ImageFormat.NV21, size.width, size.height, null);
        Bitmap bitmap = null;
        if (image != null) {
            try {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compressToJpeg(new Rect(0, 0, size.width, size.height), 80, stream);
                bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 获取图片文件的信息,是否旋转了90度,如果是则反转
     *
     * @param bitmap 需要旋转的图片
     * @param path   图片的路径
     */
    public static Bitmap reviewPicRotate(Bitmap bitmap, String path) {
        int degree = getPicRotate(path);
        if (degree != 0) {
            Matrix m = new Matrix();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            m.setRotate(degree); // 旋转angle度
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);// 从新生成图片
        }
        return bitmap;
    }
    /**
     * 读取图片文件旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片旋转的角度
     */
    public static int getPicRotate(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL
            );
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
    /**
     * 计算图片的压缩比例;
     *
     * @param options   图片处理
     * @param reqWidth  压缩的宽度
     * @param reqHeight 压缩的高度;
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
                                            int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            LogUtils.i("heightRatio:" + ((float) height / (float) reqHeight)
                    + "\nwidthRatio:" + ((float) width / (float) reqWidth));
//            inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
            //去缩放更小的那个:
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        // 保证size为1 、2、 4 这样的数,因为3 、5 之类会有异常。
        if (inSampleSize > 1 && inSampleSize % 2 != 0) {
            inSampleSize = inSampleSize - 1;
        }

        return inSampleSize;
    }
    /**
     * 压缩图片
     *
     * @param filePath 传入要压缩的图片的路径
     * @param width    目标width
     * @param height   目标height
     * @return
     * @throws IOException
     */
    public static Bitmap getSmallBitmap(String filePath, int width, int height) throws IOException {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, width, height);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        File file = new File(filePath);
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        assert fs != null;
        Bitmap bitmap = BitmapFactory.decodeFileDescriptor(
                fs.getFD(), null, options
        );
        // Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        if (bitmap == null) {
            return null;
        }
        // bitmap = reviewPicRotate(bitmap, filePath);

        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            // 处理图片 可修改保存格式和 质量
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        } finally {
            try {
                if (baos != null) baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
    /**
     * 压缩图片
     *
     * @param filePath 传入要压缩的图片的路径
     * @param size     要压缩的大小
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath, int size) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = size;
        Log.i("Bitmap", "--" + options.inSampleSize);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        File file = new File(filePath);
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFileDescriptor(
                    fs.getFD(), null, options
            );
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //    Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
        if (bitmap == null) {
            return null;
        }
        // 可选
        // bitmap = reviewPicRotate(bitmap, filePath);

        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            // 可定义
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, baos);
        } finally {
            try {
                if (baos != null) baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
    /**
     * @param resources 传入Resources
     * @param resid     资源ID
     * @param size      要压缩的大小
     * @return
     */
    public static Bitmap getSmallBitmap(Resources resources, int resid, int size) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resid, options);

        // Calculate inSampleSize
        options.inSampleSize = size;
        Log.i("Bitmap", "--" + options.inSampleSize);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, resid, options);
        if (bitmap == null) {
            return null;
        }
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        } finally {
            try {
                if (baos != null) baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
    /**
     * @param resources 传入Resources
     * @param resid     资源ID
     * @param width     目标width
     * @param height    目标height
     * @return
     */
    public static Bitmap getSmallBitmap(Resources resources, int resid, int width, int height) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resid, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, width, height);
        Log.i("Bitmap", "--" + options.inSampleSize);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, resid, options);
        if (bitmap == null) {
            return null;
        }
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        } finally {
            try {
                if (baos != null) baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
    /**
     * 画一个圆角图
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        Bitmap output = Bitmap.createBitmap(
                bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888
        );
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
    /**
     * 缩放Bitmap图片
     **/
    public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    /**
     * 转换图片成圆形
     *
     * @param bitmap 传入Bitmap对象
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect(
                (int) left, (int) top, (int) right, (int) bottom
        );
        final Rect dst = new Rect(
                (int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom
        );
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值