需求:
Java实现对图片压缩指定大小。比如1260*945。如果图片尺寸大于,就压缩。小于,就拉伸到指定大小
代码实现:
import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO;public class ImageProcessor {public static void main(String[] args) {String inputImagePath = "input.jpg"; // 输入图片路径String outputImagePath = "output.jpg"; // 输出图片路径int targetWidth = 1260;int targetHeight = 945;try {BufferedImage inputImage = ImageIO.read(new File(inputImagePath));// 获取原始图片的尺寸int originalWidth = inputImage.getWidth();int originalHeight = inputImage.getHeight();// 创建一个新的 BufferedImage,用于存放处理后的图片BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, inputImage.getType());// 创建一个 Graphics2D 对象,用于绘制新图片Graphics2D graphics = outputImage.createGraphics();// 如果原始图片尺寸大于目标尺寸,则进行压缩if (originalWidth > targetWidth || originalHeight > targetHeight) {Image scaledImage = inputImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);graphics.drawImage(scaledImage, 0, 0, null);} else {// 如果原始图片尺寸小于目标尺寸,则进行拉伸graphics.drawImage(inputImage, 0, 0, targetWidth, targetHeight, null);}// 释放资源graphics.dispose();// 保存处理后的图片ImageIO.write(outputImage, "jpg", new File(outputImagePath));System.out.println("图片处理完成。");} catch (IOException e) {e.printStackTrace();}} }