java实现多张图片和文字合并 java图片合成示例代码

我们通过java把下面的背景图和二维码以及文字“java菜市场-专注于技术干货的免费分享”合并成一张新的图片


背景图片

background的副本.gif


二维码图片

qrcode的副本.gif


public class Main {


    /**
     * 合成图片
     *
     * @param backgroundPath
     * @param qrCodePath
     * @param message
     * @param outPutPath
     * @throws IOException
     */
    public static void overlapImage(String backgroundPath, String qrCodePath, String message, String outPutPath) throws IOException {

        // 设置背景图片大小
        BufferedImage backgroundImage = resizeImage(566, 230, ImageIO.read(new File(backgroundPath)));
        // 设置二维码图片大小
        BufferedImage qrCodeImage = resizeImage(150, 150, ImageIO.read(new File(qrCodePath)));

        Graphics2D graphics = backgroundImage.createGraphics();

        // 在背景图片上添加文字
        graphics.setColor(Color.white);
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 20));
        graphics.drawString(message, 100, 40);

        // 在背景图片上添加二维码图片
        graphics.drawImage(qrCodeImage, 210, 60, qrCodeImage.getWidth(), qrCodeImage.getHeight(), null);
        graphics.dispose();

        // 输出新的图片
        ImageIO.write(backgroundImage, "png", new File(outPutPath));
    }

    /**
     * 重新设置图片大小
     *
     * @param width
     * @param height
     * @param bufferedImage
     * @return
     */
    private static BufferedImage resizeImage(int width, int height, BufferedImage bufferedImage) {
        BufferedImage newBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        newBufferedImage.getGraphics().drawImage(bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        return newBufferedImage;
    }

    public static void main(String[] args) throws IOException {
        String backgroundPath = "/Users/admin/Desktop/background.png";
        String qrCodePath = "/Users/admin/Desktop/qrcode.png";
        String message = "java菜市场-专注于技术干货的免费分享";
        String outPutPath = "/Users/admin/Desktop/newImage.png";

        overlapImage(backgroundPath, qrCodePath, message, outPutPath);
    }

}


最终生成的合成后的图片:

newImage的副本.gif


如果想了解通过java实现图片压缩、裁剪、翻转、添加水印等,请参考这篇文章:

java使用google开源工具Thumbnailator实现图片压缩


打赏 支付宝打赏 微信打赏

如果文章对您有帮助,欢迎移至上方打赏按钮...

随手一点
  • 打酱油

    57人

  • 6人

  • 呵呵

    0人

  • 草泥马

    0人

文章评论 抢沙发