package com.jeffchen.pic;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import javax.imageio.ImageIO;public class GetPic { /** * 加载图片到缓冲区 * @param path 图片路径 * @return BufferedImage */ public static BufferedImage getPic(String path){ BufferedImage bufferImage = null; try { bufferImage = ImageIO.read(new File(path)); } catch (IOException e) { e.printStackTrace(); } return bufferImage; } /** * 合并图片 * @param bgimage 背景图片 * @param hdimage 合并的图片 * @param x X坐标定位 * @param y Y坐标定位 * @param width 插入图片的宽 * @param height 插入图片的高 * @return 若合并成功,返回ture */ public static boolean combinePic(BufferedImage bgimage,BufferedImage hdimage,int x,int y,int width,int height){ //创建画板 Graphics2D g2d = bgimage.createGraphics(); //画图 g2d.drawImage(hdimage, x, y, width, height, null); //释放资源 g2d.dispose(); return true; } /** * 保存合并后的图片 * @param image * @param savePath * @return */ public static boolean saveImage(BufferedImage image,String savePath){ try { ImageIO.write(image, "jpg",new FileOutputStream(savePath) ); } catch (IOException e) { e.printStackTrace(); } return true; } public static void main(String[] args) { //加载图片 BufferedImage backgroupImage = getPic("bg.jpg"); BufferedImage headImage = getPic("head.jpg"); BufferedImage qrcodeImage = getPic("qrcode.png"); //合并图片 combinePic(backgroupImage, headImage, 50, 680, 100, 100); combinePic(backgroupImage, qrcodeImage, 300, 680, 100, 100); //保存图片 saveImage(backgroupImage, "newImage.jpg"); }}
|