1 /** 2 * 頭像裁剪,組合圖片,生成海報 3 * @param picUrl 4 * @param headPic 5 * @throws Exception 6 */ 7 public void createPost(String picUrl,String headPic) throws Exception{ 8 int width1 = 130; 9 URL url1 = new URL(headPic);//背景圖片 10 BufferedImage headPicImg = ImageIO.read(url1); 11 // 透明底的圖片 12 BufferedImage formatAvatarImage = new BufferedImage(width1, width1, BufferedImage.TYPE_INT_RGB); 13 14 Graphics2D graphics = formatAvatarImage.createGraphics(); 15 graphics.setColor(Color.white); //GREEN:綠色; 紅色:RED; 灰色:GRAY 白色:white 16 graphics.fillRect(0, 0, width1, width1); 17 //把圖片切成一個圓 18 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 19 //留一個像素的空白區域,這個很重要,畫圓的時候把這個覆蓋 20 int border =1; 21 //圖片是一個圓型 22 Ellipse2D.Double shape = new Ellipse2D.Double(border, border, width1 - border * 2, width1 - border * 2); 23 //須要保留的區域 24 graphics.setClip(shape); 25 graphics.drawImage(headPicImg, border, border, width1 - border * 2, width1 - border * 2, null); 26 //繪製二維碼 27 HashMap hints = new HashMap(); 28 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //指定字符編碼爲「utf-8」 29 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //指定二維碼的糾錯等級爲中級 30 hints.put(EncodeHintType.MARGIN, 1); //設置圖片的邊距 31 BitMatrix bitMatrix = new MultiFormatWriter().encode( "愛你一萬年", BarcodeFormat.QR_CODE, 250, 250, hints); 32 BufferedImage ii = toBufferedImage(bitMatrix); 33 URL url = new URL(picUrl);//背景圖片 34 BufferedImage picUrlImg = ImageIO.read(url); 35 36 //繪製寬=480,長=640的圖板 37 int width = 750, hight = 1606; 38 BufferedImage image = new BufferedImage(width, hight, BufferedImage.TYPE_INT_RGB); 39 //獲取圖形上下文,graphics想象成一個畫筆 40 graphics = (Graphics2D) image.getGraphics(); 41 //消除線條鋸齒 42 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 43 //對指定的矩形區域填充顏色 44 graphics.setColor(Color.white); //GREEN:綠色; 紅色:RED; 灰色:GRAY 白色:white 45 graphics.fillRect(0, 0, 750, 1606); 46 //對指定的矩形區域填充顏色 47 graphics.drawImage(picUrlImg,0,0,null); 48 graphics.drawImage(formatAvatarImage,30,1326,null); 49 graphics.drawImage(ii,470,1326,null); 50 51 Font font=new Font("宋體",Font.BOLD,28); 52 graphics.setFont(font); 53 graphics.setColor(Color.BLACK); 54 graphics.drawString("徐睿", 170, 1386); 55 graphics.drawString("18703652539", 170, 1416); 56 font=new Font("宋體",Font.ITALIC,25); 57 graphics.setFont(font); 58 graphics.setColor(Color.BLACK); 59 graphics.drawString("我是你的專屬客服,您有任何關於", 50, 1496); 60 graphics.drawString("信用卡申請的相關問題可隨時向我", 50, 1536); 61 graphics.drawString("諮詢", 50, 1576); 62 63 //graphics.setPaintMode(); 64 //graphics.translate(400, 600); 65 66 graphics.dispose();//釋放此圖形的上下文並釋放它所使用的全部系統資源 67 FileOutputStream out = new FileOutputStream("D:\\yy/1.jpeg"); 68 ImageIO.write(image, "JPEG", out); 69 70 out.flush(); 71 out.close(); 72 73 }