我想根据那里的大小压缩我从android的画廊中选择的图像,并将其上传到云存储中。例如,如果我选择的图像大小为300kb,我不减少它并保持质量为100,但是如果相同的是7Mb,则我希望将其减小为10质量,并且我想将所选图像的最大大小设置为7Mb(未压缩的原始图片),并且类似地对两者之间的尺寸设置了不同的条件。
我的代码
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
File f = new File(resultUri.getPath());
long sizeUri = f.length()/1024;
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(),resultUri));
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int baossize= baos.size()/1024;
byte[] uploadbaos = baos.toByteArray();
int lengthbmp = (uploadbaos.length);
int size= lengthbmp/1024;
Log.d(TAG,"baossize: "+baossize+" ByteArray: "+size+" UriSize: "+sizeUri);
// UploadingImage();
}
在给定的示例中,您可以设置最大大小,例如您可以设置为7MB。
public static boolean reduceImage(String path, long maxSize) {
File img = new File(path);
boolean result = false;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = null;
options.inSampleSize=1;
while (img.length()>maxSize) {
options.inSampleSize = options.inSampleSize+1;
bitmap = BitmapFactory.decodeFile(path, options);
img.delete();
try
{
FileOutputStream fos = new FileOutputStream(path);
img.compress(path.toLowerCase().endsWith("png")?
Bitmap.CompressFormat.PNG:
Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
result = true;
}catch (Exception errVar) {
errVar.printStackTrace();
}
};
return result;
}