Android手机拍照和手机相册选取图片的工具类ImageUtils

package com.shentaiwang.jsz.savepatient.util;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
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.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.BufferedOutputStream;
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;
import java.util.Locale;

/**
 * Created by user on 2016/12/16.
 */
public class ImageUtil {
    public static final int CODE_SETHDIMG_ALNUM = 1;
    public static final int CODE_SETHDIMG_CAM = 2;
    public static final int CROP_IMG = 100;

    public File camImgFile = null;
    public File cropImgFile = null;

    public void gotoCam(Context context) {
        try {
        //获取当前系统的android版本号
        int currentApiVersion = android.os.Build.VERSION.SDK_INT;

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String str = dateFormat.format(new Date(System.currentTimeMillis()));

        //设置保存拍摄照片路径(DCIM/Camera/Modle_PictureWall_img_20170212_122223.jpg)
        //路径默认,若修改则不能保存照片
        camImgFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "/Camera/Modle_PictureWall_img_" + str + ".jpg");

        Uri outputImgUriFromCam = null;
        if (currentApiVersion < 24) {
            outputImgUriFromCam = Uri.fromFile(camImgFile);
        } else {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, camImgFile.getAbsolutePath());

                outputImgUriFromCam = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

        }

        //跳转到照相机拍照
        Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        it.putExtra(MediaStore.EXTRA_OUTPUT, outputImgUriFromCam);

        ((Activity) context).startActivityForResult(it, CODE_SETHDIMG_CAM);
//        startActivityForResult(it,CODE_SETHDIMG_CAM);
        }catch (Exception e){
            Toast.makeText(context,"请开启摄像权限",Toast.LENGTH_SHORT).show();
        }
    }


    public void gotoAlbum(Context context) {
        Intent it = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        ((Activity) context).startActivityForResult(it, CODE_SETHDIMG_ALNUM);
//        startActivityForResult(it,CODE_SETHDIMG_ALNUM);
    }

    public void cropImg(Context context, boolean isFromCam, boolean isSetHd, Intent data, String fileName) {
        File inputFile = null;

        if (isFromCam) {
            inputFile = camImgFile;
        } else {
            Log.d("ImageUtil", "cropImg:图片数据: "+data.getData());
            inputFile = new File(getRealPathFromURI(context, data.getData()));
        }

        //设置保存路径名称
        cropImgFile = new File(context.getExternalFilesDir(fileName), String.valueOf(System.currentTimeMillis()));

        WindowManager manager = ((Activity) context).getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);

        Intent it = new Intent("com.android.camera.action.CROP");
        it.setDataAndType(getImageContentUri(context, inputFile), "image/*");

        it.putExtra("output", Uri.fromFile(cropImgFile));
        it.putExtra("crop", "true");
        it .putExtra("scale",true);//黑边
        it .putExtra("scaleUpIfNeeded",true);//黑边


        if (isSetHd) {
            // 裁剪框比例
            it.putExtra("aspectX", 1);
            it.putExtra("aspectY", 1);

            // 输出图片大小
            it.putExtra("outputX", outMetrics.widthPixels / 2);
            it.putExtra("outputY", outMetrics.widthPixels / 2);
        } else {
            // 裁剪框比例
            it.putExtra("aspectX", 3);
            it.putExtra("aspectY", 2);

            // 输出图片大小
            it.putExtra("outputX", 600);
            it.putExtra("outputY", 400);
        }

        // 返回格式
        it.putExtra("outputFormat", "JPEG");

        ((Activity) context).startActivityForResult(it, CROP_IMG);
