Android实用工具之三—图片处理工具

package net.hyww.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.widget.Toast;
import com.nostra13.universalimageloader.utils.StorageUtils;
import net.hyww.widget.simplecropimage.CropImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @HYWW 图片处理类 2013-10-22
 */
public class PicUtils {
    private static final boolean DBG = true;
    private static final String TAG = PicUtils.class.getSimpleName();

    /**
     * 图片缓存技术的核心类,用于缓存所有下载好的图片,在程序内存达到设定值时会将最少最近使用的图片移除掉。
     */
    public static LruCache<String, Bitmap> mMemoryCache;
    /**
     * 从系统相册获取相片requestCode
     */
    public static final int FORM_PHOTOS_CODE = 1;
    /**
     * 从系统相机获取相片requestCode
     */
    public static final int FORM_OS_CAMERA_CODE = 2;
    /**
     * 相片裁剪requestCode
     */
    public static final int CROP_PIC_CODE = 3;

    public static final int PICK_PIC_REQUEST_CODE = 4;

    public static final int VERTICAL = 1;
    public static final int HORIZONTAL = 2;

    public static final String[] picType = {"bmp", "dib", "gif", "jfif",
            "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};
    
    public static File getImageFile(Context context,String fileName) {
      File f = null;
      if (!TextUtils.isEmpty(FileUtils.getExternalDir(context)))
         f = new File(fileName);

      if (f!=null&&f.getParentFile()!=null&&!f.getParentFile().exists())
         f.getParentFile().mkdirs();

      if (f!=null&&!f.exists()) {
         try {
            f.createNewFile();
         } catch (IOException e) {
            return null;
         }
      }

      return f;
   }

    public static File getFile(Context context,String fileName) {
        File f = null;
        if (!TextUtils.isEmpty(FileUtils.getExternalDir(context)))
            f = new File(fileName);

        if (f!=null&&f.getParentFile()!=null&&!f.getParentFile().exists())
            f.getParentFile().mkdirs();

        if (f!=null&&!f.exists()) {
            try {
                f.createNewFile();
            } catch (IOException e) {
                return null;
            }
        }

        return f;
    }
    
    public static boolean isPhotoExist(Context context,String fileName) {
       File f = null;
      if (!TextUtils.isEmpty(FileUtils.getExternalDir(context)))
         f = new File(fileName);
        if (f == null){
            return false;
        }
      return f.exists();
    }

    /**
     * 使用相机生成照片
     *
     * @param context
     */
    public static void getPicFromCamera(Activity context,File saveFile) {
        try {
            camerasaveFile=saveFile;
            Intent intent_camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent_camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(saveFile));
            context.startActivityForResult(intent_camera, PicUtils.FORM_OS_CAMERA_CODE);
        } catch (Exception e) {
        }
    }

    /**
     * 选择新照相
     *
     * @param context
     */
    public static File camerasaveFile;
    public static void getPicFromCamera(Fragment context,File saveFile) {
        try {
            camerasaveFile=saveFile;
            Intent intent_camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent_camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(saveFile));
            context.startActivityForResult(intent_camera, PicUtils.FORM_OS_CAMERA_CODE);
        } catch (Exception e) {
        }
    }

    /**
     * 系统相册选择照片
     *
     * @param context
     */
    public static void getPicFromPhotos(Activity context) {
        try{
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
            intent.setType("image/*");
//        intent.putExtra("output", Uri.fromFile(new File(new File(
//                IMAGE_FILE_SAVE_PATH), oldPicName)));
            context.startActivityForResult(intent, FORM_PHOTOS_CODE);
        }catch (Exception e){
        }
    }

    /**
     * 系统相册选择照片
     *
     * @param context
     */
    public static void getPicFromPhotos(Fragment context) {
        try{
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
//        intent.putExtra("output", Uri.fromFile(new File(new File(
//                IMAGE_FILE_SAVE_PATH), oldPicName)));
        context.startActivityForResult(intent, FORM_PHOTOS_CODE);
        }catch (Exception e){
        }
    }

//    /**
//     * 调用系统裁剪图片
//     * @param context
//     * @param oldPicName   原图位置
//     * @param cropPicName  裁剪后位置
//     * @param cropPicWidth 裁剪后宽
//     * @param x            裁剪比例x//     * @param y            裁剪比例y//     */
//    public static void getCropPic(Activity context, String oldPicName,
//                                  String cropPicName, int cropPicWidth, int x, int y) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        if (TextUtils.indexOf(oldPicName, "/") >= 0) {
//            intent.setDataAndType(Uri.fromFile(new File(oldPicName)), "image/*");
//        } else {
//            intent.setDataAndType(
//                    Uri.fromFile(new File(IMAGE_FILE_SAVE_PATH, oldPicName)),
//                    "image/*");
//        }
//        intent.putExtra("crop", "true");
//        intent.putExtra("aspectX", x);
//        intent.putExtra("aspectY", y);
//        intent.putExtra("outputX", cropPicWidth);
//        intent.putExtra("outputY", cropPicWidth * y / x);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.putExtra("return-data", true);
        intent.putExtra(CropImage.IMAGE_PATH, path);
