圖片疊加效果Java代碼實現,疊加效果java代碼
本文執行個體為大家分享了Java實現圖片疊加效果展示的具體代碼,供大家參考,具體內容如下
import java.awt.AlphaComposite;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class NewImageUtils { /** * * @Title: 構造圖片 * @Description: 產生浮水印並返回java.awt.image.BufferedImage * @param file * 源檔案(圖片) * @param waterFile * 浮水印檔案(圖片) * @param x * 距離右下角的X位移量 * @param y * 距離右下角的Y位移量 * @param alpha * 透明度, 選擇值從0.0~1.0: 完全透明~完全不透明 * @return BufferedImage * @throws IOException */ public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException { // 擷取底圖 BufferedImage buffImg = ImageIO.read(file); // 擷取層圖 BufferedImage waterImg = ImageIO.read(waterFile); // 建立Graphics2D對象,用在底圖對象上繪圖 Graphics2D g2d = buffImg.createGraphics(); int waterImgWidth = waterImg.getWidth();// 擷取層圖的寬度 int waterImgHeight = waterImg.getHeight();// 擷取層圖的高度 // 在圖形和映像中實現混合和透明效果 g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); // 繪製 g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null); g2d.dispose();// 釋放圖形上下文使用的系統資源 return buffImg; } /** * 輸出浮水印圖片 * * @param buffImg * 映像加浮水印之後的BufferedImage對象 * @param savePath * 映像加浮水印之後的儲存路徑 */ private void generateWaterFile(BufferedImage buffImg, String savePath) { int temp = savePath.lastIndexOf(".") + 1; try { ImageIO.write(buffImg, savePath.substring(temp), new File(savePath)); } catch (IOException e1) { e1.printStackTrace(); } } /** * * @param args * @throws IOException * IO異常直接拋出了 * @author bls */ public static void main(String[] args) throws IOException { String sourceFilePath = "D://img//di.png"; String waterFilePath = "D://img//ceng.png"; String saveFilePath = "D://img//new.png"; NewImageUtils newImageUtils = new NewImageUtils(); // 構建疊加層 BufferedImage buffImg = NewImageUtils.watermark(new File(sourceFilePath), new File(waterFilePath), 0, 0, 1.0f); // 輸出浮水印圖片 newImageUtils.generateWaterFile(buffImg, saveFilePath); }}
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。