URL轉二維碼以及圖片合成

最近項目中有一個需求,要將一個URL鏈接轉成二維碼,併合成到一個固定的背景圖片上的指定位置。其實將二維碼合成到圖片上還是將圖片合成到二維碼上,都是同一個道理。

需要採用google提供的 'com.google.zxing', name: 'core', version: '3.3.3'   包 來將URL轉化成二維碼圖片。

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;


 /**
     * 
     * @param url  需要封裝到二維碼中的地址
     * @param Qrheight 二維碼高
     * @param Qrwidth  二維碼寬 
     * @return
     * @throws WriterException
     */
    private static BufferedImage createImage(String  url,int Qrheight,int Qrwidth) throws WriterException {
    	Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, Qrheight, Qrwidth, hints);
        int width = Qrheight;
        int height = Qrwidth;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }




    /**
	    * 合成圖片
	 * @param url		二維碼鏈接
	 * @param path		背景圖片地址
	 * @param startX	二維碼在背景圖片的X軸位置
	 * @param startY	二維碼在背景圖片的Y軸位置
	 * @param codeWidth	二維碼寬度
	 * @param codeHeight 二維碼高度
	 * @return			合成的圖片
	 */
	public static BufferedImage compositeImage(String url, String path, int startX, int startY, int codeWidth, int codeHeight) {
		try {
			BufferedImage headImage = createImage(url, codeWidth, codeHeight);
			
			Image backImage = null;
			
			FileInputStream fileInputStream = new FileInputStream(path);
	      //backBIS64 = ImageUtil.GetImageStr(fileInputStream);
		   // 讀取背景圖片
			
			backImage = ImageIO.read(fileInputStream);
			int alphaType = BufferedImage.TYPE_INT_RGB;
			BufferedImage back = new BufferedImage(backImage.getWidth(null), backImage.getHeight(null), alphaType);
			// 畫圖
			Graphics2D g = back.createGraphics();
			g.drawImage(backImage, 0, 0, null);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
			g.drawImage(headImage, startX, backImage.getHeight(null) - startY, headImage.getWidth(null), headImage.getHeight(null), null);
 
			 g.setColor(Color.gray); 
             g.setFont(new Font("宋體",Font.CENTER_BASELINE,10)); //字體、字型、字號 
             g.drawString("購車請識別二維碼", startX+2, backImage.getHeight(null) - startY+97 );
			
			g.dispose();
 
			return back;
 
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	

成品如圖所示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章