参考资料:
https://blog.csdn.net/sm16111/article/details/82115460
https://www.jb51.net/article/160230.htm
概念解释:
ImageView:用来显示图片
步骤:
1、弹出图片选择框
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, 2);
2、显示图片
方法一:
ImageView iv = findViewById(R.id.PhotoShowView); iv.setImageURI(uri);
方法二:
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
//设置图片显示,可以看到效果
ImageView imageView = (ImageView) findViewById(R.id.PhotoShowView);
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(),e);
}
代码:
package com.example.grammartest;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadPhotoActivity extends AppCompatActivity {
String tag = "ReadPhotoActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_photo);
InitView();
}
void InitView(){
Button bt = findViewById(R.id.ChoosePhotoBt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, 2);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2){
if (null != data){
Uri uri = data.getData();
Log.i(tag,"onActivityResult" +uri.toString());
ShowPhoto2(uri);
}
}
}
void ShowPhoto1(Uri uri){
ImageView iv = findViewById(R.id.PhotoShowView);
iv.setImageURI(uri);
}
void ShowPhoto2(Uri uri){
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
//设置图片显示,可以看到效果
ImageView imageView = (ImageView) findViewById(R.id.PhotoShowView);
/* 将Bitmap设定到ImageView */
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(),e);
}
}
}