Files
DevToolsAvalonia/常用工具集/ViewModels/03图片相关/二维码条形码解析ViewModel.cs
2025-08-26 08:37:44 +08:00

90 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using SkiaSharp;
using ZXing;
using ZXing.Common;
using ZXing.SkiaSharp;
using .Base;
namespace .ViewModel._03图片相关
{
public class ViewModel : ViewModelBase
{
public string ImagePath { get; set; } = "";
public string Result { get; set; } = "";
public DelegateCommand SelectPathCmd { get; set; }
public DelegateCommand GetResultCmd { get; set; }
public ViewModel()
{
SelectPathCmd = new DelegateCommand(SelectPathCmdFunc);
GetResultCmd = new DelegateCommand(GetResultCmdFunc);
}
/// <summary>
/// 选择文件
/// </summary>
/// <param name="obj"></param>
private async void SelectPathCmdFunc(object obj)
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
FilePickerOpenOptions options = new FilePickerOpenOptions();
options.Title = "选择二维码图片";
options.AllowMultiple = false;
options.FileTypeFilter = [
FilePickerFileTypes.ImageAll
];
var result = await sp.OpenFilePickerAsync(options);
if (result == null || result.Count == 0) return;
ImagePath = result.FirstOrDefault()?.Path.LocalPath;
}
private void GetResultCmdFunc(object obj)
{
try
{
MultiFormatReader formatReader = new MultiFormatReader();
Dictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, Encoding.UTF8.HeaderName);
// 优化精度
hints.Add(DecodeHintType.TRY_HARDER, true);
// 复杂模式开启PURE_BARCODE模式
hints.Add(DecodeHintType.PURE_BARCODE, true);
formatReader.Hints = hints;
SKBitmap bitmap = SKBitmap.Decode(ImagePath);
LuminanceSource source = new SKBitmapLuminanceSource(bitmap);
Result result = formatReader.decode(new BinaryBitmap(new HybridBinarizer(source)));
if (null == result)
{
result = formatReader.decode(new BinaryBitmap(new GlobalHistogramBinarizer(source)));
}
bitmap.Dispose();
if (result != null)
{
Result = result.Text; // 显示解析出的一维码文本内容
}
else
{
Result = "未能解析条码";
}
}
catch (Exception ex)
{
Result = ex.Message;
}
}
}
}