效果:
一、打开系统相机,自己拍照得到照片
//打开系统拍照程序,选择拍照图片
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA);
接着,解析得到图片数据,并设置给ImageView显示,同时保存到本地
//拍照
Bundle bundle = data.getExtras();
// 获取相机返回的数据,并转换为图片格式
Bitmap bitmap = (Bitmap) bundle.get("data");
//bitmap圆形裁剪
bitmap = BitmapUtils.zoom(bitmap, UIUtils.dp2px(62), UIUtils.dp2px(62));
Bitmap circleImage = BitmapUtils.circleBitmap(bitmap);
//真是项目当中,是需要上传到服务器的..这步我们就不做了。
iv.setImageBitmap(circleImage);
//将图片保存在本地
saveImage(circleImage);
二、//打开系统图库程序,选择图片
//打开系统图库程序,选择图片
Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture, PICTURE);
》解析图库的操作,跟android系统有很大相关性。不同的系统使用uri的authority有很大不同。
不同版本的uri获取方法,这里列举的是>19之后的方法
private boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isMedia(Uri uri) {
return "media".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
uri路径查询字段方法
/**
* uri路径查询字段
*
* @param context
* @param uri
* @param selection
* @param selectionArgs
* @return
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
图片选择程序方法
public void changeIcon(View view){
String[] items = new String[]{"图库","相机"};
new AlertDialog.Builder(this)
.setTitle("选择来源")
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i){
case 0://图库
// UIUtils.toast("图库",false);
//启动其他应用的Activity:使用隐式意图
Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture,PICTURE);
break;
case 1://相机
// UIUtils.toast("相机",false);
//打开系统拍照程序,选择拍照图片
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA);
break;
}
}
})
.setCancelable(false)
.show();
}
//重写启动新的activity以后的回调方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA&&resultCode==RESULT_OK&&data!=null){//相机
//获取Intent中的图片对象
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
//对获取到的bitmap进行压缩,图形处理
bitmap = BitmapUtils.zoom(bitmap,ivUserIcon.getWidth(),ivUserIcon.getHeight());
bitmap = BitmapUtils.circleBitmap(bitmap);
//加载显示
ivUserIcon.setImageBitmap(bitmap);
//上传到服务器
//保存到本地
saveImage(bitmap);
}else if (requestCode==PICTURE&&resultCode==RESULT_OK&&data!=null){//图库
//图库
Uri selectedImage = data.getData();
//android各个不同的系统版本,对于获取外部存储上的资源,返回的Uri对象都可能各不一样,
// 所以要保证无论是哪个系统版本都能正确获取到图片资源的话就需要针对各种情况进行一个处理了
//这里返回的uri情况就有点多了
//在4.4.2之前返回的uri是:content://media/external/images/media/3951或者file://....
// 在4.4.2返回的是content://com.android.providers.media.documents/document/image
String pathResult = getPath(selectedImage);
//存储--->内存
Bitmap decodeFile = BitmapFactory.decodeFile(pathResult);
Bitmap zoomBitmap = BitmapUtils.zoom(decodeFile, ivUserIcon.getWidth(),ivUserIcon.getHeight());
//bitmap圆形裁剪
Bitmap circleImage = BitmapUtils.circleBitmap(zoomBitmap);
//加载显示
ivUserIcon.setImageBitmap(circleImage);
//上传到服务器(省略)
//保存到本地
saveImage(circleImage);
}
}
图片保存到本地方法
//将bitmap保存到本地的操作
/**
* 数据的存储。(5种)
* Bimap:内存层面的图片对象。
*
* 存储--->内存:
* BitmapFactory.decodeFile(String filePath);
* BitmapFactory.decodeStream(InputStream is);
* 内存--->存储:
* bitmap.compress(Bitmap.CompressFormat.PNG,100,OutputStream os);
*/
private void saveImage(Bitmap bitmap) {
File filesDir;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断sd卡是否挂载
//路径1:storage/sdcard/Android/data/包名/files
filesDir = this.getExternalFilesDir("");
}else {//手机内部存储
//路径:data/data/包名/files
filesDir = this.getFilesDir();
}
FileOutputStream fos = null;
try {
File file = new File(filesDir,"icon.png");
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
读取本地保存的图片
private void readImage() {
File filesDir;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//判断sd卡是否挂载
//路径1:storage/sdcard/Android/data/包名/files
filesDir = this.getActivity().getExternalFilesDir("");
} else {//手机内部存储
//路径:data/data/包名/files
filesDir = this.getActivity().getFilesDir();
}
File file = new File(filesDir, "icon.png");
if (file.exists()){
//存储-->内存
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ivMeIcon.setImageBitmap(bitmap);
}
}
/**
* 根据系统相册选择的文件获取路径
*
* @param uri
*/
@SuppressLint("NewApi")
private String getPath(Uri uri) {
int sdkVersion = Build.VERSION.SDK_INT;
//高于4.4.2的版本
if (sdkVersion >= 19) {
Log.e("TAG", "uri auth: " + uri.getAuthority());
if (isExternalStorageDocument(uri)) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(this, contentUri, null, null);
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(this, contentUri, selection, selectionArgs);
} else if (isMedia(uri)) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = this.managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
return actualimagecursor.getString(actual_image_column_index);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(this, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* uri路径查询字段
*
* @param context
* @param uri
* @param selection
* @param selectionArgs
* @return
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isMedia(Uri uri) {
return "media".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
图片压缩,处理工具类
package com.willkong.p2pclient.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
public class BitmapUtils {
public static Bitmap circleBitmap(Bitmap source) {
int width = source.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawCircle(width / 2, width / 2, width / 2, paint);
//设置图片相交情况下的处理方式
//setXfermode:设置当绘制的图像出现相交情况时候的处理方式的,它包含的常用模式有:
//PorterDuff.Mode.SRC_IN 取两层图像交集部分,只显示上层图像
//PorterDuff.Mode.DST_IN 取两层图像交集部分,只显示下层图像
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return bitmap;
}
//实现图片的压缩处理
public static Bitmap zoom(Bitmap source,float w,float h){
Matrix matrix = new Matrix();
//图片的压缩处理
matrix.postScale(w / source.getWidth(),h / source.getHeight());
Bitmap bitmap = Bitmap.createBitmap(source,0,0,source.getWidth(),source.getHeight(),matrix,true);
return bitmap;
}
}