因为要用到二维码解析,所以就使用了zxing的图片进行识别,开始时图片大小随意传输,有手机拍照图片,有手机截图图片,还有电脑截图图片,各种大小不一致,就导致zxing的识别率特别低。
后续想到了图片处理,测试了一些,目前使用512px的识别成功率比较高,目前程序识别成功率大概在95%以上。
下面上干货吧!
//图片像素按比例缩放
Image imagePic = Image.FromStream(stream);
Bitmap bmp = imagePic as Bitmap;
if (imagePic.Width > 512)
{
int zoomMultiple = imagePic.Width / 512;
int toWidth = 512;
int toHeight = imagePic.Height / zoomMultiple;
bmp = new Bitmap(toWidth, toHeight);
using (Graphics g = Graphics.FromImage(bmp))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Transparent);
g.DrawImage(imagePic,
new Rectangle(0, 0, toWidth, toHeight),
new Rectangle(0, 0, imagePic.Width, imagePic.Height),
GraphicsUnit.Pixel);
imagePic.Dispose();
}
图片设置好之后进行识别就可以了
//第一种识别方式Zxing
var codes = new BarcodeReader
{
AutoRotate = true,
TryInverted = true,
Options = new DecodingOptions
{
TryHarder = true
}
}.DecodeMultiple(bmp);
if (codes != null)
{
result.DataView = codes[0].Text;
result.Code = Enum.ResultCode.DealSuccess;
result.Message = "识别成功";
return ReturnResp(result);
}
//第二种识别方式ZBar
using (ZBar.ImageScanner scanner = new ZBar.ImageScanner())
{
var symbols = scanner.Scan(bmp);
if (symbols.Count > 0 && symbols[0].Data.Length > 8)
{
result.DataView = symbols[0].Data;
result.Code = Enum.ResultCode.DealSuccess;
result.Message = "识别成功";
return ReturnResp(result);
}
}
//第三种识别方式Zxing
MultiFormatReader reader = new MultiFormatReader();
Dictionary<DecodeHintType, object> dictionary = new Dictionary<DecodeHintType, object> { { DecodeHintType.CHARACTER_SET, "UTF-8" } };
RGBLuminanceSource source = new RGBLuminanceSource(QrCode.Bitmap2Rgb(bmp), bmp.Width, bmp.Height);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result resultVerify = reader.decode(bitmap, dictionary);
if (resultVerify != null)
{
result.DataView = resultVerify.Text;
result.Code = Enum.ResultCode.DealSuccess;
result.Message = "识别成功";
return ReturnResp(result);
}
string thoughtWorksResult = "";
//第四种识别方式thoughtWorks
try
{
QRCodeDecoder decoder = new QRCodeDecoder();
thoughtWorksResult = decoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage(bmp));
}
catch (Exception)
{
}
if (!string.IsNullOrEmpty(thoughtWorksResult))
{
result.DataView = thoughtWorksResult;
result.Code = Enum.ResultCode.DealSuccess;
result.Message = "识别成功";
return ReturnResp(result);
}
else
{
result.Code = Enum.ResultCode.DealFail;
result.Message = "识别失败";
}
好了识别目前还没想到更好的提高成功率的方法,找到再进行更新吧。