// 用到的包 import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.Date;
public static void main(String[] args) { try { String serverUploadImgUrl = "/Users/biusun/Desktop/"; // 圖片保存路徑 // 背景圖片 (注:此圖片來源於網絡) String backImgUrlStr = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1587644051898&di=54814ecdba4457113823e78af9d55682&imgtype=0&src=http%3A%2F%2Fpic.90sjimg.com%2Fdesign%2F01%2F45%2F68%2F00%2F5901fb923c111.png"; InputStream backImgUrl = new URL(backImgUrlStr).openStream(); BufferedImage backImg = ImageIO.read(backImgUrl); // 要合並的圖片 (注:此圖片來源於網絡) String imgUrlStr = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1587644124018&di=fbd350136cf6cd21f985f89e1ecda7d8&imgtype=0&src=http%3A%2F%2Fimgs.shougongke.com%2FPublic%2Fdata%2Fhand%2F201507%2F08%2Fstep%2F38%2F1436341208928.jpg"; InputStream imgUrl = new URL(imgUrlStr).openStream(); BufferedImage img = ImageIO.read(imgUrl); int backImgNewWidth = backImg.getWidth();// 背景圖片寬度 int backImgNewHeight = backImg.getHeight();// 背景圖片高度度 // 生成新的合並的圖片(調整圖片的大小) int imgNewWidth = backImgNewWidth / 3; // BufferedImage imgNew = new BufferedImage(圖片寬度, 圖片高度, 圖像類型); BufferedImage imgNew = new BufferedImage(imgNewWidth, imgNewWidth, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = imgNew.createGraphics(); g2d.drawImage(img, 0, 0, imgNew.getWidth(), imgNew.getHeight(), null); g2d.dispose(); // 兩圖片合並 int imgNewWidthPosition = (backImgNewWidth - imgNewWidth) / 2; int imgNewHeightPosition = (backImgNewHeight - imgNewWidth) / 2; Graphics g = backImg.getGraphics(); // backImg(注意 // g.drawImage(圖片, x 位置, y 位置, null); g.drawImage(imgNew, imgNewWidthPosition, imgNewHeightPosition, null); //把 imgNew,整合在 backImg 里面 // g.dispose(); //最后一個參數用來設置字體的大小(文字放在 liunx,可能會亂碼,那是因為服務器上沒有這個字體,要上傳,自行百度) Font fTxtBottom = new Font("微軟雅黑", Font.PLAIN, 30); Color myColorTxtBottom = Color.BLACK; //圖片顏色 g.setColor(myColorTxtBottom); g.setFont(fTxtBottom); // g.drawString(文字, x 位置, y 位置); g.drawString("陌生人,您好!", backImgNewWidth / 2, backImgNewHeight / 5); // 第二段文字 (圖片也可以多張) // Font fTxtBottom = new Font("微軟雅黑", Font.PLAIN, 30); // Color myColorTxtBottom = Color.BLACK; //圖片顏色 // g.setColor(myColorTxtBottom); // g.setFont(fTxtBottom); //// g.drawString(文字, x 位置, y 位置); // g.drawString("陌生人,您好!", backImgNewWidth / 2, backImgNewHeight / 3); g.dispose(); //調這個方法就是開始這個整合 (可以多張圖片,多個文字整合成一張圖片,只有把他們放在這方法里面就行) String imgName = new Date().getTime() + ".jpg"; //生成的圖片名稱 File newFile = new File(serverUploadImgUrl, imgName); //生成新的圖片 // 此處要寫PNG否則可能會出現遮罩層 ImageIO.write(backImg, "png", newFile); } catch (Exception e) { e.printStackTrace(); } System.out.println("結束"); }