/* 请求识别码 */
private static final int CODE_CAMERA_REQUEST = 0xa1;
private static final int CODE_RESULT_REQUEST = 0xa2;
打开相册:
Intent intentFromGallery = new Intent(Intent.ACTION_PICK);
// 设置文件类型
intentFromGallery.setType("image/*");
startActivityForResult(intentFromGallery, CODE_CAMERA_REQUEST);
private String base64;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == getActivity().RESULT_CANCELED) {
} else if (requestCode == CODE_GALLERY_REQUEST && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//把图片地址转为base64(项目需要)
base64 = ImageUtil.imageToBase64(picturePath);
//把base64转为bitmap并显示在ImageView上
img.setImageBitmap(ImageUtil.base64ToBitmap(base64));
}
可以指定URI,但是指定URI的话在onActivityResult()中data(intent)为null,不能通过data(intent)获取图片,需要通过之前指定的URI来获取
private static String path = "/sdcard/TakePhoto/myPicture/";//sd路径
private Uri imageUri;
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file1 = new File(path);
if (!file1.exists()) {
file1.mkdirs();
}
String fileName = path + "1.png";
File file = new File(fileName);
if (Build.VERSION.SDK_INT >= 24) {
//android 7.0新加特性
imageUri = FileProvider.getUriForFile(this, "me.xifengwanzhao.fileprovider", file);
} else {
imageUri = Uri.fromFile(file);
}
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
if (Build.VERSION.SDK_INT >= 24) {
//android 7.0新加特性
intentFromCapture.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 用户没有进行有效的设置操作,返回
if (resultCode == RESULT_CANCELED) {
return;
}
switch (requestCode) {
case CODE_CAMERA_REQUEST:
//通过URI获取图片 裁剪
cropPhoto(imageUri);
break;
case CODE_RESULT_REQUEST:
startActivity(new Intent(MainActivity.this, SecondActivity.class));
finish();
break;
}
}
/**
* 裁剪原始的图片
*/
public void cropPhoto(Uri uri) {
DisplayMetrics dm = getResources().getDisplayMetrics();
int heightPixels = dm.heightPixels;
int widthPixels = dm.widthPixels;
int width = 0;
if (heightPixels >= widthPixels) {
width = widthPixels;
} else {
width = heightPixels;
}
File file = new File(path);
File file2 = new File(path + getCurrentTime() + ".png");
if (!file.exists()) {
file.mkdirs();
}
try {
if (!file2.exists()) {
file2.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
Uri fromFile = Uri.fromFile(file2);
Intent intent = new Intent("com.android.camera.action.CROP");
if (Build.VERSION.SDK_INT >= 24) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
if (Build.MANUFACTURER.equals("HUAWEI")) {
intent.putExtra("aspectX", 9998);
intent.putExtra("aspectY", 9999);
} else {
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
}
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 1000);
intent.putExtra("outputY", 1000);
//设置目的地址uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, fromFile);
intent.putExtra("return-data", false);
intent.putExtra("outputFormat", "png");
startActivityForResult(intent, CODE_RESULT_REQUEST);
}
注:要使用上面的指定URI方法需要在ManiFest文件中添加
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="me.xifengwanzhao.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
并在res下新建个文件夹命名为xml,在xml文件夹下创建个文件file_paths
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path name="root" path="" />
<files-path name="files" path="" />
<cache-path name="cache" path="" />
<external-path name="external" path="" />
<external-files-path name="name" path="path" />
<external-cache-path name="name" path="path" />
</paths>
最后送上上面用到的图片路径转base64和base64转bitmap的方法
public class ImageUtil {
/**
* bitmap转为base64
*
* @param bitmap
* @return
*/
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* base64转为bitmap
*
* @param base64Data
* @return
*/
public static Bitmap base64ToBitmap(String base64Data) {
byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
/**
* 将图片转换成Base64编码的字符串
*
* @param path
* @return base64编码的字符串
*/
public static String imageToBase64(String path) {
if (TextUtils.isEmpty(path)) {
return null;
}
InputStream is = null;
byte[] data = null;
String result = null;
try {
is = new FileInputStream(path);
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.encodeToString(data, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}