从相机获取Android完整大小图像

3
我正在开发一款Android应用程序,可以从相机或设备照片库上传图像到远程站点。后者我已经成功实现了选择和上传操作。然而,我在处理全尺寸图像并进行上传方面遇到了困难。以下是我的代码:
// From onCreate
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

我有一个处理Activity结果的方法。这个方法可以同时处理从相册和相机选择的情况:

public void onActivityResult(int requestCode, int resultCode, Intent data) {

  String filepath = ""; 
  Uri selectedImageUri;

  if (resultCode == RESULT_OK) {
    if (requestCode == CAMERA_PIC_REQUEST) {
      Bitmap photo = (Bitmap) data.getExtras().get("data");
      // Gets real path of image so it can be uploaded
      selectedImageUri = getImageUri(getApplicationContext(), photo);
    }
    else {
      selectedImageUri = data.getData();
    }
    // Handle the upload ...
  }
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
  String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
  return Uri.parse(path);
}

这样做是有效的,但图片很小,并且不符合存储图像的命名约定。我了解到要保存全尺寸,需要在cameraIntent上使用putExtra并传递MediaStore.EXTRA_OUTPUT,并声明一个临时文件,因此我已经修改了我的意图代码如下:

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
camImgFilename = sdf.format(new Date())+".jpg";

File photo = new File Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), camImgFilename);

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

然而,这会导致出现错误,提示“找不到源代码”。

不确定怎么继续下去?

更新

看起来我的照片已经被创建了。一旦应用程序关闭,我可以使用文件浏览器导航到目录并查看图像。我不确定是什么导致应用程序崩溃。


1
请查看此链接:https://dev59.com/g2oy5IYBdhLWcg3wcNvh#8543376,您可以实现自定义相机。 - Ahmad Raza
1个回答

5
我认为问题在于您仍然试图从Intent中访问缩略图。为了检索完整大小的图像,您需要直接访问该文件。因此,我建议在启动相机活动之前保存文件名,然后在onActivityResult中加载该文件。
我建议阅读官方文档中的“简单拍照”页面,其中您将找到有关缩略图的以下引用:

注意:来自“数据”的此缩略图图像可能适合作为图标,但不适合其他用途。处理全尺寸图像需要更多的工作。

此外,在最后一节中,您将找到所需的代码:
private void setPic() {
    // Get the dimensions of the View
    int targetW = mImageView.getWidth();
    int targetH = mImageView.getHeight();

    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    // Determine how much to scale down the image
    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
    mImageView.setImageBitmap(bitmap);
}

感谢您的回答,移除 Bitmap photo = (Bitmap) data.getExtras().get("data"); 后我的应用程序不再崩溃,并且上面列出的 galleryAddPic() 方法 setPic() 在图库中列出了该图像。完美! - amburnside

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接