我正在开发一个 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);
}
然而,这有效,图像很小并且不遵循存储图像的命名约定。我读过要保存完整大小我需要使用 putExtra 并在 cameraIntent 上传递 MediaStore.EXTRA_OUTPUT 并声明一个临时文件,所以我调整了我的 Intent 代码如下:
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);
然而,这会导致抛出错误,指出“找不到源”。
不确定从哪里开始?
更新
看来正在创建我的照片。应用程序关闭后,我可以使用文件资源管理器导航到目录并查看图像。我不确定导致应用程序崩溃的原因。
最佳答案
我认为问题在于您仍在尝试从 Intent
访问缩略图。为了检索完整尺寸的图像,您需要直接访问该文件。所以我建议在开始相机 Activity 之前保存文件名,然后在 onActivityResult
加载文件。
我建议阅读 Taking Photos Simply page from the official documentation在哪里可以找到关于缩略图的引用:
Note: This thumbnail image from "data" might be good for an icon, but not a lot more. Dealing with a full-sized image takes a bit more work.
同样在最后一部分,您将找到所需的代码:
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);
}
关于Android 从相机获取全尺寸图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350473/