gpt4 book ai didi

java - 选择图库中的图像

转载 作者:行者123 更新时间:2023-12-02 03:14:24 26 4
gpt4 key购买 nike

我有这段代码,但是当我单击按钮时,图库将打开,当我选择图像时,图库将再次关闭。什么也不会发生。

公共(public)类 MainActivity 扩展 AppCompatActivity {

private Button loadimagebutton;
private ImageView imageView;

private static int RESULT_LOAD_IMAGE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

loadimagebutton = (Button) findViewById(R.id.button);

loadimagebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);

if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();

imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
else{
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
}
}

出了什么问题?

最佳答案

希望这对您有帮助:

private String getRealPathFromUri(Uri contentURI) {
String result = "";
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}

和 onActivityResult();

imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(BitmapFactory.decodeFile(getRealPathFromUri(uri)));

关于java - 选择图库中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40536456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com