先看一下效果
尺寸压缩代码
private void ciCun_zip() {
// 第一次采样
BitmapFactory.Options options = new BitmapFactory.Options();
// 第一次只加载边框, 所以设置为 true
options.inJustDecodeBounds = true;
// 第一次加载, 只加载图片边框进来 , 不加载像素点
BitmapFactory.decodeFile(path,options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
int sampleSize = 1; // 缩放比例
int destWidth = 50; // 控件的宽度, 也就是要加载为的宽
int destHeight = 50; // 控件的高度, 也就是要加载为的高
while (outWidth/sampleSize > destWidth || outHeight / sampleSize > destHeight){
// 如果宽高的任意一方的缩放比例没有达到要求,都要继续增大缩放比例
// sampleSize 应该为2的n次幂,如果sampleSize设置的数值不是2的n次幂,那么系统就会取就近值
sampleSize *= 2;
}
//第二次采样
// 第二次采样不能只加载图片的变宽,所以我们设置 inJustDecodeBounds = false;
options.inJustDecodeBounds = false;
options.inSampleSize = sampleSize; // 设置为要缩放的比例
options.inPreferredConfig = Bitmap.Config.ARGB_8888; //
Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 按比例加载出来的图片
img_cc.setImageBitmap(bitmap);
}
// 质量压缩
private void ziLiang_zip() {
// 想要压缩的目标大小 kb
int maxKB = 1;
// 原来的图片
Bitmap bitmap = BitmapFactory.decodeFile(path);
// 利用 ByteArrayOutputStream 暂时存储
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 这里的 100 表示不压缩, 只是利用outputStream拿到一个最初的 byte 值
bitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
// 压缩质量的 值
int options = 100;
// 循环压缩, 不满足条件就一直压缩
while (outputStream.toByteArray().length/1024 > maxKB && options != 10){
outputStream.reset();// 清空outputstream
// 这里压缩options%,把压缩后的数据存放到output中
bitmap.compress(Bitmap.CompressFormat.JPEG,options,outputStream);
options -= 10; // 每次将压缩质量缩小 10 , 这个可以根据自己需要定义
}
// 质量压缩值 已经确定
// 写入到新的文件中
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + “/zip.jpeg”);
FileOutputStream fileOutputStream = null;
try {
if (file.exists()){
file.delete();
}
fileOutputStream = new FileOutputStream(file);
// 这里的option就是压缩 后的 值
bitmap.compress(Bitmap.CompressFormat.JPEG,options,fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
// 关流, 避免内存泄露
if (fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 将压缩后的 图片 读取出来, 并展示
Bitmap bitmap1 = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + “/zip.jpeg”);
img_zl.setImageBitmap(bitmap1);
}
// 压缩后去你保存的地址看就可以看得出来 看一下图吧 没有接近于1kb 可以试着把那个质量缩小值改小点 我的是10 改成 5 应该会好一点