zxing 可以从github的官方网站上下载下来,这里提供一个VS 2010编译zxing的静态库工程,编译时注意一点是:zxing的很多不同的文件夹下含有相同名称的源文件,在编译时应该分别设置这些源文件的obj文件输出到不同的路径下,否则VS默认会将这些obj文件输出到同一个目录下,从而产生相互覆盖,编译期也会给出警告,这样编译生成的库不全,后期链接调用时很可能发生链接不到的错误。具体可以参考下图。

我这提供一个可用的zxing编译成静态库的VS 2010的工程。

http://download.csdn.net/detail/kuzuozhou/7346123

参考github上给出的示例程序,我这提供了两个解码二维码的接口,1.接收图片文件为参数;2.接收图片的二进制数据为参数。

相应的源文件有:

//BufferBitmapSource.h#include <zxing/LuminanceSource.h>
#include <stdio.h>
#include <stdlib.h>
using namespace zxing; class BufferBitmapSource : public LuminanceSource {
private:typedef LuminanceSource Super;int width, height; ArrayRef<char> buffer; public:BufferBitmapSource(int inWidth, int inHeight, ArrayRef<char> inBuffer); ~BufferBitmapSource(); int getWidth() const; int getHeight() const; ArrayRef<char> getRow(int y, ArrayRef<char> row) const; ArrayRef<char> getMatrix() const;
};
//BufferBitmapSource.cpp#include "parseQR\BufferBitmapSource.h"
#include <iostream>BufferBitmapSource::BufferBitmapSource(int inWidth, int inHeight, ArrayRef<char> inBuffer) :Super(inWidth,inHeight),buffer(inBuffer)
{width = inWidth; height = inHeight; buffer = inBuffer;
}BufferBitmapSource::~BufferBitmapSource()
{
}int BufferBitmapSource::getWidth() const
{return width;
}int BufferBitmapSource::getHeight() const
{return height;
}ArrayRef<char> BufferBitmapSource::getRow(int y, ArrayRef<char> row) const
{if (y < 0 || y >= height) {fprintf(stderr, "ERROR, attempted to read row %d of a %d height image.\n", y, height); return NULL; }// WARNING: NO ERROR CHECKING! You will want to add some in your code. if (row == NULL) row = ArrayRef<char>(getWidth());for (int x = 0; x < width; x ++){row[x] = buffer[y*width+x]; }return row;
}ArrayRef<char> BufferBitmapSource::getMatrix() const
{return buffer;
}
//ImageReaderSource.h// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
#ifndef __IMAGE_READER_SOURCE_H_
#define __IMAGE_READER_SOURCE_H_
/**  Copyright 2010-2011 ZXing authors** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/#include <zxing/LuminanceSource.h>
#include <zxing/common/Array.h>class ImageReaderSource : public zxing::LuminanceSource {
private:typedef LuminanceSource Super;const zxing::ArrayRef<char> image;const int comps;char convertPixel(const char* pixel) const;public:static zxing::Ref<LuminanceSource> create(std::string const& filename);ImageReaderSource(zxing::ArrayRef<char> image, int width, int height, int comps);zxing::ArrayRef<char> getRow(int y, zxing::ArrayRef<char> row) const;zxing::ArrayRef<char> getMatrix() const;
};#endif /* __IMAGE_READER_SOURCE_H_ */
//ImageReaderSource.cpp/**  Copyright 2010-2011 ZXing authors** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/#include "parseQR\ImageReaderSource.h"
#include <zxing/common/IllegalArgumentException.h>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include "parseQR\lodepng.h"
#include "parseQR\jpgd.h"using std::string;
using std::ostringstream;
using zxing::Ref;
using zxing::ArrayRef;
using zxing::LuminanceSource;inline char ImageReaderSource::convertPixel(char const* pixel_) const {unsigned char const* pixel = (unsigned char const*)pixel_;if (comps == 1 || comps == 2) {// Gray or gray+alphareturn pixel[0];} if (comps == 3 || comps == 4) {// Red, Green, Blue, (Alpha)// We assume 16 bit values here// 0x200 = 1<<9, half an lsb of the result to force roundingreturn (char)((306 * (int)pixel[0] + 601 * (int)pixel[1] +117 * (int)pixel[2] + 0x200) >> 10);} else {throw zxing::IllegalArgumentException("Unexpected image depth");}
}ImageReaderSource::ImageReaderSource(ArrayRef<char> image_, int width, int height, int comps_): Super(width, height), image(image_), comps(comps_) {}Ref<LuminanceSource> ImageReaderSource::create(string const& filename) {string extension = filename.substr(filename.find_last_of(".") + 1);std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);int width, height;int comps = 0;zxing::ArrayRef<char> image;if (extension == "png") {std::vector<unsigned char> out;{ unsigned w, h;unsigned error = lodepng::decode(out, w, h, filename);if (error) {ostringstream msg;msg << "Error while loading '" << lodepng_error_text(error) << "'";throw zxing::IllegalArgumentException(msg.str().c_str());}width = w;height = h;}comps = 4;image = zxing::ArrayRef<char>(4 * width * height);memcpy(&image[0], &out[0], image->size());} else if (extension == "jpg" || extension == "jpeg") {char *buffer = reinterpret_cast<char*>(jpgd::decompress_jpeg_image_from_file(filename.c_str(), &width, &height, &comps, 4));image = zxing::ArrayRef<char>(buffer, 4 * width * height);}if (!image) {ostringstream msg;msg << "Loading \"" << filename << "\" failed.";throw zxing::IllegalArgumentException(msg.str().c_str());}return Ref<LuminanceSource>(new ImageReaderSource(image, width, height, comps));
}zxing::ArrayRef<char> ImageReaderSource::getRow(int y, zxing::ArrayRef<char> row) const {const char* pixelRow = &image[0] + y * getWidth() * 4;if (!row) {row = zxing::ArrayRef<char>(getWidth());}for (int x = 0; x < getWidth(); x++) {row[x] = convertPixel(pixelRow + (x * 4));}return row;
}/** This is a more efficient implementation. */
zxing::ArrayRef<char> ImageReaderSource::getMatrix() const {const char* p = &image[0];zxing::ArrayRef<char> matrix(getWidth() * getHeight());char* m = &matrix[0];for (int y = 0; y < getHeight(); y++) {for (int x = 0; x < getWidth(); x++) {*m = convertPixel(p);m++;p += 4;}}return matrix;
}

