java 生成二維碼

一步一步用?java?設計生成二維碼

?

轉至?http://blog.sina.com.cn/s/blog_5a6efa330102v1lb.html

在物聯網的時代,二維碼是個很重要的東西了,現在無論什么東西都要搞個二維碼標志,唯恐落伍,就差人沒有用二維碼識別了。也許有一天生分證或者戶口本都會用二維碼識別了。今天心血來潮,看見別人都為自己的博客添加了二維碼,我也想搞一個測試一下.

?

主要用來實現兩點:

1.?生成任意文字的二維碼.

2.?在二維碼的中間加入圖像.

3.

下載QR二維碼包。

首先得下載?zxing.jar?包,?我這里用的是3.0?版本的core包

下載地址:?現在已經遷移到了github:?https://github.com/zxing/zxing/wiki/Getting-Started-Developing,

當然你也可以從maven倉庫下載jar?包:?http://central.maven.org/maven2/com/google/zxing/core/

package qrcodesoft;import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;import com.google.zxing.LuminanceSource;public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left,int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white
                }}}this.image = new BufferedImage(sourceWidth, sourceHeight,BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}public byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left,this.top + top, width, height);}public boolean isRotateSupported() {return true;}public LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0,0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight,sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top,sourceWidth - (left + width), getHeight(), width);}
}
package qrcodesoft;import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// 二維碼尺寸private static final int QRCODE_SIZE = 300;// LOGO寬度private static final int WIDTH = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath,boolean needCompress) throws Exception {Hashtable hints = new Hashtable();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);int width = bitMatrix.getWidth();int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000: 0xFFFFFFFF);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入圖片QRCodeUtil.insertImage(image, imgPath, needCompress);return image;}private static void insertImage(BufferedImage source, String imgPath,boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println(""+imgPath+"   該文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 壓縮LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}Image image = src.getScaledInstance(width, height,Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 繪制縮小后的圖g.dispose();src = image;}// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}public static void encode(String content, String imgPath, String destPath,boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath,needCompress);mkdirs(destPath);String file = new Random().nextInt(99999999)+".jpg";ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));}public static void mkdirs(String destPath) {File file =new File(destPath);   //當文件夾不存在時,mkdirs會自動創建多層目錄,區別于mkdir.(mkdir如果父目錄不存在則會拋出異常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath)throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}public static void encode(String content, String destPath,boolean needCompress) throws Exception {QRCodeUtil.encode(content, null, destPath, needCompress);}public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}public static void encode(String content, String imgPath,OutputStream output, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath,needCompress);ImageIO.write(image, FORMAT_NAME, output);}public static void encode(String content, OutputStream output)throws Exception {QRCodeUtil.encode(content, null, output, false);}public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}public static void main(String[] args) throws Exception {String text = "http://www.dans88.com.cn";QRCodeUtil.encode(text, "d:/MyWorkDoc/my180.jpg", "d:/MyWorkDoc", true);}}

  

?

轉載于:https://www.cnblogs.com/yujianhuang/p/6900042.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392670.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392670.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392670.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 922. 按奇偶排序數組 II(雙指針)

給定一個非負整數數組 A&#xff0c; A 中一半整數是奇數&#xff0c;一半整數是偶數。 對數組進行排序&#xff0c;以便當 A[i] 為奇數時&#xff0c;i 也是奇數&#xff1b;當 A[i] 為偶數時&#xff0c; i 也是偶數。 你可以返回任何滿足上述條件的數組作為答案。 示例&a…

機器學習 深度學習 ai_如何突破AI炒作成為機器學習工程師

機器學習 深度學習 aiI’m sure you’ve heard of the incredible artificial intelligence applications out there — from programs that can beat the world’s best Go players to self-driving cars.我敢肯定&#xff0c;您已經聽說過令人難以置信的人工智能應用程序-從可…

arcgis插值不覆蓋區劃圖_ArcGIS繪圖—空氣質量站點數據插值繪制等值線圖

作者&#xff1a;吳琳&#xff1b;陳天舒&#xff0c;山東大學環境科學&#xff08;大氣化學&#xff09;博士在讀數據&#xff08;Excel格式&#xff09;&#xff1a;多站點污染物數據&#xff08;國&#xff0c;省&#xff0c;市控點&#xff09;&#xff0c;站點經緯度信息繪…

數字校驗

