在不改变分辨率的情况下减小图像大小 安卓工作室.



在我的安卓应用程序中,我使用相机意图点击一张照片并将其上传到我的服务器进行处理。但是,要求图像的分辨率应大于500X500。

如今,默认相机分辨率要高得多,因此所需的分辨率不是问题。但是,在大多数情况下,分辨率要高得多,图像大小可达3 MB左右。因此,将图像上传到服务器需要更长的时间,尤其是在互联网连接较差的地区。

我想在不降低分辨率的情况下减小图像的大小,最好减小到 100 KB 左右。

我通过意图捕获图像的代码是:

imageHolder = (ImageView)findViewById(R.id.cPhoto78);
imageHolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File outputFile1 = new File(getExternalStorageDirectory(), "/APDCLSBM/APDCL1.jpg");
outputFile1.delete();// Deletes the existing photo
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Toast.makeText(getBaseContext(),"Error in clicking picture",
Toast.LENGTH_SHORT).show();
finish();
}
Intent a = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (photoFile != null) {
Uri outputFileUri = FileProvider.getUriForFile(photoCamera.this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
a.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(a, 1);
}
}
});

以下函数创建图像文件和路径:

private File createImageFile() throws IOException {
String imageFileName = "APDCL1";
File storageDir = new File(
getExternalStorageDirectory() + IMAGE_DIRECTORY);
File image = new File(storageDir, imageFileName+".jpg");
currentPhotoPath = image.getAbsolutePath();
Log.d("path1",currentPhotoPath);
return image;
}

请建议一种方法

private File createImageFile() throws IOException {
String imageFileName = "APDCL1";
File storageDir = new File(
getExternalStorageDirectory() + IMAGE_DIRECTORY);
File image = new File(storageDir, imageFileName+".jpg");
try{
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath);
}catch(Exception e){ e.printStacktrace(); return null;}
File reducedSizeImage = new File.createTempFile("name",".jpg",location);
try ( FileOutputStream outputStream = new FileOutputStream(reducedSizeImage)) 

{
image.compress(Bitmap.CompressFormat.JPEG,20, outputStream); // this line will reduce the size , try changing the second argument to adjust to correct size , it ranges 0-100

} catch (Exception e) {
e.printStackTrace();
return null;
}
return reducedSizeImage // otherwise upload this file
}

祝你今天开心

最新更新