我正在使用相机意图允许用户拍照并将图像上传到Firebase存储。我注意到在这个过程中,由于我在拉位图而不是实际的图像文件,因此丢失了相当大的图像质量。我显然希望在必要时限制文件大小和压缩,但我也希望保留原始图像质量。这是我调用相机意图并提示用户拍照的地方:
case 1:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getApplication().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, TAKE_PICTURE);
} else {Toast.makeText(getApplicationContext(), getResources().getString(R.string.camera_error), Toast.LENGTH_LONG).show();
}
break;
这是我检索图像数据的.onActivityResult()方法:
case TAKE_PICTURE:
//TODO: Limit file size to prevent reaching Firebase storage limit
if (resultCode == CreateActivity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImagePreview.setDrawingCacheEnabled(true);
mImagePreview.buildDrawingCache();
mImagePreview.setImageBitmap(imageBitmap);
encodeBitmapAndSaveToFirebase(imageBitmap);
}
break;
保存到Firebase:
private void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
String uniqueID = java.util.UUID.randomUUID().toString();
mFileRef = mStorageRef.child(uniqueID);
UploadTask uploadTask = mFileRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "Error Loading Photo", Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
resultImageURL = downloadUrl.toString();
Picasso.with(getApplicationContext())
.load(resultImageURL)
.into(mImagePreview);
}
});
}
答案 0 :(得分:2)
此处,quality =&gt;我们希望我们的图片具有1到100的质量。 targetWidth&amp; targetHeight =&gt;这将为您提供px中的图像大小。
takePicture(){
Camera.getPicture({
quality : 95,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.PNG,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: true
}).then(imageData => {
this.guestPicture = imageData;
}, error => {
console.log("ERROR -> " + JSON.stringify(error));
});
}
答案 1 :(得分:1)
使用外置相机应用在Android中拍照的Google教程是:https://developer.android.com/training/camera/photobasics.html
如果您遵循该示例,您将创建一个文件,相机应用程序将保存图像数据。如果您不想丢失图像中的任何质量,请直接上传该文件的内容。现在,您正在上传图像的缩略图,这将远远不及源图像的大小和质量。