//        startActivityForResult(it, CROP_IMG);
    }

    public String getRealPathFromURI(Context context, Uri uri) {
        String mImgPath;
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
        if(cursor!=null){
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            mImgPath=picturePath;
        }else{
            mImgPath=uri.getPath();
        }
        return mImgPath;



    }

    public Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{"_id"}, "_data=? ", new String[]{filePath}, (String) null);
        if (cursor != null && cursor.moveToFirst()) {
            int values1 = cursor.getInt(cursor.getColumnIndex("_id"));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + values1);
        } else if (imageFile.exists()) {
            ContentValues values = new ContentValues();
            values.put("_data", filePath);
            return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }

    public void refreshAlbum(Context context, String path) {
        context.sendBroadcast(new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", Uri.parse("file://" + path)));
    }


    public static byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 根据byte数组生成文件
     *
     * @param bytes 生成文件用到的byte数组
     */
    public static boolean createFileWithByte(byte[] bytes) {
        String fileName = "portrait.png";


        // TODO Auto-generated method stub
        /**
         * 创建File对象,其中包含文件所在的目录以及文件的命名
         *
         */
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//判断SDCard进行操作
            //获取SDCard指定目录下
            String sdCardDir = Environment.getExternalStorageDirectory() + "/CropImage/";
            File dirFile = new File(sdCardDir);//目录转换成文件夹
            if (!dirFile.exists()) {//如果不存在,就建立这个文件夹
                dirFile.mkdir();
            }
            File file = new File(sdCardDir, fileName);
            // 创建FileOutputStream对象
            FileOutputStream outputStream = null;
            // 创建BufferedOutputStream对象
            BufferedOutputStream bufferedOutputStream = null;
            try {
                // 如果文件存在则删除
                if (file.exists()) {
                    file.delete();
                }
                // 在文件系统中根据路径创建一个新的空文件
                file.createNewFile();
                // 获取FileOutputStream对象
                outputStream = new FileOutputStream(file);
                // 获取BufferedOutputStream对象
                bufferedOutputStream = new BufferedOutputStream(outputStream);
                // 往文件所在的缓冲输出流中写byte数据
                bufferedOutputStream.write(bytes);
                // 刷出缓冲输出流,该步很关键,要是不执行flush()方法,那么文件的内容是空的。
                bufferedOutputStream.flush();
            } catch (Exception e) {
                // 打印异常信息
                e.printStackTrace();
            } finally {
                // 关闭创建的流对象
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bufferedOutputStream != null) {
                    try {
                        bufferedOutputStream.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
            }
            return true;
        }
        return false;

    }

    /**
     * 获取文件路径并转换成Bitmap
     *
     * @param filepath
     * @return
     */
    public static Bitmap getFilePath(String filepath) {
        File file = new File(filepath);
        Bitmap bm = null;
        if (file.exists()) {
            bm = BitmapFactory.decodeFile(filepath);
        }
        return bm;
    }

    public static Bitmap Bytes2Bitmap(byte[] bytes) {
        if (bytes.length != 0) {
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        } else {
            return null;
        }
    }

    public static Bitmap toRoundCorner(Bitmap bitmap, float ratio) {//把正方形图片转化为圆形,ratio为2
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        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);
        canvas.drawRoundRect(rectF, bitmap.getWidth() / ratio,
                bitmap.getHeight() / ratio, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;

    }

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


    public static String savePhotoToSDCard(Bitmap bitmap) {
        String photoName = "";
        if (checkSDCardAvailable()) {
            // 图片时间命名
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date(System.currentTimeMillis());
            photoName = format.format(date);
            // 存储至DCIM文件夹下
            File dir = new File(Environment
                    .getExternalStorageDirectory() + "/Stw/temp/save/");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File photoFile = new File(dir.getAbsolutePath(), photoName + ".png");
            Bitmap photoBitmap = bitmap;
//            FileOutputStream fileOutputStream = null;
//            try {
//                fileOutputStream = new FileOutputStream(photoFile);
            if (photoBitmap != null) {
//                    double maxSize = 400.00;
                // 将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                photoBitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
                int options = 80;//先压缩到80%
                while (baos.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
                    if (options <= 0) {//有的图片过大,可能当options小于或者等于0时,它的大小还是大于目标大小,于是就会发生异常,异常的原因是options超过规定值。所以此处需要判断一下
                        break;
                    }
                    baos.reset();// 重置baos即清空baos
                    options -= 10;// 每次都减少10
                    bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                }
//                    byte[] b = baos.toByteArray();
//                    // 将字节换成KB
//                    double mid = b.length / 1024;
//                    // 判断bitmap占用空间是否大于允许空间 如果大于则压小于则不压缩
//                    if (mid > maxSize) {
//                        // 获取bitmap大小 是允许最大大小的多少
//                        double i = mid / maxSize;
//                        // 压缩 此处用到平方将宽带和高度压缩掉对应的平方根
//                        // 保持刻度和高度和原bitmap比率,压缩后也达到了大小占用空间的大小)
//                        photoBitmap = zoomImage(photoBitmap,
//                                photoBitmap.getWidth() / Math.sqrt(i),
//                                photoBitmap.getHeight() / Math.sqrt(i));
//                    }
//                    if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
//                            fileOutputStream)) {
//                        fileOutputStream.flush();
//                        // fileOutputStream.close();
//                    }
                try {
                    FileOutputStream fos = new FileOutputStream(photoFile);
                    fos.write(baos.toByteArray());
                    fos.close();
                    baos.close();
                    return photoFile.getAbsolutePath();
                } catch (Exception e) {

                }


            }
//            } catch (FileNotFoundException e) {
//                photoFile.delete();
//                e.printStackTrace();
//            } catch (IOException e) {
//                photoFile.delete();
//                e.printStackTrace();
//            } finally {
//                try {
//                    if (fileOutputStream != null) {
//                        fileOutputStream.close();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

        }

        return null;
    }

    /**
     * 压缩图片
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放�?
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    //检查sd卡是否存在
    public static boolean checkSDCardAvailable() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }


}









你可能感兴趣的:(Android)