Android实用工具之三—图片处理工具
来源:互联网 发布:剑三插件怎么下载数据 编辑:程序博客网 时间:2024/05/16 17:13
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); }}
0 0
- Android实用工具之三—图片处理工具
- Android实用工具类-GrallyAndPhotoUtils图片处理工具
- Android实用工具之二—APK工具
- Android工具类之Bitmap图片处理
- Android工具类之Bitmap图片处理
- Android实用工具之一—时间戳工具
- android 处理图片工具
- android 处理图片工具
- android 处理图片工具
- android 处理图片工具
- android 处理图片工具
- android 处理图片工具
- android 处理图片工具
- android 图片处理工具
- 三种图片处理工具
- Android开发中实用工具之--Log工具类
- Android 实用工具之HierarchyViewer
- Android 实用工具之emulator
- unreal 1
- [树]二叉排序树的建立与先序遍历
- 关于烂代码的那些事(中)
- 丁帅自媒体
- [FastDFS] 文件路径M00是什么意思
- Android实用工具之三—图片处理工具
- 总结关系型数据库三范式
- poj 1177 Picture 【线段树 扫描线 求轮廓周长】
- unreal 2
- [FastDFS] 关于FastDFS的一点问题
- 关于烂代码的那些事(下)
- uva201
- unreal 3
- Markdown使用笔记