如何顯示2個圖片的合成效果,例如在檔案上蓋章,要求印章圖片透明。
假設檔案圖片為p1,印章圖片為p2。
BufferedImage bi1 = null;
int x = 10;
int y = 10;
BufferedImage bi2 = null;
try {
bi1 = javax.imageio.ImageIO.read(new File("p1.jpg"));
bi2 = javax.imageio.ImageIO.read(new File("p2.png"));
} catch (IOException e) {
e.printStackTrace();
}
Graphics g = bi1.getGraphics();
g.drawImage(bi2, x, y, null);
FileOutputStream out=null; //輸出到檔案流
try {
out = new FileOutputStream("p.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(bi1);
out.close();
} catch (IOException e) {
e.printStackTrace();合并國
} -
p1背景圖,p2印章,p為輸出圖。p2要是gif或png等支援透明圖象的。
x,y 為在背景圖放置印章的座標( 左上方開始算)。
在Java2D中設定畫圖的透明度:
float alpha = 0.5f; // 透明度
Graphics2D g2d = bufferedImage.createGraphics();
// 設定透明
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP, alpha)); // 開始
// g2d.drawImage(); // 畫圖
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER)); // 結束