java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java调整图片大小

Java调整图片大小的3种方式小结

作者:入夏忆梦

在软件开发中处理图像是一个常见任务,特别是当我们需要优化图像尺寸以适应不同的应用场景时,这篇文章主要介绍了Java调整图片大小的3种方式,需要的朋友可以参考下

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("图片尺寸调整完成!");

总结 

到此这篇关于Java调整图片大小的3种方式小结的文章就介绍到这了,更多相关Java调整图片大小内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文