
也就是图片压缩,可以不修改任何大小的压缩(速度快),也可等比例修改大小压缩(较慢)下面这是一段等比例缩小图片的方法 。public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp,String hzm) { try { if (!image.exists()) { return ""; } Image img = ImageIO.read(image); // 判断图片格式是否正确 if (img.getWidth(null) == -1) { return "no"; } else { int newWidth; int newHeight; // 判断是否是等比缩放 if (gp == true) { // 为等比缩放计算输出的图片宽度及高度 double rate1 = ((double) img.getWidth(null)) / (double) width ; double rate2 = ((double) img.getHeight(null)) / (double) height ; // 根据缩放比率大的进行缩放控制 double rate = rate1 > rate2 ? rate1 : rate2; newWidth = (int) (((double) img.getWidth(null)) / rate); newHeight = (int) (((double) img.getHeight(null)) / rate); } else { newWidth = img.getWidth(null); // 输出的图片宽度 newHeight = img.getHeight(null); // 输出的图片高度 } BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB); /* * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 * 优先级比速度高 生成的图片质量比较好 但速度慢 */ Image im = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH); tag.getGraphics().drawImage(im, 0, 0, null); FileOutputStream out = new FileOutputStream(outputDir + outputFileName); //JPEGImageEncoder可适用于其他图片类型的转换 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } } catch (IOException ex) { ex.printStackTrace(); } return "ok"; }
【java如何实现把一个大图片压缩到指定大小的图片且长宽比不变】
猜你喜欢
- 淘宝如何取消店铺优惠活动?淘宝活动有哪些值得参与?
- 立冬节气如何养生 立冬节气养生注意事项
- 你觉得陈赫在《瞄准》里面的演技如何?
- 想要北海市海边租房1个月,不知道可有这样的业务,如何联系
- 红糖大枣水怎么煮 红糖大枣水如何煮
- Python修改文件指定行怎么做?Python如何修改文本文件指定行内容
- Python坐标轴标签中文出错怎么办?Python坐标轴字体大小如何调整
- Python坐标轴范围如何设置?Matplotlib绘图怎么设置坐标轴范围
- Python设置坐标轴名称怎么做?Python坐标轴标签如何倾斜
- Python画三维折线图代码是什么?Python如何绘制三维折线图
