图片居中

前言

在开发过程中,有时候想要将一张图片在另外一张图片居中显示,可以采取一下做法

图片居中显示

java 复制代码
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;


public class ImageCenterDisplayDemo {

    static void main() {
        try {
            // 1. 加载子图像(要居中显示的图像)
            BufferedImage subImage = ImageIO.read(new File("D:\temp\2.png"));
            // 2. 创建父图像(画布,这里创建800x600的空白图像,也可以加载现有图像)
            int parentWidth = 2000;
            int parentHeight = 2000;
            BufferedImage parentImage = new BufferedImage(parentWidth, parentHeight, BufferedImage.TYPE_INT_RGB);

            // 3. 调用方法将子图像居中绘制到父图像
            BufferedImage resultImage = drawImageCentered(parentImage, subImage);

            // 4. 保存结果图像(可选)
            ImageIO.write(resultImage, "PNG", new File("d:/result.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将子图像居中绘制到父图像上
     *
     * @param parentImage 父图像(画布)
     * @param subImage    子图像(要居中的图像)
     * @return 绘制后的图像
     */
    public static BufferedImage drawImageCentered(BufferedImage parentImage, BufferedImage subImage) {
        // 获取父图像和子图像的宽高
        int parentW = parentImage.getWidth();
        int parentH = parentImage.getHeight();
        int subW = subImage.getWidth();
        int subH = subImage.getHeight();

        // 计算居中坐标(水平居中x,垂直居中y)
        int x = (parentW - subW) / 2;
        int y = (parentH - subH) / 2;

        // 获取Graphics2D对象(用于绘制)
        Graphics2D g2d = parentImage.createGraphics();
        try {
            // 开启抗锯齿(可选,让图像边缘更平滑)
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            // 绘制子图像到居中坐标
            g2d.drawImage(subImage, x, y, null);
        } finally {
            // 释放资源
            g2d.dispose();
        }

        return parentImage;
    }
}

结果为

总结

可以使用以上方法将图片居中显示

相关推荐
倔强的石头_6 小时前
WorkBuddy 上手实战:打造一个可用的本地 AI 工作台
后端
苍何11 小时前
Coding 真有质的飞跃?实测下豆包seed 2.1 pro
后端
苍何11 小时前
试了下腾讯 Marvis,回不去了...
后端
caibixyy12 小时前
springboot+langchain4j 实战 Day14——工具嵌入多 Agent(Tool-Equipped Multi-Agent)
后端
caibixyy12 小时前
springboot+langchain4j 实战 Day13 多 Agent 协作(Router + 子 Agent 分流)
后端
飘尘12 小时前
前端转全栈(Java 后端)必须要知道的:开发中的锁机制与分布式并发控制
前端·后端·全栈
苍何12 小时前
清华团队做了个具身智能大脑,有点东西!
后端
fliter12 小时前
强类型的诅咒,还是 Rust 类型系统的生存指南
后端
用户83562907805112 小时前
Python 操作 PDF 附件:添加、查看与管理指南
后端·python