Android 对本地图片进行压缩处理

对图片进行整体压缩,不改变宽高比,只影响清晰度

//本地照片的读取路径
private static String photoPath = "/sdcard/AnBo/";
private static String photoName = photoPath + "laolisb.jpg";


BitmapFactory.Options op = new BitmapFactory.Options();
op.inSampleSize = 4; // 这个数字越大,图片就越小.图片就越不清晰


Bitmap pic = null;
pic = BitmapFactory.decodeFile(photoName, op);  //先从本地读照片,然后利用op参数对图片进行处理  


//将处理后的图片重新写回本地
FileOutputStream b = null;              
try {
        b = new FileOutputStream(photoName);
} catch (FileNotFoundException e) {
                    e.printStackTrace();
}
if (pic != null) {
        pic.compress(Bitmap.CompressFormat.JPEG, 50, b);
}


改变图片宽高比


private static String photoPath = "/sdcard/AnBo/";
private static String photoName = photoPath + "laolisb.jpg";


BitmapFactory.Options op = new BitmapFactory.Options();
// 设置图片的大小
Bitmap bitMap = BitmapFactory.decodeFile(photoName);
int width = bitMap.getWidth();
int height = bitMap.getHeight();
// 设置想要的大小
int newWidth = 120;
int newHeight = 640;
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,matrix, true);


//将新文件回写到本地                     
FileOutputStream b = null;              
try {
        b = new FileOutputStream(photoName);
} catch (FileNotFoundException e) {
        e.printStackTrace();
}
if (bitMap != null) {
        bitMap.compress(Bitmap.CompressFormat.JPEG, 50, b);
}


FR:海涛高软(QQ技术交流群:386476712)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值