由于经常要写文档和宣传彩页,里面都有涉及图片,强制调整了图片大小,导致图片变得模糊。所以需要提供一个工具,这就变得很重要了。我这里提供java代码,可以进行图片大小调整,至于调多少,你说了算。
看代码:
public static void main(String[] args) {String inputPath = "D:/file/gpt114.png"; //gpt114.com小图标String outputPath = "D:/file/gpt114-123.png"; // 输出图片路径int targetWidth = 32; // 目标宽度int targetHeight = 32; // 目标高度tosize(outputPath,targetWidth,targetHeight,outputPath); }
private static void tosize(String inputPath, int targetWidth, int targetHeight, String outputPath) {try {BufferedImage originalImage = ImageIO.read(new File(inputPath));BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics2D = resizedImage.createGraphics();graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);graphics2D.drawImage(originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);graphics2D.dispose();ImageIO.write(resizedImage, "png", new File(outputPath)); // 根据需要更改文件格式,如"jpg"System.out.println("图片大小调整并保存成功!");} catch (IOException e) {e.printStackTrace();} }