网站首页 网站建设 IT知识 IT知识教程 java对图片进行压缩和resize缩放的方法

java对图片进行压缩和resize缩放的方法

2021-05-19 21:24:06


这里展示一下如何对图片进行压缩和resize。分享给大家,具体如下:

压缩

public static boolean compress(String src,String to, float quality) { boolean rs = true; // Build param JPEGEncodeParam param = null; // Build encoder File destination = new File(to); FileOutputStream os = null; try { BufferedImage image = ImageIO.read(new File(src)); param = JPEGCodec.getDefaultJPEGEncodeParam(image); param.setQuality(quality, false); os = FileUtils.openOutputStream(destination); JPEGImageEncoder encoder; if (param != null) { encoder = JPEGCodec.createJPEGEncoder(os, param); } else { return false; } encoder.encode(image); } catch(Exception e){ e.printStackTrace(); rs = false; }finally { IOUtils.closeQuietly(os); } return rs; }

resize

public static boolean resize(String src,String to,int newWidth,int newHeight) { try { File srcFile = new File(src); File toFile = new File(to); BufferedImage img = ImageIO.read(srcFile); int w = img.getWidth(); int h = img.getHeight(); BufferedImage dimg = new BufferedImage(newWidth, newHeight, img.getType()); Graphics2D g = dimg.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null); g.dispose(); ImageIO.write(dimg, "jpg", toFile); } catch (Exception e) { e.printStackTrace(); return false; } return true; }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。 如涉及版权问题,请提交至online#300.cn邮箱联系删除。

以上产品还未完全满足我的所有需求,在下方提交我的专属需求
我的专属需求:
*手机号:
*验证码:
img
咨询报价
现在咨询
img

在线咨询

建站在线咨询

img

微信咨询

扫一扫添加
动力姐姐微信

img
img

TOP