//        intent.putExtra("output", Uri.fromFile(new File(new File(
//                IMAGE_FILE_SAVE_PATH), cropPicName)));
//        context.startActivityForResult(intent, CROP_PIC_CODE);
//    }


    private static Intent getCropIntent(Activity activity, String path, int x, int y) {
        Intent intent = new Intent(activity, CropImage.class);

        // tell CropImage activity to look for image to crop
        intent.putExtra(CropImage.IMAGE_PATH, path);
        String outPutPath = null;
        File outFile= OtherUtils.getFileFloder(activity,Environment.DIRECTORY_PICTURES);
        if (outFile==null){
            outPutPath=FileUtils.getExternalDir(activity);
        }else{
            outPutPath = outFile.getAbsolutePath();
        }
        intent.putExtra(CropImage.IMAGE_PATH_OUT_PUT,
                outPutPath + File.separator + getImageSaveName("crop"));

        // allow CropImage activity to rescale image
        intent.putExtra(CropImage.SCALE, true);

        // if the aspect ratio is fixed to ratio 1/1
        intent.putExtra(CropImage.ASPECT_X, x);
        intent.putExtra(CropImage.ASPECT_Y, y);
        intent.putExtra(CropImage.OUTPUT_X, x);
        intent.putExtra(CropImage.OUTPUT_Y, y);
        return intent;
    }

    /**
     * 裁剪图片
     *
     * @param context
     * @param path
     * @param x
     * @param y
     */
    public static void cropImage(Activity context, String path, int x, int y) {
        try {
            context.startActivityForResult(getCropIntent(context, path, x, y), CROP_PIC_CODE);
        } catch (ActivityNotFoundException e) {
            String errorMessage = "Whoops - your device doesn't support the crop action!";

            Toast toast = Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
            e.printStackTrace();
        }
    }

    /**
     * 裁剪图片
     *
     * @param fragment
     * @param path
     * @param x
     * @param y
     */
    public static void cropImage(Fragment fragment, String path, int x, int y) {
        try {
            fragment.startActivityForResult(getCropIntent(fragment.getActivity(), path, x, y), CROP_PIC_CODE);
        } catch (ActivityNotFoundException e) {
            String errorMessage = "Whoops - your device doesn't support the crop action!";

            Toast toast = Toast.makeText(fragment.getActivity(), errorMessage, Toast.LENGTH_SHORT);
            toast.show();
            e.printStackTrace();
        }
    }

    /**
     * 获取图片存储名称
     *
     * @return
     */
    public static String getImageSaveName() {
        return getImageSaveName(null);
    }

    /**
     * 获取图片存储名称
     *
     * @return
     */
    public static String getImageSaveName(String suffix) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");// 获取当前时间,进一步转化为字符串
        Date date = new Date(System.currentTimeMillis());
        String str = format.format(date);
        String fileName = null;
        if (TextUtils.isEmpty(suffix)) {
            fileName = str + ".jpg";
        } else {
            fileName = str + "_" + suffix + ".jpg";
        }
        return fileName;
    }

