您的位置:首页 > 移动开发 > Android开发

android 对已知路径下图片进行压缩

2017-09-05 00:00 369 查看
用户有很多对图片最大内存进行限制的需求,当图片宽高小于已定标准的宽高时,不对图片做处理,当图片宽高大雨已定标准的宽高时,对图片宽高进行赋值,使大图片满足压缩后满足要求,同时保证不对清晰度小的图片进行处理

int maxWidth=624,maxHeight=840;//定义目标图片的最大宽高,若原图高于这个数值,直接赋值为以上的数值
Bitmap bitmap= BitmapFactory.decodeFile(path);
int originWidth=bitmap.getWidth();
int originHeight=bitmap.getHeight();
if(originWidth<maxWidth&&originHeight<maxHeight){
return ;
}
int width=originWidth;
int height=originHeight;

if(originWidth>maxWidth) {
width=maxWidth;
double i = originWidth * 1.0 / maxWidth;
height = (int) Math.floor(originHeight / i);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);

}
if(height>maxHeight){
height=maxHeight;
bitmap=Bitmap.createBitmap(bitmap,0,0,width,height);
}
File file=new File(path);
if(file.exists()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: