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

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

2016-09-20 11:36 447 查看
对图片进行整体压缩,不改变宽高比,只影响清晰度

//本地照片的读取路径
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