C# 读写文本,生成二维码

<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="微软雅黑"
        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="预览" 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="打开图片" Height="30" Width="120" Margin="0,0,10,0" Click="BtnOCR_Click"/>
                    <Button x:Name="BtnClose" Content="清除" Height="30" Width="120" Margin="0,0,10,0" Click="BtnClose_Click"/>
                    <Button x:Name="BtnSave" Content="保存二维码" Height="30" Width="120" Click="BtnSave_Click"/>
                </StackPanel>
                <Image Name="ImgPreview" Grid.Row="1" Margin="5"/>
            </Grid>
        </GroupBox>
        <GroupBox Grid.Column="1" Header="识别结果:挑选" Margin="5,10,10,10">
            <TextBox x:Name="TxtPreview" TextWrapping="Wrap" BorderThickness="0" IsReadOnly="True"/>
        </GroupBox>

        <GroupBox Grid.Row="1" Grid.Column="1" Header="原始识别结果" Margin="5,10,10,10">
            <TextBox x:Name="TxtP1" TextWrapping="Wrap" BorderThickness="0" IsReadOnly="True"/>
        </GroupBox>

        <GroupBox Grid.Row="1" Grid.Column="0" Header="二维码" 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 = "图片(*.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 = "对应正数发票代码:033001900211号码:00264713订单号:627959,";
                var remark = ocrResult.Text;
                //string pattern = @"^对应正数发票代码:\d{12}号码:(\d+)订单号:\d{6,7}";

                //string pattern = @"^发票号: \d{15}";
                string pattern = @"发票号:(\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(); 这两句都可以
                        ms.Close();
                        //Convert it to BitmapImage
                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.StreamSource = new MemoryStream(bytes);
                        image.EndInit();
                        this.ImageViewer1.Source = image;
                    }));

                    
                }
            });
        }

        /// <summary>
        /// 导出图片
        /// </summary>
        /// <param name="element">xaml 里面的某个可视化元素对象 </param>
        private void ExportPicture(Bitmap bitmapImg)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "PNG 文件 (*.png)|*.png|JPG 文件 (*.jpg)|*.jpg|BMP 文件 (*.bmp)|*.bmp|GIF 文件 (*.gif)|*.gif|TIF 文件 (*.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("附件另存成功!");
            }
        }

        private void StartDistinguish1()
        {
            //OpenFileDialog openFile = new()
            //{
            //    Filter = "图片(*.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 = "对应正数发票代码:033001900211号码:00264713订单号:627959,";
                var remark = ocrResult.Text;
                //string pattern = @"^对应正数发票代码:\d{12}号码:(\d+)订单号:\d{6,7}";

                //string pattern = @"^发票号: \d{15}";
                string pattern = @"发票号:(\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();
        }
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值