当前位置:网站首页>C # read and write text and generate QR code
C # read and write text and generate QR code
2022-07-19 14:23:00 【Lava of Rodinia】
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<ApplicationIcon>preferences_system_login_48px_572066_easyicon.net.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Content Include="preferences_system_login_48px_572066_easyicon.net.ico" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="PaddleOCRSharp" Version="2.0.2" />
<PackageReference Include="QRCoder" Version="1.4.3" />
</ItemGroup>
</Project>
<Window x:Class="ORCTest3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" FontFamily=" Microsoft YaHei " xmlns:local="clr-namespace:ORCTest3" mc:Ignorable="d" WindowStartupLocation="CenterScreen" Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="0.7*"/>
</Grid.RowDefinitions>
<GroupBox Grid.Column="0" Header=" preview " Margin="10,10,5,10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,5">
<Button x:Name="BtnOCR" Content=" Open the picture " Height="30" Width="120" Margin="0,0,10,0" Click="BtnOCR_Click"/>
<Button x:Name="BtnClose" Content=" eliminate " Height="30" Width="120" Margin="0,0,10,0" Click="BtnClose_Click"/>
<Button x:Name="BtnSave" Content=" Save QR code " Height="30" Width="120" Click="BtnSave_Click"/>
</StackPanel>
<Image Name="ImgPreview" Grid.Row="1" Margin="5"/>
</Grid>
</GroupBox>
<GroupBox Grid.Column="1" Header=" Recognition result : choose " Margin="5,10,10,10">
<TextBox x:Name="TxtPreview" TextWrapping="Wrap" BorderThickness="0" IsReadOnly="True"/>
</GroupBox>
<GroupBox Grid.Row="1" Grid.Column="1" Header=" Original recognition result " Margin="5,10,10,10">
<TextBox x:Name="TxtP1" TextWrapping="Wrap" BorderThickness="0" IsReadOnly="True"/>
</GroupBox>
<GroupBox Grid.Row="1" Grid.Column="0" Header=" QR code " Margin="5,10,10,10">
<Image x:Name="ImageViewer1"/>
</GroupBox>
</Grid>
</Window>
using Microsoft.Win32;
using PaddleOCRSharp;
using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
namespace ORCTest3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
IQRCode _qrcode;
byte[] buffer;
Bitmap bitmapImg;
public BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
{
BitmapImage bmp = null;
try
{
bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = new MemoryStream(byteArray);
bmp.EndInit();
}
catch
{
bmp = null;
}
return bmp;
}
private void StartDistinguish()
{
OpenFileDialog openFile = new()
{
Filter = " picture (*.bmp;*.jpg;*.jpeg;*.png)|*.bmp;*.jpg;*.jpeg;*.png"
};
if (!(bool)openFile.ShowDialog()) return;
Dispatcher.BeginInvoke(new Action(() =>
{
ImgPreview.Source = new BitmapImage(new Uri(openFile.FileName, UriKind.RelativeOrAbsolute));
}));
Task.Run(() =>
{
var imagebyte = File.ReadAllBytes(openFile.FileName);
Bitmap bitmap = new Bitmap(new MemoryStream(imagebyte));
OCRModelConfig? config = null;
OCRParameter oCRParameter = new();
OCRResult ocrResult = new();
using (PaddleOCREngine engine = new(config, oCRParameter))
{
ocrResult = engine.DetectText(bitmap);
}
//var remark = " Corresponding to positive invoice code :033001900211 number :00264713 The order number :627959,";
var remark = ocrResult.Text;
//string pattern = @"^ Corresponding to positive invoice code :\d{12} number :(\d+) The order number :\d{6,7}";
//string pattern = @"^ Invoice number : \d{15}";
string pattern = @" Invoice number :(\d{16})";
string parentFphm = Regex.Match(remark, pattern).Result("$1");
if (ocrResult != null)
{
//_qrcode = new QRCode();
//buffer = _qrcode.GenerateQRCode(parentFphm);
//MemoryStream ms = new MemoryStream(buffer);
//Bitmap bmpt = new Bitmap(ms);
//BitmapImage bitmapImage = new BitmapImage();
//bitmapImage.StreamSource = ms;
//bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
var generator = new QRCodeGenerator();
var codeData = generator.CreateQrCode(parentFphm, QRCodeGenerator.ECCLevel.M, true);
QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData);
bitmapImg = qrcode.GetGraphic(10, Color.Black, Color.White, false);
//using MemoryStream stream = new MemoryStream();
//bitmapImg.Save(stream, ImageFormat.Jpeg);
Dispatcher.BeginInvoke(new Action(() =>
{
TxtPreview.Text = parentFphm;
this.TxtP1.Text = remark;
}));
Dispatcher.Invoke(new Action(() =>
{
MemoryStream ms = new MemoryStream();
bitmapImg.Save(ms, ImageFormat.Bmp);
byte[] bytes = ms.GetBuffer(); //byte[] bytes= ms.ToArray(); These two sentences are OK
ms.Close();
//Convert it to BitmapImage
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new MemoryStream(bytes);
image.EndInit();
this.ImageViewer1.Source = image;
}));
}
});
}
/// <summary>
/// Export pictures
/// </summary>
/// <param name="element">xaml A visual element object inside </param>
private void ExportPicture(Bitmap bitmapImg)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "PNG file (*.png)|*.png|JPG file (*.jpg)|*.jpg|BMP file (*.bmp)|*.bmp|GIF file (*.gif)|*.gif|TIF file (*.tif)|*.tif"
};
if (saveFileDialog.ShowDialog() == true)
{
string? dir = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string filePath = saveFileDialog.FileName;
if (File.Exists(filePath))
{
File.Delete(filePath);
}
bitmapImg.Save(filePath);
MessageBox.Show(" Attachment saved successfully !");
}
}
private void StartDistinguish1()
{
//OpenFileDialog openFile = new()
//{
// Filter = " picture (*.bmp;*.jpg;*.jpeg;*.png)|*.bmp;*.jpg;*.jpeg;*.png"
//};
//if (!(bool)openFile.ShowDialog()) return;
string path = @"C:\Users\ZG\Desktop\fapiao.jpg";
Dispatcher.BeginInvoke(new Action(() =>
{
ImgPreview.Source = new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute));
}));
Task.Run(() =>
{
var imagebyte = File.ReadAllBytes(path);
Bitmap bitmap = new Bitmap(new MemoryStream(imagebyte));
OCRModelConfig? config = null;
OCRParameter oCRParameter = new();
OCRResult ocrResult = new();
using (PaddleOCREngine engine = new(config, oCRParameter))
{
ocrResult = engine.DetectText(bitmap);
}
//var remark = " Corresponding to positive invoice code :033001900211 number :00264713 The order number :627959,";
var remark = ocrResult.Text;
//string pattern = @"^ Corresponding to positive invoice code :\d{12} number :(\d+) The order number :\d{6,7}";
//string pattern = @"^ Invoice number : \d{15}";
string pattern = @" Invoice number :(\d{16})";
string parentFphm = Regex.Match(remark, pattern).Result("$1");
if (ocrResult != null)
{
Dispatcher.BeginInvoke(new Action(() =>
{
this.TxtP1.Text = remark;
TxtPreview.Text = parentFphm;
}));
//Dispatcher.BeginInvoke(new Action(() =>
//{
// this.TxtP1.Text = parentFphm;
//}));
}
});
}
private void BtnOCR_Click(object sender, RoutedEventArgs e)
{
StartDistinguish();
}
private void BtnClose_Click(object sender, RoutedEventArgs e)
{
ImgPreview.Source = null;
TxtPreview.Text = "";
}
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
ExportPicture(bitmapImg);
}
}
}
interface IQRCode
{
byte[] GenerateQRCode(string content);
}
using System;
using System.Collections.Generic;
using QRCoder;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace ORCTest3
{
public class QRCode : IQRCode
{
public byte[] GenerateQRCode(string content)
{
var generator = new QRCodeGenerator();
var codeData = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M, true);
QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData);
var bitmapImg = qrcode.GetGraphic(10, Color.Black, Color.White, false);
using MemoryStream stream = new MemoryStream();
bitmapImg.Save(stream, ImageFormat.Jpeg);
return stream.GetBuffer();
}
}
}
边栏推荐
- The NFT market pattern has not changed. Can okaleido set off a new round of waves?
- 通达信开户是真的吗?通达信开户安全吗?
- 研二非科班研究生如何备战秋招
- CF 807 E. Mark and Professor Koro(权值线段树)
- 面额10exp(303)的钞票
- 欧奈尔的RPS曲线的编制方法(陶博士原创)
- 毕设-基于SSM在线预约挂号系统
- 非凸優化問題經典必看綜述“從對稱性到幾何性”,羅切斯特大學等
- Keil环境下STM32定位hardfault位置方法和遇到的情况
- 洛谷:P3092 [USACO13NOV]No Change G(状压+二分,独特的状态定义,不写会后悔一辈子的题)
猜你喜欢

