生成二维码-生成内嵌二维码的海报

//生成内嵌二维码的海报
                        String imgType = "png";
//                        String backImageUrl = posterPd.get("product_poster").toString();
                        String backImageUrl = Const.POSTER_BACKIMG;//背景图的地址
                        String url = PathUtil.PathAddress() + "front/product_detail?classify_alias=" + productClassify
                                + "&platform_type=mobile&page_type=detail&product_no=" + productNo + "&share_code=" + shareCode;//二维码地址
                        String shortUrl = TwoDimensionCode.shortUrl(url);//缩短二维码地址
                        String encoderQRCodeInPic = encoderQRCodeInPic(shortUrl, imgType, backImageUrl);//合成
                        if (null != encoderQRCodeInPic && "" != encoderQRCodeInPic){
                            resultCode = Const.ERRORCOREZERO;
                            map.put("qrcode_poster",encoderQRCodeInPic);
                        }else {
                            resultCode = Const.ERRORCOREONE;
                            map.put("error_info","图片生成失败");
                        }

缩短二维码url:

/**
	 * 缩短url 以减少生成二维码的密度
	 * @param url
	 * @return
	 */
	public static String shortUrl(String url){
		String username = Const.SHORT_URL_USERNAME;
		String password = Const.SHORT_URL_PASSWORD;
		String action = Const.SHORT_URL_ACTION;
		String format = Const.SHORT_URL_FORMAT;

		List<NameValuePair> postParams = new ArrayList<>();
		postParams.add(new BasicNameValuePair("url", url));
		postParams.add(new BasicNameValuePair("username", username));
		postParams.add(new BasicNameValuePair("password", password));
		postParams.add(new BasicNameValuePair("action", action));
		postParams.add(new BasicNameValuePair("format", format));

		String responseJson = HttpUtil.httpPostMethod(Const.SHORT_URL, new HashMap<String, String>(), postParams, "utf-8", false);
		JSONObject json = JSONObject.fromObject(responseJson);
		url = (String) json.get("shorturl");
		return url;
	}
/**
     * 通过post方法采集指定网页,如果采集成功返回采集结果 否则返回null
     * @param url 发送post请求的网页url
     * @param postParams post参数数组
     * @param charset 网页字符集
     * @param jsEnabled 是否支持js解析
     * @return 如果采集成功返回网页内容字符串,否则返回null
     */
    public static String httpPostMethod(String url, Map<String, String> headerMap, List<NameValuePair> postParams, String charset, boolean jsEnabled){
        try {
            Thread.sleep(GATHER_SLEEP * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        logger.info("正在HTTP POST 请求 URL: " + url);
        HttpClient httpClient = new DefaultHttpClient();
        String retString = null;
        HttpPost post = new HttpPost(url);
        HttpResponse response = null;
        //set header
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            post.setHeader(key, value);
        }

        try {
            post.setEntity(new UrlEncodedFormEntity(postParams,"utf-8"));
            response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                logger.error("http entity null");
                return null;
            }
            Header encodingHeader = entity.getContentEncoding();
            if (encodingHeader != null) {
                HeaderElement[] codecsElements = encodingHeader.getElements();
                for (int i = 0; i < codecsElements.length; i++) {
                    if (codecsElements[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response
                                .getEntity()));
                    }
                }
            }// end if

            retString = EntityUtils.toString(entity, "utf-8");

        } catch (UnsupportedEncodingException e) {
            logger.error(e);
            return null;
        } catch (ClientProtocolException e) {
            logger.error(e);
            return null;
        } catch (IOException e) {
            logger.error(e);
            return null;
        }
        return retString;
    }

合成图片

