Java 如何在android中对不同的iMate大小使用不同的图像压缩
我想将我从android gallery中选择的图片按照大小进行压缩,然后上传到云存储中。例如,如果我选择的图像大小为300kb,我不想缩小它并保持质量100,但如果相同的大小为7Mb,我想将其质量降低到10,并且我想将所选图像的最大大小设置为7Mb(原始图像,无压缩),并且类似地,对中间的大小施加不同的条件 我的代码Java 如何在android中对不同的iMate大小使用不同的图像压缩,java,android,performance,Java,Android,Performance,我想将我从android gallery中选择的图片按照大小进行压缩,然后上传到云存储中。例如,如果我选择的图像大小为300kb,我不想缩小它并保持质量100,但如果相同的大小为7Mb,我想将其质量降低到10,并且我想将所选图像的最大大小设置为7Mb(原始图像,无压缩),并且类似地,对中间的大小施加不同的条件 我的代码 if(resultCode==RESULT\u OK){ resultUri=result.getUri(); 文件f=新文件(resultUri.getPath()); lon
if(resultCode==RESULT\u OK){
resultUri=result.getUri();
文件f=新文件(resultUri.getPath());
long sizeUri=f.length()/1024;
试一试{
bitmap=ImageDecoder.decodebmap(ImageDecoder.createSource(getContentResolver(),resultUri));
}捕获(IOE异常){
e、 printStackTrace();
}
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
压缩(bitmap.CompressFormat.JPEG,100,baos);
int baosize=baos.size()/1024;
byte[]uploadbaos=baos.toByteArray();
int lengthbmp=(uploadBas.length);
int size=长度bmp/1024;
Log.d(标签“baosize:+baosize+”ByteArray:+size+“UriSize:+sizeUri”);
//上传图像();
}
在给定的示例中,您可以设置最大大小,就像在您的示例中可能是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;
}
在给定的示例中,您可以设置最大大小,就像在您的示例中,它可以是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;
}
就这么做吧:
int quality;
if (sizeUri <= 300)
quality = 90;
else if (sizeUri <= 1000)
quality = 80;
else if (sizeUri <= 2000)
quality = 70;
else if (sizeUri <= 3000)
quality = 50;
else
quality = 30;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
int质量;
如果(sizeUri就这么做:
int quality;
if (sizeUri <= 300)
quality = 90;
else if (sizeUri <= 1000)
quality = 80;
else if (sizeUri <= 2000)
quality = 70;
else if (sizeUri <= 3000)
quality = 50;
else
quality = 30;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
int质量;
if(sizeUri)