Java的圖片處理 – 合并圖片

來源:互聯網
上載者:User

  如何顯示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)); // 結束 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.