1 function validNumber(fieldname,fielddesc){2 var value $.trim($("#key_"fieldname).val());3 var num /^([0-9.])$/;4 5 var flag num.test(value);6 if(!flag) {7 alert("【"fielddesc"】只能輸入數字");8 …

JavaScript覆蓋率統計實現

主要需求 1、 支持browser & nodejs 由于javascript既能夠在瀏覽器環境執行&#xff0c;也能夠在nodejs環境執行&#xff0c;因此須要能夠統計兩種環境下單元測試的覆蓋率情況。 2、 透明、無縫 用戶寫單元測試用例的時候&#xff0c;不須要為了支持覆蓋率統計多寫代碼&…

leetcode 328. 奇偶鏈表(雙指針)

給定一個單鏈表&#xff0c;把所有的奇數節點和偶數節點分別排在一起。請注意&#xff0c;這里的奇數節點和偶數節點指的是節點編號的奇偶性&#xff0c;而不是節點的值的奇偶性。 請嘗試使用原地算法完成。你的算法的空間復雜度應為 O(1)&#xff0c;時間復雜度應為 O(nodes)…

NSLog打印當前文件,當前函數,當前行數

NSLog(”%s, %s, %d”, __FILE__, __FUNCTION__, __LINE__); 轉載于:https://www.cnblogs.com/shenfei2031/archive/2011/08/06/2129636.html

單元格內容分列多行_姓名太多,放在一列打印時浪費紙張,可以分成多行多列打印...

在日常工作中&#xff0c;往往會碰到這種情況(如下圖)&#xff1a;只有一列數據&#xff0c;而且比較多&#xff0c;如果打印起來就浪費紙張&#xff0c;然后復制、粘貼把表格變成幾列&#xff0c;方便打印。今天小編和大家分享不用復制、粘貼&#xff0c;就能快速完成一列分成…

caesar加密_如何編寫Caesar密碼:基本加密簡介

caesar加密by Brendan Massey由布倫丹梅西(Brendan Massey) The Caesar Cipher is a famous implementation of early day encryption. It would take a sentence and reorganize it based on a key that is enacted upon the alphabet. Take, for example, a key of 3 and th…

Java中接口、抽象類與內部類學習

2019獨角獸企業重金招聘Python工程師標準>>> Java中接口、抽象類與內部類學習 接口與內部類為我們提供了一種將接口與實現分離的更加結構化的方法。 抽象類和抽象方法 抽象方法&#xff1a;僅有聲明而沒有方法體。 抽象類&#xff1a;包含一個或多個抽象方法的類&am…

leetcode 402. 移掉K位數字(貪心算法)

給定一個以字符串表示的非負整數 num&#xff0c;移除這個數中的 k 位數字&#xff0c;使得剩下的數字最小。 注意: num 的長度小于 10002 且 ≥ k。 num 不會包含任何前導零。 示例 1 : 輸入: num “1432219”, k 3 輸出: “1219” 解釋: 移除掉三個數字 4, 3, 和 2 形成…

javascript 自定義Map

遷移時間&#xff1a;2017年5月25日08:24:19 Author:Marydon 三、自定義Map數據格式 需特別注意的是&#xff1a; js中沒有像java中的Map數據格式&#xff0c;js自帶的map()方法用于&#xff1a;返回一個由原數組中的每個元素調用一個指定方法后的返回值組成的新數組。 map()使…

gif分解合成_如何通過分解和合成使復雜的問題更容易

gif分解合成Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“發現功能JavaScript”被BookAuthority評為最佳新功能編程書籍之一 &#xff01; Our natural way of dealing with complexity is to break it in…

vs2005 新建項目一片空白

最近在研究 workflow fundation ,但是在安裝了他的extensions之后&#xff0c;發現VS2005 新建項目一片空白&#xff0c;除開workflow其他的項目模板全部丟失&#xff0c;新建項目對話框中空空如也。查閱資料后發現&#xff0c;可以通過 命令 devenv.exe /InstallVSTemplates 來…

docker導入鏡像 liunx_docker掃盲?面試連這都不會就等著掛吧

推薦閱讀&#xff1a;java喵&#xff1a;6大面試技能樹&#xff1a;JAVA基礎JVM算法數據庫計算機網絡操作系統?zhuanlan.zhihu.com一只Tom貓&#xff1a;都是“Redis惹的禍”&#xff0c;害我差點掛在美團三面&#xff0c;真是“虛驚一場”&#xff01;?zhuanlan.zhihu.com現…

crontab里shell腳本將top信息寫入文件

crontab里shell腳本將top信息寫入文件&#xff1a; 注&#xff1a; 1、top -n 1代表執行1次退出&#xff08;默認top是不退出的&#xff09;,-d 1代表每1秒執行1次 2、crontab里需加/bin/bash # crontab -e */5 * * * * /bin/bash /usr/local/bin/top.sh # vi top.sh #!/bin/ba…

leetcode 1030. 距離順序排列矩陣單元格(bfs)

給出 R 行 C 列的矩陣&#xff0c;其中的單元格的整數坐標為 (r, c)&#xff0c;滿足 0 < r < R 且 0 < c < C。 另外&#xff0c;我們在該矩陣中給出了一個坐標為 (r0, c0) 的單元格。 返回矩陣中的所有單元格的坐標&#xff0c;并按到 (r0, c0) 的距離從最小到…

Linux iptables:規則原理和基礎

什么是iptables&#xff1f; iptables是Linux下功能強大的應用層防火墻工具&#xff0c;但了解其規則原理和基礎后&#xff0c;配置起來也非常簡單。 什么是Netfilter&#xff1f; 說到iptables必然提到Netfilter&#xff0c;iptables是應用層的&#xff0c;其實質是一個定義規…

太陽系八大行星碰撞的視頻_火星的身世:從太陽系的起源說起

大約46億年前盤狀的太陽星云從一大片又冷又暗的氣體云中誕生太陽自己并沒有任何暴露確切年齡的線索&#xff0c;我們之所以能夠知道太陽系的“生日”&#xff0c;是因為迄今從隕石中找到的最古老固體物質&#xff0c;年齡約為45.68億年。一般認為&#xff0c;太陽系的各個地方是…

refract推導_我們如何利用Refract來利用React式編程的力量

refract推導by Joe McGrath通過喬麥克格拉斯 我們如何利用Refract來利用React式編程的力量 (How we harnessed the power of reactive programming with Refract) Have you ever wondered how open-source libraries built by companies come into existence?您是否想過公司建…