/**
     * 生成海报内嵌二维码图片
     *
     * @param content
     *            存储内容
     *            图片路径
     * @param imgType
     *            图片类型
     */
    public static String encoderQRCodeInPic(String content, String imgType,String backImageUrl) {
        return encoderQRCodeInPic(content,  imgType, picSize,backImageUrl);
    }
 /**
     * 生成海报内嵌二维码图片
     *
     * @param content
     *            存储内容
     * @param imgType
     *            图片类型
     * @param size
     *            二维码尺寸
     */
    public static String encoderQRCodeInPic(String content, String imgType,
                                       int size, String backImageUrl) {

        String gluePicAddr = null;
        try {

            BufferedImage bufImg = qRCodeCommon(content, imgType, size);
//            BufferedImage bufImgNew = new BufferedImage(330,330,bufImg.getType());
            BufferedImage bufImgNew = resizeBufferedImage(bufImg,330,330,true);

            //合成海报
            gluePicAddr = createPicTwo(249, 873, bufImgNew,backImageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return gluePicAddr;
        }
    }

第一步 生成二维码

/**
	 * 生成二维码(QRCode)图片的公共方法
	 * 
	 * @param content
	 *            存储内容
	 * @param imgType
	 *            图片类型
	 * @param size
	 *            二维码尺寸
	 * @return
	 */
	public static BufferedImage qRCodeCommon(String content, String imgType, int size) {
		BufferedImage bufImg = null;

		try {



			Qrcode qrcodeHandler = new Qrcode();
			// 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
			qrcodeHandler.setQrcodeErrorCorrect('L');
			qrcodeHandler.setQrcodeEncodeMode('B');
			// 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大
			qrcodeHandler.setQrcodeVersion(versionVar); //versionVar = 6
//			if(size < 8){
//				qrcodeHandler.setQrcodeVersion(versionVar);
//			}else{
//				qrcodeHandler.setQrcodeVersion(18);
//			}

			// 获得内容的字节数组,设置编码格式
			byte[] contentBytes = content.getBytes("utf-8");
			// 图片尺寸
			//int imgSize = 67 + 12 * (size - 1);
			int imgSize = 67 + 12 * (size - 1);
			
			//System.out.println(imgSize);
			
			bufImg = new BufferedImage(imgSize+15, imgSize+15,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = bufImg.createGraphics();
			// 设置背景颜色
			gs.setBackground(Color.WHITE);
			gs.clearRect(0, 0, imgSize+15, imgSize+15);

			// 设定图像颜色> BLACK
			gs.setColor(Color.BLACK);
			// 设置偏移量,不设置可能导致解析出错
			int pixoff = 10;
			int pixoffSize = 1;
			if (contentBytes.length > 0 && contentBytes.length < 800) {

				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(new Double(Math.floor(j * 3 * rate )).intValue() + pixoff, new Double(Math.floor(i * 3 * rate)).intValue() + pixoff, new Double(Math.floor(3 * rate)).intValue()+ pixoffSize, new Double(Math.floor(3 * rate)).intValue()+ pixoffSize);
						}
					}
				}
			} else {
				throw new Exception("QRCode content bytes length = "
						+ contentBytes.length + " not in [0, 800].");
			}
			gs.dispose();
			bufImg.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bufImg;
	}

第二步,根据实际需要调整二维码大小,具体调整方式参见resizeBufferedImage方法。在另一片博文有写

第三步,将二维码和背景图合成一张图

/**
	 * 图二的位置 从左上角开始
	 * @param x
	 * @param y
	 */
	public static String createPicTwo(int x, int y, BufferedImage qrCodeBuf,String backImageUrl) {

		String gluePicAdsoluteAddr = null;
		String gluePicRelativeAddr = null;

		try
		{
			System.out.print("backImageUrl="+backImageUrl);
			//读取第一张图片
			File fileOne = new File(PathUtil.getProjectResources() + backImageUrl);
			BufferedImage ImageOne = ImageIO.read(fileOne);
			int width = ImageOne.getWidth();//图片宽度
			int height = ImageOne.getHeight();//图片高度

			//从图片中读取RGB
			int[] ImageArrayOne = new int[width * height];
			ImageArrayOne = ImageOne.getRGB(0, 0, width, height, ImageArrayOne, 0, width);

			//对第二张图片做相同的处理
			BufferedImage ImageTwo = qrCodeBuf;
			int widthTwo = ImageTwo.getWidth();//图片宽度
			int heightTwo = ImageTwo.getHeight();//图片高度
			int[] ImageArrayTwo = new int[widthTwo * heightTwo];
			ImageArrayTwo = ImageTwo.getRGB(0, 0, widthTwo, heightTwo, ImageArrayTwo, 0, widthTwo);

			x = width/2-widthTwo/2;
//			y = (int)((height - heightTwo)*0.95);
			y = (int)((height - heightTwo)*0.75);
			//生成新图片
			BufferedImage ImageNew = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			ImageNew.setRGB(0, 0, width, height, ImageArrayOne, 0, width);//设置左半部分的RGB
			ImageNew.setRGB(x, y, widthTwo, heightTwo, ImageArrayTwo, 0, widthTwo);//设置右半部分的RGB

			Graphics g = ImageNew.getGraphics();
			Font font = new Font("黑体",Font.PLAIN,20);

			g.setFont(font);
			g.setColor(new Color(255, 0, 0));
			g.drawString("", 180, y+20);

			gluePicAdsoluteAddr = PathUtil.getProjectResources() + Const.FILEPATHPOSTERIMG + new Date().getTime() + ".jpg";
			gluePicRelativeAddr = Const.FILEPATHPOSTERIMG + new Date().getTime() + ".jpg";

			File outFile = new File(gluePicAdsoluteAddr);
			ImageIO.write(ImageNew, "jpg", outFile);//写图片

//			outFile.flush();
//			outFile.close();

		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			return  gluePicRelativeAddr;
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值