我们通过java把下面的背景图和二维码以及文字“java菜市场-专注于技术干货的免费分享”合并成一张新的图片
背景图片
二维码图片
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); } }
最终生成的合成后的图片:
如果想了解通过java实现图片压缩、裁剪、翻转、添加水印等,请参考这篇文章:
java使用google开源工具Thumbnailator实现图片压缩