Java调整图片大小的三种方式

1:使用Thumbnailator

Thumbnailator是Java的开源图像大小调整库,它使用渐进式双线性缩放。它支持JPG,BMP,JPEG,WBMP,PNG和GIF。

通过将以下Maven依赖项添加到我们的pom.xml中,将其包括在我们的项目中:

pom.xml

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.11</version>
</dependency>

工具类ThumbnailsUtils

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ThumbnailsUtils{
    private static final Logger logger = LoggerFactory.getLogger(ThumbnailsUtils.class);

    /**
     * 通过BufferedImage图片流调整图片大小
     */
    public static BufferedImage resizeImageOne(BufferedImage originalImage, int targetWidth, int targetHeight) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Thumbnails.of(originalImage)
                .size(targetWidth, targetHeight)
                .outputFormat("JPEG")
                .outputQuality(1)
                .toOutputStream(outputStream);
        byte[] data = outputStream.toByteArray();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
        return ImageIO.read(inputStream);
    }
   
    /**
     * BufferedImage图片流转byte[]数组
     */
    public static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "jpg", out);
        } catch (IOException e) {
            logger.error("错误信息: ", e);
        }
        return out.toByteArray();
    }


    /**
     * byte[]数组转BufferedImage图片流
     */
    private static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
        ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            logger.error("错误信息: ", e);
        }
        return image;
    }
}

2:Graphics2D 自带的方法

 public static BufferedImage scaleImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, type);
        Graphics2D g = scaledImage.createGraphics();
// Calculate the ratio between the original and scaled image size
        double scaleX = (double) targetWidth / originalImage.getWidth();
        double scaleY = (double) targetHeight / originalImage.getHeight();
        double scale = Math.min(scaleX, scaleY);
// Now we perform the actual scaling
        int newWidth = (int) (originalImage.getWidth() * scale);
        int newHeight = (int) (originalImage.getHeight() * scale);
        int x = (targetWidth - newWidth) / 2;
        int y = (targetHeight - newHeight) / 2;
        g.drawImage(originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), x, y, null);
        g.dispose();
        return scaledImage;
    }
 public static void main(String[] args) throws Exception {
    // 读取原始图片
    File originalFile = new File("D:\\test1\\schoolLogo.png");
    BufferedImage originalImage = ImageIO.read(originalFile);

    // 设定目标宽高
    int targetWidth =  1000; // 两倍放大
    int targetHeight = 1000; // 两倍放大

    // 调用 resizeImageOne 方法进行放大
    BufferedImage resizedImage =  ThumbnailsUtils.scaleImage(originalImage, targetWidth, targetHeight);

    // 将放大后的图片保存到文件
    File outputFile = new File("D:\\test1\\big.png");
    ImageIO.write(resizedImage, "png", outputFile);
}

3:前两种我在使用 ImageCombiner 项目的时候 不生效;

   // 创建新的 BufferedImage,并设置绘制质量
            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = resizedImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            // 绘制原始图像到新的 BufferedImage,并进行缩放
            Image scaledImage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            g2d.drawImage(scaledImage, 0, 0, null);
            g2d.dispose();

            // 保存新的图片
            String outputImagePath = "C:\\Users\\up1.jpg"; // 替换为实际的输出路径
            ImageIO.write(resizedImage, "jpg", new File(outputImagePath));

            System.out.println("图片尺寸调整完成!");

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要在Java调整图片的大小,你可以使用Java的内置图像处理库javax.imageio和java.awt.image。下面是一个简单的示例代码,展示了如何调整图片的大小: ```java import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageResizeExample { public static void main(String[] args) { try { // 读取原始图片 File inputFile = new File("input.jpg"); BufferedImage inputImage = ImageIO.read(inputFile); // 设置新图片的大小 int newWidth = 300; int newHeight = 200; // 创建新图片 BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType()); // 绘制新图片 Graphics2D graphics2D = outputImage.createGraphics(); graphics2D.drawImage(inputImage, 0, 0, newWidth, newHeight, null); graphics2D.dispose(); // 保存新图片 File outputFile = new File("output.jpg"); ImageIO.write(outputImage, "jpg", outputFile); System.out.println("成功调整图片大小!"); } catch (Exception e) { System.out.println("调整图片大小出错: " + e.getMessage()); } } } ``` 在上面的示例中,我们首先从文件系统中读取原始图片(input.jpg),然后创建一个缓冲图像(BufferedImage)来存储调整后的图片。接下来,我们使用Graphics2D对象来绘制新图片,并指定新的宽度和高度。最后,我们将调整后的图片保存到文件系统中(output.jpg)。 请确保替换示例代码中的输入和输出文件路径以适应你的实际需求。此外,还可以根据需要调整图片的宽度和高度。 希望这可以帮助到你!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

入夏忆梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值