歐奈爾的RPS曲線的編制方法(陶博士原創)

智康护物业养老服务方案

Comprehensive analysis of C language multimedia open source framework GStreamer

CF 807 E. Mark and Professor Koro(权值线段树)

ModuleNotFoundError: No module named ‘_ distutils_ hack‘

Okaleido or get out of the NFT siege, are you optimistic about it?

Redis source code and design analysis -- 2 Linked list

JVM性能优化

Take a look at try{}catch{}

iVX低代码平台系列详解 -- 概述篇(二)
随机推荐
96. Different binary search trees
ModuleNotFoundError: No module named ‘_ distutils_ hack‘
STM32 positioning hardfault location method and encountered situation in keil environment
Is it safe for Hongye futures to open an account online? Are there any account opening guidelines?
通达信开户是真的吗?通达信开户安全吗?
Comprehensive analysis of C language multimedia open source framework GStreamer
欧奈尔的RPS曲线的编制方法(陶博士原创)
Unity realizes UI backpack equipment dragging function
273. Grading - acwing question bank [DP]
NFT市场格局仍未变化,Okaleido能否掀起新一轮波澜?
Take a look at try{}catch{}
Some puzzles about data dictionary
华为无线设备配置动态负载均衡
洛谷:P3092 [USACO13NOV]No Change G(状压+二分,独特的状态定义,不写会后悔一辈子的题)
Redis source code and design analysis -- 2 Linked list
Huawei wireless device configuration user CAC
Luogu p3522 [poi2011] TEM temperature solution
Keil环境下STM32定位hardfault位置方法和遇到的情况
How to avoid global index in pychart? How to cancel the indexing of a folder?
Class 3 practice