Android ImageView无法从图库或相机中获取图像

时间:2018-03-30 02:26:48

标签: android android-imageview

我想在Android上从相册或相机中选择一张照片,并在ImageView,开放式相册或相机上显示照片,并且没有任何问题。但问题是,我从相机中选择的图片未在ImageView上显示,并且没有错误。

以下是我的代码

360-287-

3 个答案:

答案 0 :(得分:1)

尝试,对您的方法稍有改动,对我来说效果很好。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode== Activity.RESULT_OK) {
        if (requestCode == CAMERA_REQUEST_CODE && data! = null) {
            Uri mImageCaptureUri = data.getData();
             imageEktp.setImageURI(mImageCaptureUri);
        } else if (requestCode == SELECT_FILE && data != null) {
            Uri selectedImage = data.getData();
            imageEktp.setImageURI(selectedImage);
            Log.d("image from galery : ", selectedImage.toString());
        }
    }else{
        Toast.makeText(getActivity(), "You haven't picked Image",Toast.LENGTH_LONG).show();
    }
}

答案 1 :(得分:1)

试试这段代码:

@Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 if (resultCode == Activity.RESULT_OK) {
 if (requestCode == SELECT_FILE)
    onSelectFromGalleryResult(data);
 else if (requestCode == REQUEST_CAMERA)
    onCaptureImageResult(data);
 }
 }
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
 Bitmap bm=null;
 if (data != null) {
 try {
    bm=MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), 
data.getData());
 } catch (IOException e) {
    e.printStackTrace();
 }
 }
 ivImage.setImageBitmap(bm);
  }
 private void onCaptureImageResult(Intent data) {
 Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
 thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
 File destination = new File(Environment.getExternalStorageDirectory(),
    System.currentTimeMillis() + ".jpg");
 FileOutputStream fo;
 try {
 destination.createNewFile();
 fo = new FileOutputStream(destination);
 fo.write(bytes.toByteArray());
 fo.close();
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 ivImage.setImageBitmap(thumbnail);
 }

我认为它可以帮助您检查您的代码一次。

答案 2 :(得分:1)

代码中的小错误

if (resultCode == CAMERA_REQUEST_CODE) {
 ...
} else if (resultCode == SELECT_FILE) {
 ...
}

应该是

if (requestCode == CAMERA_REQUEST_CODE) {
 ...
} else if (requestCode == SELECT_FILE) {
 ...
}