namespace CameraBarCode
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string GetStringZimg(Bitmap img)
{
string res = "";
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] bt = ms.GetBuffer();
ms.Close();
LuminanceSource source = new RGBLuminanceSource(bt, img.Width, img.Height);
BinaryBitmap bitmap = new BinaryBitmap(new ZXing.Common.HybridBinarizer(source));
Result result=null;
try
{
//开始解码
result = new MultiFormatReader().decode(bitmap);
}
catch (ReaderException re)
{
return res;
}
if (result != null) {
res = result.ToString();
}
return res;
}
private void button1_Click(object sender, EventArgs e)
{
// 定义图像捕捉方式 从摄像头 , 注意 Windows下需要选择 VideoCaptureAPIs.DSHOW
var capture = new VideoCapture(0, VideoCaptureAPIs.DSHOW);
if (!capture.IsOpened())
return;
capture.XI_OffsetX = 0; // 以左上角为起点 坐标X
capture.XI_OffsetY = 0; // 以左上角为起点 坐标Y
capture.FrameWidth = 1000; // 宽
capture.FrameHeight = 1000; // 高
capture.AutoFocus = true;
const int sleepTime = 10;
//var window = new Window("cv");
// Mat作为图像的存储容器
var image = new Mat();
while (true)
{
capture.Read(image);
if (image.Empty())
break;
// 显示
//window.ShowImage(image);
// Windows窗体PictureBox加载
Bitmap img = image.ToBitmap();
pictureBox1.Image = img;
string txt = GetStringZimg(img);
if (txt.Length>0)
{
BarCodeString.Text = txt;
capture.Dispose();
break;
}
int flag = Cv2.WaitKey(sleepTime);
if (flag >= 0)
{
break;
}
// 可以防止界面停止响应
Application.DoEvents();
}
}
}
}