文章后边有代码详细查看,不想看我啰嗦的直接看代码吧~
之前写的data!=null时,使用Bundle extras = data.getExtras();来获取data中的数据,后来发现extras:null,不管怎么获取都获取不到数据,错误代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Bundle extras = data.getExtras();
head = extras.getParcelable("data");
if (head != null) {
myUserImage.setImageBitmap(head);// 用ImageView显示出来
}
}
super.onActivityResult(requestCode, resultCode, data);
}
后来通过其他方式获取数据,如下,但依旧无法得到图片。
if(data.hasExtra("data")){
Bitmap bitMap = data.getParcelableExtra("data");//得到图片
}
参考链接:https://blog.csdn.net/weixin_34112900/article/details/93362126?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
最终尝试得到如下结果:data.getData()可以获得数据
Log.e("test1",data.getData()+"1111"); //获取到了图片!!!
Log.e("test1",data.getExtras()+"2222");//结果为null
Log.e("test1",data.getParcelableExtra("data")+"3333");//结果为null
但却无法转化成Bundle,于是报错:
Bundle extras = data.getData();//出错!!
于是寻找可以使用data.getData()的方法:
//这个一小部分代码是正确的
if (data != null) {
String mImgPath = "";
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if(cursor!=null) //这里需要判断
{
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
mImgPath = picturePath;
}else{
mImgPath = selectedImage.getPath();
}
Bitmap head = getBitmapByPath(mImgPath);
ivUserImg.setImageBitmap(head);
}
if(cursor!=null) ,这里需要判断,但具体原因我也不清楚,反正不进行判断我这里会报错。
参考链接:https://blog.csdn.net/Trent1985/article/details/51533274
最后可以拿到图片路径,但是却无法在ImageView控件显示,并报了这个错误:BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: (No such file or directory)
个人认为是图片格式问题,于是寻找了各种方法:
一开始,我以为是权限问题,于是添加了以下权限:
Manifests:(拍照记得添加PHOTO权限)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Activity:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.user_image_activity);
// android 7.0系统解决拍照的问题
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
//允许开启访问本地文件权限
requestWritePermission();
}
//调用手机权限
private void requestWritePermission(){
if (ActivityCompat.checkSelfPermission(UserImageActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(UserImageActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
}
参考链接:
https://blog.csdn.net/crescent__moon/article/details/78758605
尝试1:本人错误无法解决,大家可以尝试
String s = mImgPath.replace(" ", "+");
Bitmap head = stringToBitmap(s);
ivUserImg.setImageBitmap(head);
public static Bitmap stringToBitmap(String string) {
Bitmap bitmap = null;
try {
byte[] bitmapArray = Base64.decode(string, Base64.NO_WRAP);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
尝试2:本人依旧无法解决
Bitmap head= BitmapFactory.decodeFile("file://" + mImgPath);
ivUserImg.setImageBitmap(head);
尝试3:终于解决了,获取到了相机拍照的图片,并在控件显示了出来
Bitmap head = getBitmapByPath(mImgPath);
ivUserImg.setImageBitmap(head);
//通过图片path获取bitmap类型
private Bitmap getBitmapByPath(String path){
Bitmap bitmap=null;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inPreferredConfig=Bitmap.Config.ARGB_4444;
int scale=1;
o2.inSampleSize=scale;
Bitmap result = null;
while(true){
try {
bitmap= BitmapFactory.decodeFile(path,o2);
break;
}catch (OutOfMemoryError e){
scale *= 2;
o2.inSampleSize = scale;
}
}
return bitmap;
}
我实在找不到 写getBitmapByPath()方法的作者链接了,日后若找到会将链接贴出。
以下代码是对朋友之前写的代码进行的修改,只是用于我自己学习使用,对日后遇到相同问题可以有所参考。
代码快速查看:
(大家记得添加Manifests中的权限)
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_image_activity);
// android 7.0系统解决拍照的问题
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
//允许开启访问本地文件权限
requestWritePermission();
ivUserImg = findViewById(R.id.iv_userImage);
ivUserImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTypeDialog();
}
});
}
//popupwindow
private void showTypeDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog dialog = builder.create();
final View view = getLayoutInflater().inflate(R.layout.popupwindow, null);
TextView tv_select_gallery = (TextView) view.findViewById(R.id.btn_select);
TextView tv_select_camera = (TextView) view.findViewById(R.id.btn_photo);
tv_select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
@Override
public void onClick(View v) {
Intent intent1 = new Intent(Intent.ACTION_PICK, null);
intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent1, 1);
dialog.dismiss();
}
});
tv_select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机
@Override
public void onClick(View v) {
Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent2.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
startActivityForResult(intent2, 2);// 采用ForResult打开
dialog.dismiss();
}
});
dialog.setView(view);
dialog.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
cropPhoto(data.getData());// 裁剪图片
}
break;
case 2:
if (resultCode == RESULT_OK) {
File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
cropPhoto(Uri.fromFile(temp));// 裁剪图片
}
break;
case 3:
if (data != null) {
String mImgPath = "";
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if(cursor!=null)
{
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
mImgPath = picturePath;
}else{
mImgPath = selectedImage.getPath();
}
Bitmap head = getBitmapByPath(mImgPath);
ivUserImg.setImageBitmap(head);
}
break;
/*
如果上边这个case3运行出错,可以尝试下这个case3:
case 3:
if (data != null) {
Bundle extras = data.getExtras();
head = extras.getParcelable("data");
if (head != null) {
myUserImage.setImageBitmap(head);// 用ImageView显示出来
//上传
contorlImage(head);
}
}
break;
*/
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//通过图片path获取bitmap类型
private Bitmap getBitmapByPath(String path){
Bitmap bitmap=null;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inPreferredConfig=Bitmap.Config.ARGB_4444;
int scale=1;
o2.inSampleSize=scale;
Bitmap result = null;
while(true){
try {
bitmap= BitmapFactory.decodeFile(path,o2);
break;
}catch (OutOfMemoryError e){
scale *= 2;
o2.inSampleSize = scale;
}
}
return bitmap;
}
/**加密*/
private static String encryptBase64_android(String string){
return Base64.encodeToString(string.getBytes(), Base64.DEFAULT);
}
/**解密*/
private static String decoderBase64_android(String string){
return new String(Base64.decode(string.getBytes(), Base64.DEFAULT));
}
/**
* 调用系统的裁剪功能
*
* @param uri
*/
public void cropPhoto(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}
//调用手机权限
private void requestWritePermission(){
if (ActivityCompat.checkSelfPermission(UserImageActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(UserImageActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/frame"
android:gravity="bottom"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:textSize="15dp"
android:gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="拍照"
android:background="@drawable/frame"
android:id="@+id/btn_photo"
android:layout_width="match_parent"
android:layout_height="40dp" />
<TextView
android:textSize="15dp"
android:gravity="center"
android:layout_marginTop="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/frame"
android:text="从相册中选择"
android:id="@+id/btn_select"
android:layout_width="match_parent"
android:layout_height="40dp"
/>
</LinearLayout>