java 代碼生成二維碼

以前,二維碼是H5端進行生成的,是寫死的。如今有一個需求,要求後臺服務根據不一樣客戶的邀請碼,生成不一樣的邀請連接二維碼。java

思路: 首先根據需求,生成二維碼,並在二維碼的中間添加logo,將二維碼上傳至fasdtfs服務器上,將該二維碼在服務器的地址返回給h5端。便可。web

詳細代碼以下:spring

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import net.mikesu.fastdfs.FastdfsClient;
import net.mikesu.fastdfs.FastdfsClientFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.minxin.me.backstage.commons.PropertiesLoader;
import com.minxin.me.backstage.commons.validator.ValidatorConstants;
import com.minxin.me.backstage.platform.customer.bean.CustomerInfoDto;
import com.minxin.me.backstage.platform.mangquerymyrefer.service.MangQueryMyReferService;
import com.minxin.me.backstage.web.util.BaseUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;

@Controller
public class CreateTwoDimensionalController {
	private static final Logger logger = LoggerFactory.getLogger(CreateTwoDimensionalController.class);
	
	private static final String LOGO_NAME = "ic_launcher.png";
	private static final String LOGO_URL = "/static/template/logo/";
	private static final String LOGO_TEMP_URL = "/static/template/temp/";
	private String webappDir;
	private static final Color defaultBackgroundColor = new Color(255, 255, 255, 0);
    private static final Color defaultForegroundColor = new Color(0, 0, 0, 1);
    private static final Color defaultLogoBoundColor = new Color(0, 0, 255, 0);
    private int background = defaultBackgroundColor.getRGB();
    private int foreground = defaultForegroundColor.getRGB(); 
	private double logoRatio = 0.2;
	private Color logoBoundColor = defaultLogoBoundColor;
	private Configuration configuration;
	
	@Autowired
	MangQueryMyReferService mangQueryMyReferService;
	@Autowired
	private PropertiesLoader proputil;
	
	public CreateTwoDimensionalController(){
		try {
			String dir = this.getClass().getClassLoader().getResource("/").getPath();
			dir = URLDecoder.decode(dir, "UTF-8");
			webappDir = new File(dir, "../..").getCanonicalPath();
			configuration = new Configuration();
			configuration.setDirectoryForTemplateLoading(new File(webappDir
					+ LOGO_URL));
			configuration.setObjectWrapper(new DefaultObjectWrapper());
			configuration.setDefaultEncoding("UTF-8"); // 這個必定要設置,否則在生成的頁面中 會亂碼
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	@RequestMapping(value = "/createTwoDimensional")
	@ResponseBody
	public CreateTwoDimensionalResponse createTwoDimensional(CreateTwoDimensionalRequest request){
		CreateTwoDimensionalResponse response = new CreateTwoDimensionalResponse();
		String filePath = "";
		String PC_URL = proputil.getProperty("pc_url");//pc邀請連接路徑錢半段
		String Me_URL = proputil.getProperty("me_url");//pc邀請連接後半段
		try {
			FastdfsClient fastdfsClient = FastdfsClientFactory.getFastdfsClient();
			Map<String,String> user = BaseUtil.getUser(request.getTokenid());
			
			String custId = user.get("custid");
			
			CustomerInfoDto customerInfoDto = mangQueryMyReferService.queryCustomerInfoById(custId);	
			String invite_code = customerInfoDto.getTemp1();//獲取該客戶邀請碼
			if(customerInfoDto.getQcodeUrl() == null){
				int width = 160;
				int height = 160;
				String codeFormat = "png";
				Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType, Object>();
				hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
				hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
			        // 二維碼邊界空白大小 1,2,3,4 (4爲默認,最大)
			    hints.put(EncodeHintType.MARGIN, 1);
				BitMatrix bitMatrix = new MultiFormatWriter().encode(Me_URL+"?num="+invite_code, BarcodeFormat.QR_CODE, width, height, hints);
				BufferedImage image = toBufferedImage(bitMatrix);//new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				
				File logoFile = new File(webappDir+LOGO_URL+LOGO_NAME);
				image = addLogoToQrCode(image, logoFile);
				File tempDir = new File(webappDir+LOGO_TEMP_URL);
				if (!tempDir.exists()) {
					tempDir.mkdirs();
				}
				File file = new File(webappDir+LOGO_TEMP_URL+custId+"."+codeFormat);
				ImageIO.write(image, codeFormat, file);
				//MatrixToImageWriter.writeToFile(bitMatrix, codeFormat, file);
				filePath = file.getAbsolutePath();
				String fileId = fastdfsClient.upload(new File(filePath)); //上傳
				file.delete();
				customerInfoDto.setQcodeUrl(fileId);
				mangQueryMyReferService.updateCustomerInfo(customerInfoDto);
				response.setUrl(Me_URL+"?num="+invite_code);
				response.setUrl_png(fileId);
			}else{
				response.setUrl(Me_URL+"?num="+invite_code);
				response.setUrl_png(customerInfoDto.getQcodeUrl());
			}
			
			response.setTokenid(request.getTokenid());
			response.setVersion(request.getVersion());
			response.setMsg("success");
			response.setCode(ValidatorConstants.SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			response.setTokenid(request.getTokenid());
			response.setVersion(request.getVersion());
			response.setCode(ValidatorConstants.SYS_ERROR_CODE);
			response.setMsg("error");
			logger.error(e.getMessage(),e);
		}
		
		
		
		
		return response;
		
	}
	
	@SuppressWarnings("unused")
	private BufferedImage addLogoToQrCode(BufferedImage qrImg, File qrLogoFile) {
        if (qrLogoFile == null || !qrLogoFile.exists() || !qrLogoFile.isFile()) {
            return qrImg;
        }
        try {
            Graphics2D g = qrImg.createGraphics();
            BufferedImage logoImg = ImageIO.read(qrLogoFile);
            int qrWidth = qrImg.getWidth();
            int qrHeight = qrImg.getHeight();
            int logoWidth = (int) (qrWidth * logoRatio);
            int logoHeight = (int) (qrHeight * logoRatio);
            int x = (qrWidth - logoWidth) / 2;
            int y = (qrHeight - logoHeight) / 2;
            g.drawImage(logoImg, x, y, logoWidth, logoHeight, null);
            g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
            // logo邊框大小
            g.setStroke(new BasicStroke(1));
            g.setColor(logoBoundColor);
            g.drawRect(x, y, logoWidth, logoHeight);
            g.dispose();
            logoImg.flush();
            qrImg.flush();
        } catch (Exception e) {
        	logger.error(String.format("add logo %s to qr image error", qrLogoFile.getAbsolutePath()), e);
        }
        return qrImg;
    }
	
	private BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        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, matrix.get(x, y) ? foreground : background);
            }
        }
        return image;
    }
}

//請求參數
import java.io.Serializable;

import com.minxin.me.backstage.platform.sms.BaseApi;


public class CreateTwoDimensionalRequest extends BaseApi implements Serializable{

	private static final long serialVersionUID = -3802851575686062881L;

}

//響應參數
import java.io.Serializable;

import com.minxin.me.backstage.platform.sms.BaseApi;




public class CreateTwoDimensionalResponse extends BaseApi implements Serializable{

	private static final long serialVersionUID = 4943643764029800328L;

	private String url;
	private String url_png;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl_png() {
		return url_png;
	}

	public void setUrl_png(String url_png) {
		this.url_png = url_png;
	}
	
	
}
相關文章
相關標籤/搜索