调用java自带的image合成图片

直接上源码,在一张图片上加另外一张图片

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {

public static void main(String[] args) {

try {

//读取背景图片
BufferedInputStream backBIS = new BufferedInputStream( new FileInputStream("back.jpg"));
Image backImage = ImageIO.read(backBIS);


//读取头像图片
BufferedInputStream headBIS = new BufferedInputStream( new FileInputStream("head.png"));
Image headImage = ImageIO.read(headBIS);

if (backImage == null)
System.out.println("haha null");
int alphaType = BufferedImage.TYPE_INT_RGB;
if (hasAlpha(backImage)) {
alphaType = BufferedImage.TYPE_INT_ARGB;
}

//画图
BufferedImage backgroundImage = new BufferedImage(backImage.getWidth(null), backImage.getHeight(null), alphaType);
Graphics2D g = backgroundImage.createGraphics();
g.drawImage(backImage, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP, 1));
g.drawImage(headImage, 133, 133, headImage.getWidth(null),headImage.getHeight(null), null);

//输出
byte[] imageInByte = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(backgroundImage, "png", baos);
imageInByte = baos.toByteArray();
baos.close();

BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("output.png"));
output.write(imageInByte);
output.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("succ");
}


/**
* 是否开启alpha通道
* @param image
* @return
*/
public static boolean hasAlpha(Image image) {
if (image instanceof BufferedImage) {
BufferedImage bimage = (BufferedImage)image;
return bimage.getColorModel().hasAlpha();
}
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
ColorModel cm = pg.getColorModel();
return cm.hasAlpha();
}


}

你可能感兴趣的:(image)