package www.tydic.com.util;import android.app.Activity;import android.content.ActivityNotFoundException;import android.content.ContentResolver;import android.content.Context;import android.content.Intent;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.provider.MediaStore;import android.util.Base64;import android.widget.Toast;import com.yalantis.ucrop.UCrop;import java.io.BufferedOutputStream;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.InputStreamReader;import java.io.StringWriter;import java.text.SimpleDateFormat;import java.util.Date;/** * Created by LIUREN on 2017/2/16. */public class PhoneUtils { /** * 使用方式: * * 1.获取拍照原图Bitmap: PhoneUtils.onInitPhoneResult(this,requestCode,resultCode,data,"init.jpg") * 参数列表:上下文环境,请求码,响应码,返回的数据,图片名称 * 注:请求码,响应码,返回的数据是onActivityResult()方法的参数 * 2.获取一定压缩比例的原图 * (1)方式一:拍照保存:PhoneUtils.onInitPhoneResult(this,requestCode,resultCode,data,"init.jpg") * 将拍照保存路径下的照片进行处理 PhoneUtils.getBitmapOption(Environment.getExternalStorageDirectory() + "/phone/init.jpg", 20)) * 参数:拍照保存的全路径,缩放比列(20表示缩放比为原图的1/20) * (2)方式二:将现有的bitmap进行压缩处理: * 将bitmap保存:PhoneUtils.saveBitmapFile(bitmap,filePath); * 参数:有效的bitmap,保存的全路径 * 将保存路径下的bitmap进行压缩:PhoneUtils.getBitmapOption(filePath, 20)) * 参数:保存的全路径,缩放比列 * 3.保存一个bitmap:PhoneUtils.saveBitmapFile(bitmap,filePath); * 参数:有效的bitmap,保存的全路径 * 4.缩放一个一个路径下的bitmap:PhoneUtils.getBitmapOption(filePath, 20)) * 参数:保存的全路径,缩放比列 * 5.获取一个拍照缩略图: * 拍照:PhoneUtils.getAbbreviationsPhone(this); * 在onActivityResult()中PhoneUtils.onAbbreviationsPhoneResult(this,requestCode,resultCode,data) * 参数:上下文,请求码,响应码,返回数据 * 6.获取相册选择的单个图片: * (1):得到一个图片的bitmap: * 调用相册:PhoneUtils.getAlbumPhone(上下文环境); * 在onActivityResult()中PhoneUtils.onmyPhoneResult(this,requestCode,resultCode,data);得到bitmap * (2):得到一个图片的file: * 调用相册:PhoneUtils.getAlbumPhone(上下文环境); * 在onActivityResult()中PhoneUtils.onmyPhoneFileResult(this,requestCode,resultCode,data);得到file * 7.获取拍照剪切图片: * 调用PhoneUtils.getSheraPack(this,"cut.jpg"); * 在在onActivityResult()中监听PHONE_CODE_SHEAR_PACK响应码调用Uri packUri =PhoneUtils.onInitCutPhoneResult(this,requestCode,resultCode,data,"cut.jpg");获得拍照的原图 * 在调用PhoneUtils.crop(this,packUri)进去截图 * 在在onActivityResult()中监听PHONE_CODE__CUT截图完毕响应码 Bitmap photo=data.getParcelableExtra("data"); * 获得phone这个截图后的bitmap * 8.获取相册剪切图片: * 调用PhoneUtils.getSheraMyPhone(this);进入相册请求图片 * 在在onActivityResult()中监听PHONE_CODE__SHEAR_MYPHONE响应码调用Uri myUri=PhoneUtils.onCutmyPhoneResult(this,requestCode,resultCode,data);;获得相册图片uri * 在调用PhoneUtils.crop(this,myUri)进去截图 * 在在onActivityResult()中监听PHONE_CODE__CUT截图完毕响应码 Bitmap photo=data.getParcelableExtra("data"); * 获得phone这个截图后的bitmap * 9.选择相册多张图片: * */ //拍照获取缩略图的请求码 public final static int PHONE_CODE_ABBPHONE=0; //拍照获取相册图片的请求码 public final static int PHONE_CODE_ALBUNMPHONE=1; //拍照获原图图的请求码 public final static int PHONE_CODE_INITPACKPHONE=2; //拍照剪切图片请求码 public final static int PHONE_CODE_SHEAR_PACK=3; //相册剪切图片请求码 public final static int PHONE_CODE__SHEAR_MYPHONE=4; //剪切请求码 public final static int PHONE_CODE__CUT=5; /** * 调用系统相机获取拍照缩略图 */ public static void getAbbreviationsPhone(Activity activity){ //为安全起见,拿到sdcard是否可用的状态码 String state = Environment.getExternalStorageState(); //如果sd卡可用 if (state.equals(Environment.MEDIA_MOUNTED)){ //如果可用 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); activity.startActivityForResult(intent,PHONE_CODE_ABBPHONE); }else { Toast.makeText(activity,"sdcard状态异常", Toast.LENGTH_SHORT).show(); } } /** * 调用系统相册获取获取单张图片uri */ public static void getAlbumPhone(Activity activity){ Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*");//相片类型 activity.startActivityForResult(intent,PHONE_CODE_ALBUNMPHONE); } /** * 调用相机获取剪切图 */ public static void getSheraPack(Activity activity,String fileName){ //先验证手机是否有sdcard String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { try { //将拍摄的照片保存在一个指定好的文件下 File dir= new File(Environment.getExternalStorageDirectory() + "/cut"); if (!dir.exists()) dir.mkdirs(); Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); File f = new File(dir, fileName); Uri u = Uri.fromFile(f); intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0); intent.putExtra(MediaStore.EXTRA_OUTPUT, u); activity.startActivityForResult(intent, PHONE_CODE_SHEAR_PACK); } catch (ActivityNotFoundException e) { Toast.makeText(activity, "没有找到储存目录", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(activity, "sdcard状态异常", Toast.LENGTH_LONG).show(); } } /** * 调用相册获取剪切图 */ public static void getSheraMyPhone(Activity activity){ Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*");//相片类型 activity.startActivityForResult(intent,PHONE_CODE__SHEAR_MYPHONE); } /** * 调用本地相机获取拍照原图 * filename 图片文件名 xxx.jpg * 返回值 图片的路径 * 如果失败返回空 */ public static void getInitPhone(Activity activity,String fileName) { //先验证手机是否有sdcard String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { try { //将拍摄的照片保存在一个指定好的文件下 File dir= new File(Environment.getExternalStorageDirectory() + "/phone"); if (!dir.exists()) dir.mkdirs(); Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); File f = new File(dir, fileName); Uri u = Uri.fromFile(f); intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0); intent.putExtra(MediaStore.EXTRA_OUTPUT, u); activity.startActivityForResult(intent, PHONE_CODE_INITPACKPHONE); } catch (ActivityNotFoundException e) { Toast.makeText(activity, "没有找到储存目录", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(activity, "sdcard状态异常", Toast.LENGTH_LONG).show(); } } /** * onActivityResult拍照后返回原图 */ public static Bitmap onInitPhoneResult(Activity activity,int requestCode, int resultCode, Intent data,String fileName){ try { File f=new File(Environment.getExternalStorageDirectory() + "/phone/"+fileName); Uri u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(activity.getContentResolver(), f.getAbsolutePath(), null, null)); Bitmap bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), u); return bitmap; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * onActivityResult拍照后返回原图Uri, 剪切常用 */ public static Uri onInitCutPhoneResult(Activity activity,int requestCode, int resultCode, Intent data,String fileName){ File f=new File(Environment.getExternalStorageDirectory() + "/cut/"+fileName); Uri u = null; try { u = Uri.parse(MediaStore.Images.Media.insertImage(activity.getContentResolver(), f.getAbsolutePath(), null, null)); } catch (FileNotFoundException e) { e.printStackTrace(); } return u; } /** * onActivityResult拍照后返回缩略图的bitmap */ public static Bitmap onAbbreviationsPhoneResult(Activity activity,int requestCode, int resultCode, Intent data){ Bitmap phone = null; if (data.getData() != null|| data.getExtras() != null){ Uri uri =data.getData(); if (uri != null) { phone = BitmapFactory.decodeFile(uri.getPath()); if (phone!=null){ return phone; } } } if (phone == null) { Bundle bundle =data.getExtras(); if (bundle != null){ phone =(Bitmap) bundle.get("data"); if (phone!=null){ return phone; } } else { Toast.makeText(activity.getApplicationContext(), "找不到图片",Toast.LENGTH_SHORT).show(); } } return null; } /** * onActivityResult相册返回的bitmap */ public static Bitmap onmyPhoneResult(Activity activity,int requestCode, int resultCode, Intent data){ Bitmap phone = null; Uri uri = data.getData(); if (uri!=null){ try { phone = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri); if (phone!=null){ return phone; } } catch (IOException e) { e.printStackTrace(); } }else { Toast.makeText(activity.getApplicationContext(), "找不到该图片",Toast.LENGTH_SHORT).show(); } return null; } /** * onActivityResult相册返回的uri 截图多用 */ public static Uri onCutmyPhoneResult(Activity activity, int requestCode, int resultCode, Intent data){ Bitmap phone = null; Uri uri = data.getData(); if (uri!=null){ return uri; }else { Toast.makeText(activity.getApplicationContext(), "找不到该图片",Toast.LENGTH_SHORT).show(); } return null; } /** * onActivityResult相册返回的file */ public static File onmyPhoneFileResult(Activity activity,int requestCode, int resultCode, Intent data){ Bitmap phone = null; Uri uri = data.getData(); if (uri!=null){ return uriToFile(activity,uri); }else { Toast.makeText(activity.getApplicationContext(), "找不到该图片",Toast.LENGTH_SHORT).show(); } return null; } /** * 将bitmap保存到指定的文件路径下 * filepath:"/mnt/sdcard/pic/01.jpg" */ public static void saveBitmapFile(Bitmap bitmap,String filePath){ File file=new File(filePath);//将要保存图片的路径 try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 将指定路径下的图片缩小到原来的几分之一 返回bitmap.当inSampleSize=2时,表示缩小1/2 */ public static Bitmap getBitmapOption(String filePath,int inSampleSize){ System.gc(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inSampleSize = inSampleSize; return BitmapFactory.decodeFile(filePath,options); } /** * uri转file */ public static File uriToFile(Activity activity,Uri uri){ if ( null == uri ) return null; final String scheme = uri.getScheme(); String data = null; if ( scheme == null ) data = uri.getPath(); else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) { data = uri.getPath(); } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) { Cursor cursor = activity.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null ); if ( null != cursor ) { if ( cursor.moveToFirst() ) { int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA ); if ( index > -1 ) { data = cursor.getString( index ); } } cursor.close(); } } File file = new File(data); return file; } /** * bitmap转uri */ public static Uri bitmapToUri(Activity activity,Bitmap bitmap){ return Uri.parse(MediaStore.Images.Media.insertImage(activity.getContentResolver(), bitmap, null,null)); } /** * uri转bitmap */ public static Bitmap bitmapToUri(Activity activity,Uri uri){ Bitmap bitmap=null; try { bitmap= MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri); } catch (IOException e) { } return bitmap; } /** * 调用uCrop工具截图 * @param activity * @param uri */ public static void startCrop(Activity activity,Uri uri){ //裁剪后保存到文件中 Uri sourceUri = uri; SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmss"); Date date = new Date(); String imageName = simpleDateFormat.format(date); Uri destinationUri = Uri.fromFile(new File(activity.getCacheDir(), imageName+".jpeg")); UCrop.of(sourceUri, destinationUri).start(activity,PHONE_CODE__CUT); } /** * 保存图片到相册 * @param context * @param bmp * @param saveAfterName 保存图片的名称需要带后缀名 */ public static String saveImageToGallery(Context context, Bitmap bmp,String saveAfterName) { if (bmp == null){ Toast.makeText(context,"图片为空,无法保存!",Toast.LENGTH_SHORT).show(); return null; } // 首先保存图片 File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee"); if (!appDir.exists()) { appDir.mkdir(); } File file = new File(appDir, saveAfterName); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { Toast.makeText(context,"未发现文件!",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } catch (IOException e) { Toast.makeText(context,"保存出错!",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } catch (Exception e){ Toast.makeText(context,"保存出错!",Toast.LENGTH_SHORT).show(); e.printStackTrace(); } // 最后通知图库更新//注解掉改代码,如果保留,则相册会重复生成多个图片// try {// MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), saveAfterName, null);// } catch (FileNotFoundException e){// e.printStackTrace();// } Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri uri = Uri.fromFile(file); intent.setData(uri); context.sendBroadcast(intent); return String.valueOf(file.getAbsoluteFile()); } /** * 图片转换成Base64位字符串 * @param file * @return */ public static String photo2Base64String (File file){ //将图片文件转化为字节数组字符串,并对其进行Base64编码处理 String imgFile = file.getAbsolutePath(); InputStream in = null; byte[] data = null; //读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } return Base64.encodeToString(data, Base64.DEFAULT);//返回Base64编码过的字节数组字符串 }}
调用相机和相册的方法:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode==RESULT_OK) { switch(requestCode) { case PHONE_CODE_INITPACKPHONE: //返回原图 mPackBitmap=PhoneUtils.onInitPhoneResult(this,requestCode,resultCode,data,"init.jpg"); if (mPackBitmap!=null){ // mInitPachPhoneImageView.setImageBitmap(mPackBitmap); } break; case PHONE_CODE_ABBPHONE: //返回缩略图 Bitmap bitmap1 = PhoneUtils.onAbbreviationsPhoneResult(this, requestCode, resultCode, data); if (bitmap1!=null){ //mFalsePhoneImageView.setImageBitmap(bitmap1); } break; case PHONE_CODE_ALBUNMPHONE: //相册图片 Bitmap bitmap=PhoneUtils.onmyPhoneResult(this,requestCode,resultCode,data); if (bitmap!=null){ //mMyPhoneImageView.setImageBitmap(bitmap); } break; case PHONE_CODE_SHEAR_PACK: cutType=0; //拍照截图返回 //返回原图 Uri packUri=PhoneUtils.onInitCutPhoneResult(this,requestCode,resultCode,data,"cut.jpg"); //进入截图 Log.i("MAINACTVI","666"); PhoneUtils.startCrop(this,packUri); Log.i("MAINACTVI","a"); break; case PHONE_CODE__SHEAR_MYPHONE: cutType=1; //相册截图返回 //返回相册uri Uri myUri=PhoneUtils.onCutmyPhoneResult(this,requestCode,resultCode,data); //进入截图 PhoneUtils.startCrop(this,myUri); break; case PHONE_CODE__CUT: Log.i("MAINACTVI","b"); //截图完毕 Uri photoUri = UCrop.getOutput(data); File newFile = PhoneUtils.uriToFile(OcrPhotoActivity.this,photoUri); //转换为File newCompressedImageBitmap = Compressor.getDefault(this).compressToBitmap(newFile);//对图片进行压缩转换为Bitmap if (cutType==0){ //拍照截图 if(newCompressedImageBitmap!=null){ String imageViewId = (String) SharedPreferencesUtils.get(OcrPhotoActivity.this,"imageViewId",""); if (imageViewId.equals("1")){ ID_img_font.setImageBitmap(newCompressedImageBitmap); SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_font",photoUri.toString()); }else if(imageViewId.equals("2")){ ID_img_back.setImageBitmap(newCompressedImageBitmap); SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_back",photoUri.toString()); }else if(imageViewId.equals("3")){ ID_img_hand.setImageBitmap(newCompressedImageBitmap); SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_hand",photoUri.toString()); } }else{ Toast.makeText(this,"截图错误",Toast.LENGTH_SHORT).show(); } }else { //相册截图 if(newCompressedImageBitmap!=null){ String imageViewId = (String) SharedPreferencesUtils.get(OcrPhotoActivity.this,"imageViewId",""); if (imageViewId.equals("1")){ ID_img_font.setImageBitmap(newCompressedImageBitmap); SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_font",photoUri.toString()); }else if(imageViewId.equals("2")){ ID_img_back.setImageBitmap(newCompressedImageBitmap); SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_back",photoUri.toString()); }else if(imageViewId.equals("3")){ ID_img_hand.setImageBitmap(newCompressedImageBitmap); SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_hand",photoUri.toString()); } }else{ Toast.makeText(this,"截图错误",Toast.LENGTH_SHORT).show(); } } break; } } }
然后就是SharedPreferencesUtils
package www.tydic.com.util;import android.content.Context;import android.content.SharedPreferences;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Map;/** * SharedPreferences的一个工具类,调用setParam就能保存String, Integer, Boolean, Float, Long类型的参数 * 同样调用getParam就能获取到保存在手机里面的数据 * Created by LIUREN on 2017/2/16. */public class SharedPreferencesUtils { public SharedPreferencesUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * 保存在手机里面的文件名 */ private static final String FILE_NAME = "share_data"; /** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 * * @param context * @param key * @param object */ public static void put(Context context, String key, Object object){ SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (object instanceof String) { editor.putString(key, (String) object); } else if (object instanceof Integer) { editor.putInt(key, (Integer) object); } else if (object instanceof Boolean) { editor.putBoolean(key, (Boolean) object); } else if (object instanceof Float) { editor.putFloat(key, (Float) object); } else if (object instanceof Long) { editor.putLong(key, (Long) object); } else { editor.putString(key, object.toString()); } SharedPreferencesCompat.apply(editor); } /** * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 * * @param context * @param key * @param defaultObject * @return */ public static Object get(Context context, String key, Object defaultObject) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); if (defaultObject instanceof String) { return sp.getString(key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return sp.getInt(key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return sp.getFloat(key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return sp.getLong(key, (Long) defaultObject); } return null; } /** * 移除某个key值已经对应的值 * * @param context * @param key */ public static void remove(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); SharedPreferencesCompat.apply(editor); } /** * 清除所有数据 * * @param context */ public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); SharedPreferencesCompat.apply(editor); } /** * 查询某个key是否已经存在 * * @param context * @param key * @return */ public static boolean contains(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.contains(key); } /** * 返回所有的键值对 * * @param context * @return */ public static MapgetAll(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); return sp.getAll(); } /** * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 * * @author zhy * */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * 反射查找apply的方法 * * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Method findApplyMethod() { try { Class clz = SharedPreferences.Editor.class; return clz.getMethod("apply"); } catch (NoSuchMethodException e) { } return null; } /** * 如果找到则使用apply执行,否则使用commit * * @param editor */ public static void apply(SharedPreferences.Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } editor.commit(); } }}
可以把相关数据存储到里面,需要的时候获取处理啊,如何存储,如何获取如下:
存储:
SharedPreferencesUtils.put(OcrPhotoActivity.this,"ID_img_font","12345");
获取:
String ID_img_font_path = (String) SharedPreferencesUtils.get(OcrPhotoActivity.this,"ID_img_font","");