还有其他几个jpd.h,lodepng.h及其对应的cpp文件都是示例程序给出的,这里不再添加了。

最后给出parseQRInfo.cpp的代码。

// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
*  Copyright 2010-2011 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "parseQR\parseQRInfo.h"#include <iostream>
#include <fstream>
#include <string>
#include "parseQR\ImageReaderSource.h"
#include "parseQR\BufferBitmapSource.h"
#include <zxing/common/Counted.h>
#include <zxing/Binarizer.h>
#include <zxing/MultiFormatReader.h>
#include <zxing/Result.h>
#include <zxing/ReaderException.h>
#include <zxing/common/GlobalHistogramBinarizer.h>
#include <zxing/common/HybridBinarizer.h>
#include <exception>
#include <zxing/Exception.h>
#include <zxing/common/IllegalArgumentException.h>
#include <zxing/BinaryBitmap.h>
#include <zxing/DecodeHints.h>#include <zxing/qrcode/QRCodeReader.h>
#include <zxing/multi/qrcode/QRCodeMultiReader.h>
#include <zxing/multi/ByQuadrantReader.h>
#include <zxing/multi/MultipleBarcodeReader.h>
#include <zxing/multi/GenericMultipleBarcodeReader.h>using namespace std;
using namespace zxing;
using namespace zxing::multi;
using namespace zxing::qrcode;namespace {bool more = false;bool test_mode = false;bool try_harder = false;bool search_multi = false;bool use_hybrid = false;bool use_global = false;bool verbose = false;}vector<Ref<Result> > decode(Ref<BinaryBitmap> image, DecodeHints hints) {Ref<Reader> reader(new MultiFormatReader);return vector<Ref<Result> >(1, reader->decode(image, hints));
}vector<Ref<Result> > decode_multi(Ref<BinaryBitmap> image, DecodeHints hints) {MultiFormatReader delegate;GenericMultipleBarcodeReader reader(delegate);return reader.decodeMultiple(image, hints);
}int read_image(Ref<LuminanceSource> source, bool hybrid, string expected, string& QRResult) {vector<Ref<Result> > results;string cell_result;int res = -1;try {Ref<Binarizer> binarizer;if (hybrid) {binarizer = new HybridBinarizer(source);} else {binarizer = new GlobalHistogramBinarizer(source);}DecodeHints hints(DecodeHints::DEFAULT_HINT);hints.setTryHarder(try_harder);Ref<BinaryBitmap> binary(new BinaryBitmap(binarizer));if (search_multi) {results = decode_multi(binary, hints);} else {results = decode(binary, hints);}res = 0;} catch (const ReaderException& e) {cell_result = "zxing::ReaderException: " + string(e.what());cout<<cell_result <<endl;res = -2;} catch (const zxing::IllegalArgumentException& e) {cell_result = "zxing::IllegalArgumentException: " + string(e.what());cout<<cell_result<<endl;res = -3;} catch (const zxing::Exception& e) {cell_result = "zxing::Exception: " + string(e.what());cout<<cell_result<<endl;res = -4;} catch (const std::exception& e) {cell_result = "std::exception: " + string(e.what());cout<<cell_result<<endl;res = -5;}if (test_mode && results.size() == 1) {std::string result = results[0]->getText()->getText();if (expected.empty()) {cout << "  Expected text or binary data for image missing." << endl<< "  Detected: " << result << endl;res = -6;} else {if (expected.compare(result) != 0) {cout << "  Expected: " << expected << endl<< "  Detected: " << result << endl;cell_result = "data did not match";res = -6;}}}if (res != 0 && (verbose || (use_global ^ use_hybrid))) {cout << (hybrid ? "Hybrid" : "Global")<< " binarizer failed: " << cell_result << endl;} else if (!test_mode) {if (verbose) {cout << (hybrid ? "Hybrid" : "Global")<< " binarizer succeeded: " << endl;}for (size_t i = 0; i < results.size(); i++) {if (more) {cout << "  Format: "<< BarcodeFormat::barcodeFormatNames[results[i]->getBarcodeFormat()]<< endl;for (int j = 0; j < results[i]->getResultPoints()->size(); j++) {cout << "  Point[" << j <<  "]: "<< results[i]->getResultPoints()[j]->getX() << " "<< results[i]->getResultPoints()[j]->getY() << endl;}}if (verbose) {cout << "    ";}cout << results[i]->getText()->getText() << endl;QRResult = results[i]->getText()->getText();}}return res;
}string read_expected(string imagefilename) {string textfilename = imagefilename;string::size_type dotpos = textfilename.rfind(".");textfilename.replace(dotpos + 1, textfilename.length() - dotpos - 1, "txt");ifstream textfile(textfilename.c_str(), ios::binary);textfilename.replace(dotpos + 1, textfilename.length() - dotpos - 1, "bin");ifstream binfile(textfilename.c_str(), ios::binary);ifstream *file = 0;if (textfile.is_open()) {file = &textfile;} else if (binfile.is_open()) {file = &binfile;} else {return std::string();}file->seekg(0, ios_base::end);size_t size = size_t(file->tellg());file->seekg(0, ios_base::beg);if (size == 0) {return std::string();}char* data = new char[size + 1];file->read(data, size);data[size] = '\0';string expected(data);delete[] data;return expected;
}bool parseQRInfo(string filename,string& QRResult) {bool flag = false;try_harder = true;if (!use_global && !use_hybrid) {use_global = use_hybrid = true;}Ref<LuminanceSource> source;try {source = ImageReaderSource::create(filename);} catch (const zxing::IllegalArgumentException &e) {cerr << e.what() << " (ignoring)" << endl;}string expected = read_expected(filename);int gresult = 1;int hresult = 1;if (use_hybrid) {hresult = read_image(source, true, expected, QRResult);flag = (hresult==0?true:false);}if (use_global && (verbose || hresult != 0)) {gresult = read_image(source, false, expected, QRResult);flag = (gresult==0?true:false);if (!verbose && gresult != 0) {cout << "decoding failed" << endl;}}return flag;}bool parseQRInfo(int width,int height,unsigned char* buffer,std::string &QRResult){try{// Convert the buffer to something that the library understands. ArrayRef<char> data((char*)buffer, width*height);Ref<LuminanceSource> source (new BufferBitmapSource(width, height, data)); // Turn it into a binary image. Ref<Binarizer> binarizer (new GlobalHistogramBinarizer(source)); Ref<BinaryBitmap> image(new BinaryBitmap(binarizer));// Tell the decoder to try as hard as possible. DecodeHints hints(DecodeHints::DEFAULT_HINT); hints.setTryHarder(true); // Perform the decoding. QRCodeReader reader;Ref<Result> result(reader.decode(image, hints));// Output the result. cout << result->getText()->getText() << endl;QRResult = result->getText()->getText();}catch (zxing::Exception& e) {cerr << "Error: " << e.what() << endl;return false;}return true;}

C++用zxing识别二维码相关推荐

  1. Opencv之python使用zxing识别二维码

    方式1: 安装方式: pip install zxing import zxingreader = zxing.BarCodeReader() barcode = reader.decode(&quo ...

  2. python二维码生成识别代码_Python3+qrcode+zxing生成和识别二维码教程

    一.安装依赖库 pip install qrcode pillow image zxing pillow是python3中PIL的代替库,image是生成图版需要用到的库 安装image时报错&quo ...

  3. docker中使用python zxing实现二维码内容识别

      python中可以使用多种方法实现二维码内容的识别,但是不同实现的表现也各不相同,根据个人体验,zxing的识别效果要强于pyzbar.   但在将项目打成docker时,遇到了问题. File ...

  4. Python生成+识别二维码

    二维码(QR Code),使用平面图案存储信息,根据白0黑1的算机内部逻辑,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理,记录好所有数 ...

  5. Android利用zxing生成二维码,识别二维码,中间填充图片超详细、超简易教程

    gayhub上的zxing可用于生成二维码,识别二维码 gayhub地址:https://github.com/zxing/zxing 此文只是简易教程,文末附有完整代码和demo下载地址,进入正题: ...

  6. Android利用zxing用相机扫描识别二维码(添加闪光灯和本地二维码)超详细教程

    之前写了怎么用zxing的jar包进行简单的识别和生成二维码,以及生成带图片的二维码. 接下来单独说说怎么用相机扫描二维码,用相机扫描二维码相对于前面的生成二维码,识别二维码来说要麻烦一点,网上的教程 ...

  7. java识别二维码-zxing

    1.pom文件中引入 <dependency><groupId>com.google.zxing</groupId><artifactId>javase ...

  8. (转载)Android项目实战(二十八):使用Zxing实现二维码及优化实例

    Android项目实战(二十八):使用Zxing实现二维码及优化实例 作者:听着music睡 字体:[增加 减小] 类型:转载 时间:2016-11-21 我要评论 这篇文章主要介绍了Android项 ...

  9. Zing实现本地相册识别二维码

    前言 最近公司的项目需要加入本地相册识别二维码的功能,就类似与微信那样.大家都知道二维码识别目前火的一个是Zing,一个就是Zbar,针对于这两个的区别,在此也不再赘述.(PS:网上的资料有很多)由于 ...

最新文章

  1. 目标检测--DSOD: Learning Deeply Supervised Object Detectors from Scratch
  2. ReverseMe-120(base64解码表) 逆向寒假生涯(21/100)
  3. MFC中将CBitmap画到cdc上
  4. [蓝桥杯][算法提高VIP]分分钟的碎碎念-dfs
  5. Gradle入门:创建多项目构建
  6. C# 系统环境变量读取
  7. DTP动态协商——trunk配置、如何关闭域名解析、光接口无法up的原因详解(附图)
  8. 使用 HTML5 File API 实现client log
  9. python字符串转float_令人困惑的python-无法将字符串转换为float
  10. 信号与系统(二)——正交
  11. felix 与Phoenix 发音 n和l的分辨
  12. 读论文《Toward Controlled Generation of Text》
  13. 3.8 main.js-常用配置【uni-app教程uniapp教程(黄菊华-跨平台开发系列教程)】
  14. Bumped!【最短路】(神坑
  15. 想要快乐陪伴左右吗?多种提高多巴胺的方法送给你
  16. 苏州计算机云联盟协会,【缤FUN社团】计算机协会
  17. 毕业设计 stm32便携用电功率统计系统 -物联网 嵌入式 单片机
  18. 2022届互联网校招研发薪资汇总,都是钱哇~
  19. 全套PR资源--含RAR解压密码
  20. 【ML特征工程】第 3 章 :文本数据:扁平化、过滤和分块

热门文章

  1. [系列] - go-gin-api 规划目录和参数验证(二)
  2. 工作随记-Java利用企业微信群机器人定时发送消息
  3. python人工智能课程设计_中小学课程设计:以计算思维培养为核心的人工智能课程设计与实践...
  4. PowerBI如何注册
  5. LittleFS移植实践
  6. 织梦友情链接加nofollow方法,亲测
  7. D-Link宽带路由器设置全攻略
  8. 2015 上海网赛 HDU5469 树分治
  9. Newtonsoft.Json.JsonConvert.SerializeObject()
  10. B , BX, BL, BXL