这是我从Gallery获取图像的代码。它给出了空指针异常并崩溃。我正在测试设备本身上的代码,一旦我在图库中选择图像,它就会崩溃。有什么想法我要去哪里吗?
AlertDialog.Builder builder = new AlertDialog.Builder(CreatePod.this);
builder.setMessage("Select") .setCancelable(false).setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent gallIntent=new Intent(Intent.ACTION_GET_CONTENT);
gallIntent.setType("image/*");
startActivityForResult(gallIntent, 10);
}
})
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap b = (Bitmap) extras.get("data");
imgView.setImageBitmap(b);
String timestamp = Long.toString(System.currentTimeMillis());
MediaStore.Images.Media.insertImage(getContentResolver(), b, timestamp, timestamp);
HttpResponse httpResponse;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
int f = 0;
String ba1=Base64.encodeToString(ba, f);
最佳答案
而不是使用
Bitmap b = (Bitmap) extras.get("data");
imgView.setImageBitmap(b);
使用以下代码行:
Uri imageUri = data.getData();
Bitmap b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imgView.setImageBitmap(b);
我更改了代码并运行,它对我有用!