java二維碼識別
『壹』 qrcode生成的二維碼怎麼用java讀取
看看這里的講解。有現成的用qrcode生成二維碼和解析二維碼:
http://www.sojson.com/tag_erweima.html
二維碼線上Demo:
http://www.sojson.com/qr.html
『貳』 如何使攝像頭掃描二維碼,然後解析二維碼 java源碼 zxing
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
public final class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {}
public static 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) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
}
『叄』 Java設置二維碼只能用攝像頭掃,不能拍照後再掃描
這怎麼能識別出來是拍的照片,其實生成的二維碼本身就是圖片呀,這和根據手機殼顏色換主題有異曲同工之妙哦!
不過辦法還是有的,就是需要生成端和掃碼端做修改了,二維碼動態生成(定時刷新),生成的二維碼設置過期時間(也就是二維碼信息中帶時間戳),這樣不同時間生成的二維碼是不一樣的,掃描後再進行校驗是否過期就可以了。
『肆』 誰有java二維碼掃描軟體
我沒太懂你的意思,你是要java寫的掃描軟體的話,網上有很多啊,微信也可以掃描啊,我這里有一個用java寫的生成二維碼和解析二維碼的工程,研究二維碼代碼的話可以去google的開源項目zxing看一下,希望對你有幫助。
『伍』 如何識別圖片是否是二維碼java中js或jq中
js 有專門用來識別QR 碼的庫 webQrDecodeClass.js 可以引用
『陸』 請問java如何實現二維碼一碼多識
會場的二維碼應該要包含會場id
然後會員掃描二維碼,獲得會場的id,此時會員必須登錄,登錄會員就能獲得會員id,
然後根據會員id和會場id去跟伺服器查詢作為信息
『柒』 求一個用Java編的二維碼生成識別的demo,希望內容完整點,萬分感謝
在java工程裡面導入QRCode.JAR包
importjava.awt.Color;
importjava.awt.Graphics2D;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjavax.imageio.ImageIO;
importjp.sourceforge.qrcode.QRCodeDecoder;
importjp.sourceforge.qrcode.exception.DecodingFailedException;
importcom.swetake.util.Qrcode;
publicclassTwoDimensionCode{
/**
*生成二維碼(QRCode)圖片
*
*@paramcontent
*存儲內容
*@paramimgPath
*圖片路徑
*/
publicvoidencoderQRCode(Stringcontent,StringimgPath){
this.encoderQRCode(content,imgPath,"png",7);
}
/**
*生成二維碼(QRCode)圖片
*
*@paramcontent
*存儲內容
*@paramoutput
*輸出流
*/
publicvoidencoderQRCode(Stringcontent,OutputStreamoutput){
this.encoderQRCode(content,output,"png",7);
}
/**
*生成二維碼(QRCode)圖片
*
*@paramcontent
*存儲內容
*@paramimgPath
*圖片路徑
*@paramimgType
*圖片類型
*/
publicvoidencoderQRCode(Stringcontent,StringimgPath,StringimgType){
this.encoderQRCode(content,imgPath,imgType,7);
}
/**
*生成二維碼(QRCode)圖片
*
*@paramcontent
*存儲內容
*@paramoutput
*輸出流
*@paramimgType
*圖片類型
*/
publicvoidencoderQRCode(Stringcontent,OutputStreamoutput,
StringimgType){
this.encoderQRCode(content,output,imgType,7);
}
/**
*生成二維碼(QRCode)圖片
*
*@paramcontent
*存儲內容
*@paramimgPath
*圖片路徑
*@paramimgType
*圖片類型
*@paramsize
*二維碼尺寸
*/
publicvoidencoderQRCode(Stringcontent,StringimgPath,StringimgType,
intsize){
try{
BufferedImagebufImg=this.qRCodeCommon(content,imgType,size);
FileimgFile=newFile(imgPath);
//生成二維碼QRCode圖片
ImageIO.write(bufImg,imgType,imgFile);
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*生成二維碼(QRCode)圖片
*
*@paramcontent
*存儲內容
*@paramoutput
*輸出流
*@paramimgType
*圖片類型
*@paramsize
*二維碼尺寸
*/
publicvoidencoderQRCode(Stringcontent,OutputStreamoutput,
StringimgType,intsize){
try{
BufferedImagebufImg=this.qRCodeCommon(content,imgType,size);
//生成二維碼QRCode圖片
ImageIO.write(bufImg,imgType,output);
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*生成二維碼(QRCode)圖片的公共方法
*
*@paramcontent
*存儲內容
*@paramimgType
*圖片類型
*@paramsize
*二維碼尺寸
*@return
*/
(Stringcontent,StringimgType,intsize){
BufferedImagebufImg=null;
try{
QrcodeqrcodeHandler=newQrcode();
//設置二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小
qrcodeHandler.setQrcodeErrorCorrect('M');
qrcodeHandler.setQrcodeEncodeMode('B');
//設置設置二維碼尺寸,取值范圍1-40,值越大尺寸越大,可存儲的信息越大
qrcodeHandler.setQrcodeVersion(size);
//獲得內容的位元組數組,設置編碼格式
byte[]contentBytes=content.getBytes("utf-8");
//圖片尺寸
intimgSize=67+12*(size-1);
bufImg=newBufferedImage(imgSize,imgSize,
BufferedImage.TYPE_INT_RGB);
Graphics2Dgs=bufImg.createGraphics();
//設置背景顏色
gs.setBackground(Color.WHITE);
gs.clearRect(0,0,imgSize,imgSize);
//設定圖像顏色>BLACK
gs.setColor(Color.BLACK);
//設置偏移量,不設置可能導致解析出錯
intpixoff=2;
//輸出內容>二維碼
if(contentBytes.length>0&&contentBytes.length<800){
boolean[][]codeOut=qrcodeHandler.calQrcode(contentBytes);
for(inti=0;i<codeOut.length;i++){
for(intj=0;j<codeOut.length;j++){
if(codeOut[j][i]){
gs.fillRect(j*3+pixoff,i*3+pixoff,3,3);
}
}
}
}else{
thrownewException("QRCodecontentbyteslength="
+contentBytes.length+"notin[0,800].");
}
gs.dispose();
bufImg.flush();
}catch(Exceptione){
e.printStackTrace();
}
returnbufImg;
}
/**
*解析二維碼(QRCode)
*@paramimgPath圖片路徑
*@return
*/
publicStringdecoderQRCode(StringimgPath){
//QRCode二維碼圖片的文件
FileimageFile=newFile(imgPath);
BufferedImagebufImg=null;
Stringcontent=null;
try{
bufImg=ImageIO.read(imageFile);
QRCodeDecoderdecoder=newQRCodeDecoder();
content=newString(decoder.decode(newTwoDimensionCodeImage(bufImg)),"utf-8");
}catch(IOExceptione){
System.out.println("Error:"+e.getMessage());
e.printStackTrace();
}catch(DecodingFailedExceptiondfe){
System.out.println("Error:"+dfe.getMessage());
dfe.printStackTrace();
}
returncontent;
}
/**
*解析二維碼(QRCode)
*@paraminput輸入流
*@return
*/
publicStringdecoderQRCode(InputStreaminput){
BufferedImagebufImg=null;
Stringcontent=null;
try{
bufImg=ImageIO.read(input);
QRCodeDecoderdecoder=newQRCodeDecoder();
content=newString(decoder.decode(newTwoDimensionCodeImage(bufImg)),"utf-8");
}catch(IOExceptione){
System.out.println("Error:"+e.getMessage());
e.printStackTrace();
}catch(DecodingFailedExceptiondfe){
System.out.println("Error:"+dfe.getMessage());
dfe.printStackTrace();
}
returncontent;
}
publicstaticvoidmain(String[]args){
StringimgPath="G:/TDDOWNLOAD/Michael_QRCode.png";
StringencoderContent="Hello大大、小小,welcometoQRCode!"+" Myblog[http://sjsky.iteye.com]"+" EMail[[email protected]]";
TwoDimensionCodehandler=newTwoDimensionCode();
handler.encoderQRCode(encoderContent,imgPath,"png");
//try{
//OutputStreamoutput=newFileOutputStream(imgPath);
//handler.encoderQRCode(content,output);
//}catch(Exceptione){
//e.printStackTrace();
//}
System.out.println("========encodersuccess");
StringdecoderContent=handler.decoderQRCode(imgPath);
System.out.println("解析結果如下:");
System.out.println(decoderContent);
System.out.println("========decodersuccess!!!");
}
}
第二個代碼:
importjava.awt.image.BufferedImage;
importjp.sourceforge.qrcode.data.QRCodeImage;
{
BufferedImagebufImg;
publicTwoDimensionCodeImage(BufferedImagebufImg){
this.bufImg=bufImg;
}
@Override
publicintgetHeight(){
returnbufImg.getHeight();
}
@Override
publicintgetPixel(intx,inty){
returnbufImg.getRGB(x,y);
}
@Override
publicintgetWidth(){
returnbufImg.getWidth();
}
}
『捌』 如何使用java實現二維碼掃描登錄微信網頁版(微信端)
jsp+spring+struts2+mybatis:
模仿微信網頁版掃碼登錄
使用js代碼生成qrcode二維碼減輕伺服器壓力
js循環請求服務端,判斷是否qrcode被掃
二維碼超時失效功能
二維碼被掃成功登錄,服務端產生sessionId,傳到頁面使用js保存cookie
多線程
- ### 生成qrcode相關js jquery.qrcode.js - ### 代碼 「
- function keepPool(){
- var uuid = $("#uuid").val();
- $.get(ctx+"/web/login/pool.do",{uuid:uuid,},function(msg){//如果放入一個不存在的網址怎麼辦?
- //console.log(msg);
- if(msg.successFlag == '1'){
- $("#result").html("掃碼成功");
- setCookie(msg.data.cname, msg.data.cvalue, 3*60*60*1000);
- //alert("將跳轉...");
- window.location.href = ctx +"/webstage/login/success.do";
- }else if(msg.successFlag == '0'){
- $("#result").html("該二維碼已經失效,請重新獲取");
- }else{
- keepPool();
- }
- });
- }
- //設置cookie
- function setCookie(cname, cvalue, expireTime) {
- var d = new Date();
- d.setTime(d.getTime() + expireTime);//設置過期時間
- var expires = "expires="+d.toUTCString();
- var path = "path=/"
- document.cookie = cname + "=" + cvalue + "; " + expires + "; " + path;
- }
- //二維碼首頁public String index() { try {
- uuid = UUID.randomUUID().toString(); super.getRequest().setAttribute("uuid", uuid);
- ScanPool pool = new ScanPool();
- pool.setCreateTime(System.currentTimeMillis());
- Map<String, ScanPool> map = new HashMap<String, ScanPool>(1);
- map.put(uuid, pool);
- PoolCache.cacheMap.put(uuid, pool);
- pool = null;
- } catch (Exception e) {
- Log4jUtil.CommonLog.error("pc生成二維碼登錄", e);
- } return "index";
- }//判斷二維碼是否被掃描public void pool() {
- DataResultInfo result = null;
- System.out.println("檢測[ " + uuid + " ]是否登錄");
- ScanPool pool = null;
- if(MapUtils.isNotEmpty(PoolCache.cacheMap)) pool = PoolCache.cacheMap.get(uuid); try { if (pool == null) { // 掃碼超時,進線程休眠
- result = DataResultInfo.getInstance().failure();
- result.setSuccessFlag(CommonConstant.Zero);
- result.setExtension(CommonConstant.Zero, "該二維碼已經失效,請重新獲取");
- Thread.sleep(10 * 1000L);
- } else { // 使用計時器,固定時間後不再等待掃描結果--防止頁面訪問超時
- new Thread(new ScanCounter(uuid, pool)).start(); boolean scanFlag = pool.getScanStatus(); //這里得到的ScanPool(時間靠前)和用戶使用手機掃碼後得到的不是一個,用戶掃碼後又重新更新了ScanPool對象,並重新放入了redis中,,所以這里要等待上面的計時器走完,才能獲得最新的ScanPool
- if (scanFlag) {
- result = DataResultInfo.getSuccess(); // 根據uuid從redis中獲取pool對象,得到對應的sessionId,返給頁面,通過js存cookie中
- JSONObject jsonObj = new JSONObject();
- jsonObj.put("cname", CookieConstant.SESSION_KEY);
- jsonObj.put("cvalue", pool.getSession());
- result.setData(jsonObj);
- } else {
- result = DataResultInfo.getInstance().failure();
- result.setMessage("等待掃描");
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- sendJsonMessage(result);
- }//手機掃碼介面(以id和token作為用戶身份登錄)
- public String phoneScanLogin() {
- DataResultInfo result = null;
- ScanPool pool = null;
- if(MapUtils.isNotEmpty(PoolCache.cacheMap)) pool = PoolCache.cacheMap.get(uuid); try { if (pool == null) {
- result = DataResultInfo.getInstance().failure();
- result.setMessage("該二維碼已經失效,請重新獲取");
- } else { if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(token)) { //根據id和token查詢後台,獲取用戶信息userBean
- String redisToken = redisUtil.getRedis(RedisKeyConstant.APP_TOKEN+userId); if(redisToken != null && redisToken.equals(token)){
- UserBean userBean = userService.findByUserId(Long.valueOf(userId)); if (userBean != null) {
- String sessionId = SessionConstant.SESSION_ID_PRE
- + FormatUtils.password(userBean.getId()
- .toString());
- Map<String, String> cookieSession = new HashMap<String, String>();
- cookieSession
- .put(CookieConstant.SESSION_KEY, sessionId); // WrCookie.writeCookie(getResponse(),cookieSession);
- // 添加用戶信息到redis
- boolean re = redisUtil.addUserInfo( RedisKeyConstant.SESSION + sessionId, BeanUtils.toBean(userBean, UserInfo.class));
- getSession().setAttribute( SessionConstant.USER_INFO_WEB, BeanUtils.toBean(userBean, UserInfo.class));
- getSession().setAttribute( DomainConstant.USER_CENTER_KEY, DomainConstant.USER_CENTER);
- pool.setSession(sessionId);
- pool.scanSuccess();
- }else{
- result = DataResultInfo.getInstance().failure();
- result.setMessage("用戶信息獲取異常!請稍後再試");
- }
- } else {
- result = DataResultInfo.getInstance().failure();
- result.setExtension("11", "用戶身份信息失效,請重新登錄!");
- }
- } else {
- result = DataResultInfo.getInstance().failure();
- result.setMessage("請求參數有誤!"); return "error";
- } // 不能清除,否則conn方法得不到pool對象,不會進入線程休眠
- // System.out.println("清除掃描過的uuid");
- //PoolCache.cacheMap.remove(uuid);
- }
- } catch (Exception e) {
- Log4jUtil.CommonLog.error("手機掃碼 後訪問 異常", e);
- }
- sendJsonMessage(result); return null;
- }//掃碼成功跳轉頁
- public String success() {
- String sessionId = WrCookie.getCookie(super.getRequest(), CookieConstant.SESSION_KEY);
- UserInfo userInfo = redisUtil.getUserInfo(RedisKeyConstant.SESSION + sessionId); super.getRequest().setAttribute(SessionConstant.USER_INFO_WEB, userInfo); return SUCCESS;
- }//線程判斷二維碼是否超時class ScanCounter implements Runnable { public Long timeout = 30 * 1000L; //超時時長
- // 傳入的對象
- private String uuid; private ScanPool scanPool; public ScanCounter(String p, ScanPool scanPool) {
- uuid = p; this.scanPool = scanPool;
- } @Override
- public void run() { try {
- Thread.sleep(timeout);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- notifyPool(uuid, scanPool);
- } public synchronized void notifyPool(String uuid, ScanPool scanPool) { if (scanPool != null) scanPool.notifyPool();
- } public String getUuid() { return uuid;
- } public void setUuid(String uuid) { this.uuid = uuid;
- } public ScanPool getScanPool() { return scanPool;
- } public void setScanPool(ScanPool scanPool) { this.scanPool = scanPool;
- }
- }
- public class ScanPool implements Serializable{
- /**
- * @Fields serialVersionUID : TODO(用一句話描述這個變數表示什麼)
- */
- private static final long serialVersionUID = -9117921544228636689L; private Object session ; //創建時間
- private Long createTime = System.currentTimeMillis();
- //登錄狀態
- private boolean scanFlag = false;
- public boolean isScan(){
- return scanFlag;
- }
- public void setScan(boolean scanFlag){
- this.scanFlag = scanFlag;
- }
- /**
- * 獲取掃描狀態,如果還沒有掃描,則等待固定秒數
- * @param wiatSecond 需要等待的秒數
- * @return
- */
- public synchronized boolean getScanStatus(){
- try
- {
- if(!isScan()){ //如果還未掃描,則等待
- this.wait();
- }
- if (isScan())
- { System.err.println("手機掃描完成設置getScanStatus..true..........."); return true;
- }
- } catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- return false;
- }
- /**
- * 掃碼之後設置掃碼狀態
- * @param token
- * @param id
- */
- public synchronized void scanSuccess(){
- try
- { System.err.println("手機掃描完成setScan(true)....同時釋放notifyAll(手機掃碼時,根據uuid獲得的scanpool對象)");
- setScan(true);
- this.notifyAll();
- } catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public synchronized void notifyPool(){
- try
- {
- this.notifyAll();
- } catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /***********************************************/
- public Long getCreateTime()
- {
- return createTime;
- }
- public void setCreateTime(Long createTime)
- {
- this.createTime = createTime;
- } public Object getSession() { return session;
- } public void setSession(Object session) { this.session = session;
- }
請使用手機掃碼
//生成二維碼
!function(){
var uuid =(「#uuid」).val();
varcontent;
content=「……….do?uuid=」+uuid;
//console.dir(content);(『.pc_qr_code』).qrcode({
render:」canvas」,
width:200,
height:200,
correctLevel:0,
text:content,
background:」#ffffff」,
foreground:」black」,
src:」/logo.png」
});
setCookie(「sid」, 123, -1*60*60*1000);
keepPool();//自動循環調用
}();
java代碼
ScanPool.java(存放uuid的bean)
『玖』 java大神幫幫我~~怎麼優化二維碼掃描軟體提高識別的效率啊不求代碼只求方法。萬分感謝。好人一生平安。
識別有問題嗎?如果你是用手機掃的話,可能是攝像頭像素不夠高,如果用掃瞄內槍掃的話,都沒什麼問容題的,我的二維碼在顯示器上肉眼看都比較模糊,可用防偽紙列印出來很清晰,一掃就出來了。
另外二維碼只有容錯率的說法,如下
// 設置二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小
qrcodeHandler.setQrcodeErrorCorrect('M');
『拾』 現在java手機能用二維碼識別軟體嗎飛網i碼 號稱可以java用,結果也是不行
智能機可以 謝謝