二维码及验证码的生成
生活随笔
收集整理的這篇文章主要介紹了
二维码及验证码的生成
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
二維碼生成:
public static void main(String[] args) {String message = "http://doc.canglaoshi.org";try {//參數1:二維碼上包含的文本信息 參數2:圖片生成的位置 // QRCodeUtil.encode(message,"./qr.jpg");//參數1:二維碼上包含的文本信息 參數2:圖片生成后會通過該流寫出 // QRCodeUtil.encode(message,new FileOutputStream("./qr.jpg"));//參數1:二維碼上包含的文本信息 參數2:二維碼中間的logo圖片 參數3:圖片生成的位置 參數4:是否需要壓縮logo圖片到中間大小 // QRCodeUtil.encode(message,"logo.jpg","./qr.jpg",true);QRCodeUtil.encode(message,"logo.jpg",new FileOutputStream("./qr.jpg"),true);System.out.println("二維碼生成完畢!");} catch (Exception e) {e.printStackTrace();} }驗證碼的生成:
public static void main(String[] args) {//驗證碼測試//1創建一張空圖片,并且指定寬高。 理解為:創建一張畫紙BufferedImage image = new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);//2根據圖片獲取一個畫筆,通過該畫筆畫的內容都會畫到該圖片上Graphics g = image.getGraphics();//3確定驗證碼內容(字母與數字的組合)String line = "abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";Random random = new Random();//用于生成隨機數(隨機數位line的字符下標)//為圖片背景填充一個隨機顏色//創建Color時,需要指定三個參數,分別是,紅,綠,藍。數字范圍都是(0-255)之間Color bgcolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));//將畫筆設置為該顏色g.setColor(bgcolor);//填充整張圖片為畫筆當前顏色g.fillRect(0,0,70,30);//向圖片上畫4個字符for(int i=0;i<4;i++) {//隨機生成一個字符String str = line.charAt(random.nextInt(line.length())) + "";//生成隨機顏色Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));//設置畫筆顏色g.setColor(color);//設置字體g.setFont(new Font(null, Font.BOLD, 20));//將字符串畫到圖片指定的位置上g.drawString(str, i*15+5, 18+ random.nextInt(11)-5);}//隨機生成4條干擾線for (int i=0;i<4;i++){Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));g.setColor(color);g.drawLine(random.nextInt(71), random.nextInt(31),random.nextInt(71), random.nextInt(31));}//將圖片寫入文件來生成該圖片文件try {ImageIO.write(image,"jpg",new FileOutputStream("./random.jpg"));} catch (IOException e) {e.printStackTrace();}} }總結
以上是生活随笔為你收集整理的二维码及验证码的生成的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是事务的一致性?一致性和原子性的区别
- 下一篇: 无缝漫游11k,11r, 11v