//    /**
//     * 照片压缩 方向调整
//     *
//     * @param src 图片地址
//     */
//    public static Bitmap picRotaingAndCompression(String src) {
//        return picRotaingAndCompression(src, "");
//    }
//
//    public static Bitmap picRotaingAndCompression(String src, String targetSrc) {
//        if (TextUtils.isEmpty(targetSrc)) {
//            targetSrc = src.substring(src.lastIndexOf("/") + 1);
//        }
//        int degree = readPictureDegree(new File(src).getAbsolutePath());
//
//        BitmapFactory.Options newOpts = new BitmapFactory.Options();
//        // 开始读入图片,此时把options.inJustDecodeBounds 设回true//        newOpts.inJustDecodeBounds = true;
//        Bitmap bitmap = BitmapFactory.decodeFile(src, newOpts);// 此时返回bm为空
//
//        newOpts.inJustDecodeBounds = false;
//        int w = 0;
//        if (degree == 90 || degree == 270) {
//            w = newOpts.outHeight;
//        } else {
//            w = newOpts.outWidth;
//        }
//        if (w < 0)
//            return null;
//        float ww = 1000f;//
//        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
//        int be = 1;// be=1表示不缩放
//        // if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
//        be = (int) (w / ww);
//        // } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
//        // be = (int) (newOpts.outHeight / hh);
//        // }
//        if (be <= 0)
//            be = 1;
//        newOpts.inSampleSize = be;// 设置缩放比例
//        try {
//            // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false//            bitmap = BitmapFactory.decodeFile(src, newOpts);
//            try {
//                if (degree > 0) {
//                    bitmap = rotaingImageView(degree, bitmap);
//                }
//                OutputStream output = new FileOutputStream(IMAGE_FILE_SAVE_PATH
//                        + targetSrc);
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, output);
//                // }
//                output.flush();
//                output.close();
//                newOpts = new BitmapFactory.Options();
//                if (w > 500) {
//                    newOpts.inSampleSize = 4;
//                } else {
//                    newOpts.inSampleSize = 1;
//                }
//                // 开始读入图片,此时把options.inJustDecodeBounds 设回true//                bitmap = BitmapFactory.decodeFile(IMAGE_FILE_SAVE_PATH
//                        + targetSrc, newOpts);// 此时返回bm为空
//            } catch (IOException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        } catch (Exception e) {
//        } catch (OutOfMemoryError e) {
//            System.gc();
//        }
//
//        return bitmap;
//        // return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
//    }

    public static boolean isPic(String path) {
        String tmpName = path.substring(path.lastIndexOf(".") + 1,
                path.length());
        for (int i = 0; i < picType.length; i++) {
            // 判断单个类型文件的场合
            if (picType[i].equals(tmpName.toLowerCase())) {
                return true;
            }
        }
        return false;
    }


    /**
     * 压缩图片,处理某些手机拍照角度旋转的问题
     */
    public static String compressImage(Context context,String filePath)
            throws FileNotFoundException {

        Bitmap bm = getSmallBitmap(context, filePath);

        File srcFile = new File(filePath);
        File outputFile = new File(
                StorageUtils.getCacheDirectory(context),
                srcFile.getName());

        int degree = readPictureDegree(filePath);

        if (degree != 0) {// 旋转照片角度
            bm = rotaingImageView(degree, bm);
        }

        FileOutputStream out = new FileOutputStream(outputFile);

        bm.compress(Bitmap.CompressFormat.JPEG, 70, out);

        return outputFile.getPath();
    }

    // 根据路径获得图片并压缩,返回bitmap用于显示
    public static Bitmap getSmallBitmap(Context context,String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
       if(NetWorkUtil.getAPNType(context) == NetWorkUtil.NetType.wifi){
           options.inSampleSize = calculateInSampleSize(options, 1920, 1920);
       }else{
           options.inSampleSize = calculateInSampleSize(options, 1280, 1280);
       }
//        options.inSampleSize = calculateInSampleSize(options, 800, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(filePath, options);
    }

    // 根据路径获得图片并压缩,返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath,int width,int height) {
        try {
            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;

            return BitmapFactory.decodeFile(filePath, options);
        } catch (Throwable e) {
            return null;
        }
    }

    // 计算图片的缩放值
    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 = new BigDecimal((float) height / (float) reqHeight).setScale(0, BigDecimal.ROUND_HALF_UP)
                    .intValue();
            final int widthRatio = new BigDecimal((float) width / (float) reqWidth).setScale(0, BigDecimal.ROUND_HALF_UP)
                    .intValue();
            /*final int heightRatio = new BigDecimal((float) height / (float) reqHeight).setScale(0, BigDecimal.ROUND_UP)
                    .intValue();
            final int widthRatio = new BigDecimal((float) width / (float) reqWidth).setScale(0, BigDecimal.ROUND_UP)
                    .intValue();*/
            inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
            if(inSampleSize<=1){
                inSampleSize=1;
            }
        }
        return inSampleSize;
    }

    /**
     * 读取图片属性:旋转的角度
     *
     * @param path
     *            图片绝对路径
     * @return degree 旋转的角度
     */
    public static int readPictureDegree(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 angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        if(angle==0)
            return  bitmap;
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
    }




    /**
     * 将一张图片存储到LruCache中。
     *
     * @param key
     *            LruCache的键,这里传入图片的URL地址。
     * @param bitmap
     *            LruCache的键,这里传入从网络上下载的Bitmap对象。
     */
    public static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache == null) {
            initCacheSize();
        }
        if (!TextUtils.isEmpty(key)&&getCacheBitmap(key) == null && bitmap != null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    public static Bitmap getCacheBitmap(String path) {
        if (mMemoryCache == null) {
            initCacheSize();
        }
        if(TextUtils.isEmpty(path))
            return null;
        return mMemoryCache.get(path);
    }

    public static void initCacheSize() {
        // 获取应用程序最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 5;
        // 设置图片缓存大小为程序最大可用内存的1/8
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    public static void clearCache() {
        if(mMemoryCache!=null)
            mMemoryCache.evictAll();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值