用js兩張圖片合並成一張圖片


JS和canvas的合成方式

function drawAndShareImage(){
var canvas = document.createElement("canvas");
canvas.width = 700;
canvas.height = 700;
var context = canvas.getContext("2d");

context.rect(0 , 0 , canvas.width , canvas.height);
context.fillStyle = "#fff";
context.fill();

var myImage = new Image();
myImage.src = "./2.png"; //背景圖片 你自己本地的圖片或者在線圖片
myImage.crossOrigin = 'Anonymous';

myImage.onload = function(){
context.drawImage(myImage , 0 , 0 , 700 , 700);

context.font = "60px Courier New";
context.fillText("我是文字",350,450);

var myImage2 = new Image();
myImage2.src = "./1.png"; //你自己本地的圖片或者在線圖片
myImage2.crossOrigin = 'Anonymous';

myImage2.onload = function(){
context.drawImage(myImage2 , 175 , 175 , 225 , 225);
var base64 = canvas.toDataURL("image/png"); //"image/png" 這里注意一下
var img = document.getElementById('avatar');

// document.getElementById('avatar').src = base64;
img.setAttribute('src' , base64);
}
}
}

PS:在線圖片和本地圖片都要注意下跨越的問題,最好放在服務器上測試。

 

 

java的實現方式

public static String generateCode(String codeUrl, Integer userId, String userName) {
Font font = new Font("微軟雅黑", Font.PLAIN, 30);// 添加字體的屬性設置

String projectUrl = PathKit.getWebRootPath() + "/before/codeImg/";
String imgName = projectUrl + userId + ".png";
try {
// 加載本地圖片
String imageLocalUrl = projectUrl + "weixincode2.png";
BufferedImage imageLocal = ImageIO.read(new File(imageLocalUrl));
// 加載用戶的二維碼
BufferedImage imageCode = ImageIO.read(new URL(codeUrl));
// 以本地圖片為模板
Graphics2D g = imageLocal.createGraphics();
// 在模板上添加用戶二維碼(地址,左邊距,上邊距,圖片寬度,圖片高度,未知)
g.drawImage(imageCode, 575, imageLocal.getHeight() - 500, 350, 350, null);
// 設置文本樣式
g.setFont(font);
g.setColor(Color.BLACK);
// 截取用戶名稱的最后一個字符
String lastChar = userName.substring(userName.length() - 1);
// 拼接新的用戶名稱
String newUserName = userName.substring(0, 1) + "**" + lastChar + " 的邀請二維碼";
// 添加用戶名稱
g.drawString(newUserName, 620, imageLocal.getHeight() - 530);
// 完成模板修改
g.dispose();
// 獲取新文件的地址
File outputfile = new File(imgName);
// 生成新的合成過的用戶二維碼並寫入新圖片
ImageIO.write(imageLocal, "png", outputfile);
} catch (Exception e) {
e.printStackTrace();
}
// 返回給頁面的圖片地址(因為絕對路徑無法訪問)
imgName = Constants.PROJECT_URL + "codeImg/" + userId + ".png";

return imgName;
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM