1. 程式人生 > >java微信小程式引數二維碼生成帶背景圖加字型

java微信小程式引數二維碼生成帶背景圖加字型


需求 : 
1,因為專案需求 ,生成數以萬計的二維碼   

   2 ,每個二維碼帶不同的引數

   3,二維碼有固定背景圖 
   4 , 往生成圖片上寫入 字型和編號(動態 )

設計技術 :

 1,微信介面token ,nginx 快取

  2,二維碼 圖片定義 寫字

maven


com.twelvemonkeys.imageio 
imageio-jpeg 
3.0-rc5 

還有rt.jar 在你java安裝檔案的bin裡面

獲取token資訊

publicvoidGetUrl() throws ClientProtocolException,
    IOException {
        HttpGet httpGet = new
HttpGet( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Configure.getAppID() + "&secret=" + Configure.getSecret() ); HttpClient httpClient = HttpClients.createDefault(); HttpResponse res = httpClient.execute(httpGet); HttpEntity entity = res.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"
); JSONObject jsons = JSONObject.fromObject(result); String expires_in = jsons.getString("expires_in"); //快取 if(Integer.parseInt(expires_in)==7200){ //ok String access_token = jsons.getString("access_token"); Jedis cache = new Jedis("127.0.0.1"
, 6379); System.out.println("access_token:"+access_token); Pipeline pipeline = cache.pipelined(); pipeline.set("access_token", access_token); pipeline.expire("access_token", 7200); pipeline.sync(); }else{ System.out.println("出錯獲取token失敗!"); } }

  獲取二維碼 資訊圖片

    public String GetPostUrl(String access_token,String id) throws Exception {
          //String result = HttpRequest.sendPost("http://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token, path);
        System.out.println(id);
        String url ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("path", "pages/index/index?###="+id);//你二維碼中跳向的地址
         map.put("width", "430");//圖片大小
         JSONObject json = JSONObject.fromObject(map);
         System.out.println(json);
        String  res= HttpClientConnectionManager.httpPostWithJSON(url
                     + access_token, json.toString(),id);
         System.out.println(res);
        return null;
    }

返回圖片儲存 ,根據 id

public static String httpPostWithJSON(String url, String json,String id)
                throws Exception {
            String result = null;
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

            StringEntity se = new StringEntity(json);
            se.setContentType("application/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                            "UTF-8"));
            httpPost.setEntity(se);
            // httpClient.execute(httpPost);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                        InputStream instreams = resEntity.getContent(); 
                        String uploadSysUrl = "D://erweima/";
                        File saveFile = new File(uploadSysUrl+id+".png");
                           // 判斷這個檔案(saveFile)是否存在
                           if (!saveFile.getParentFile().exists()) {
                               // 如果不存在就建立這個資料夾
                               saveFile.getParentFile().mkdirs();
                           }
                    saveToImgByInputStream(instreams, uploadSysUrl, id+".png");
                }
            }
            httpPost.abort();
            return result;
        } 

        /* @param instreams 二進位制流
    * @param imgPath 圖片的儲存路徑
    * @param imgName 圖片的名稱
    * @return
    *      1:儲存正常
    *      0:儲存失敗
    */
   public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){

       int stateInt = 1;
       if(instreams != null){
           try {
               File file=new File(imgPath+imgName);//可以是任何圖片格式.jpg,.png等
               FileOutputStream fos=new FileOutputStream(file);

               byte[] b = new byte[1024];
               int nRead = 0;
               while ((nRead = instreams.read(b)) != -1) {
                   fos.write(b, 0, nRead);
               }
               fos.flush();
               fos.close();                
           } catch (Exception e) {
               stateInt = 0;
               e.printStackTrace();
           } finally {
               try {
                instreams.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           }
       }
       return stateInt;
   }

然後是圖片重合和增加字型

public void changeImage(String imageurl,String i ){
        try { 
//            InputStream imagein = new FileInputStream(
//                    "D:/systemAvatarNew1.png");
//            InputStream imagein2 = new FileInputStream(
//                    "D:/qqfile/1852230493/FileRecv/4-02.png");
            InputStream imagein = new FileInputStream(
                    "D:/systemAvatarNew1.png");
            InputStream imagein2 = new FileInputStream(
                    imageurl);

            BufferedImage image = ImageIO.read(imagein);
            BufferedImage image2 = ImageIO.read(imagein2); 
            //image2.getWidth() - 160, image2.getHeight() - 155,
            Graphics g = image.getGraphics();
            g.drawImage(image2, 300, 230, 410,422,null);
//            g.drawImage(image2, image.getWidth() - image2.getWidth() - 195,
//                    image.getHeight() - image2.getHeight() - 190,
//                     340,349,null);
            OutputStream outImage = new FileOutputStream(
                    imageurl);
            JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(outImage);
            enc.encode(image);


            BufferedImage bimg=ImageIO.read(new FileInputStream(imageurl));  
            //得到Graphics2D 物件  
            Graphics2D g2d=(Graphics2D)bimg.getGraphics();  
            //設定顏色和畫筆粗細  
            g2d.setColor(Color.black);  
            g2d.setStroke(new BasicStroke(5));  
            //String pathString = "D://qqfile/1852230493/FileRecv/SourceHanSansCN-/SourceHanSansCN-Heavy.otf";
//            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, new File(pathString));

            g2d.setFont(new Font("微軟雅黑", Font.PLAIN, 36));  
            //g2d.setFont(Loadfont.loadFont(pathString, 45));  
            //繪製圖案或文字  
            g2d.drawString("編號: "+i, 320, 700);  
          //  g2d.drawString(i, 450, 700);    

            ImageIO.write(bimg, "JPG",new FileOutputStream(imageurl));


            File fromFile = new File(imageurl);  
            File toFile = new File(imageurl);  
            Image1 Image1 =new Image1();
            Image1.resizePng(fromFile, toFile, 1000, 1000, false);



            imagein.close();
            imagein2.close();
            outImage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

接下來再 main方法裡面跑一下 就ok ,如果是需要返回前臺資訊的,就直接記錄地址,前臺顯示就可以了