Android保存图片到本地文件夹时如何压缩图片尺寸?
解决Bitmap保存时缩小尺寸的问题
嘿,我看你现在的代码是直接保存原始Bitmap,但想缩小尺寸对吧?问题出在你用了PNG格式的压缩参数——PNG是无损压缩格式,compress方法里的第二个参数(质量值)对它根本没用,所以图片还是会以原始尺寸存储。要实现缩小尺寸,得先对Bitmap进行缩放处理,再保存缩放后的版本。
下面是修改后的完整代码,我会加上关键注释:
String fileName = "image_" + count++ + ".png"; System.out.println("file name is : " + fileName); File sd = Environment.getExternalStorageDirectory(); File folder = new File(sd + "/Wallpaper Pack"); System.out.println("folder is : " + folder); // 建议用mkdirs()代替mkdir(),这样能创建多级目录,避免父目录不存在时创建失败 if (!folder.exists()) { folder.mkdirs(); } File dest = new File(folder, fileName); try { // --- 核心步骤:先缩放Bitmap --- // 1. 定义目标尺寸(这里按原始尺寸的50%缩放,你可以根据需求调整比例或固定值) int targetWidth = bitmap.getWidth() / 2; int targetHeight = bitmap.getHeight() / 2; // 2. 创建缩放后的Bitmap(第三个参数设为true,开启双线性过滤让缩放后的图片更清晰) Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true); // --- 保存缩放后的Bitmap --- FileOutputStream out = new FileOutputStream(dest); // PNG格式下质量参数无效,填100即可 scaledBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); // 记得回收不再使用的Bitmap,避免内存泄漏 if (scaledBitmap != bitmap) { scaledBitmap.recycle(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
额外实用提示:
- 如果需要保持图片比例的同时限制最大宽度/高度,可以这样计算目标尺寸:
int maxWidth = 1080; // 你想要的最大宽度 float scaleFactor = (float) maxWidth / bitmap.getWidth(); int targetWidth = maxWidth; int targetHeight = (int) (bitmap.getHeight() * scaleFactor); - 要是用JPG格式保存,
compress的质量参数(0-100)才会生效,数值越小压缩率越高,但你需求是PNG的话就不用在意这个参数了。 - 每次创建目录前先判断是否存在,避免重复创建的无效操作。
内容的提问来源于stack exchange,提问作者rs11




