using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; using ZXing; using ZXing.Common; using static System.Net.Mime.MediaTypeNames; namespace DumaTest { internal class Program { static void Main(string[] args) { //string result = ""; //try //{ // result = CodeDict[in0]; //} //catch //{ // char[] charArray = in0.ToCharArray(); // Array.Reverse(charArray); // string reversed = new string(charArray); // result = CodeDict[reversed]; //} //out0 = result; //string imagePath = @"D:\work\TEST\Image_20250802111433217.bmp"; //// 诊断图像 //DiagnoseBarcode(imagePath); //// 尝试高级解码 //var result = DecodeBarcodeAdvanced(imagePath); //if (result != null) //{ // Console.WriteLine($"识别成功: {result.Text}"); // Console.WriteLine($"条码格式: {result.BarcodeFormat}"); //} //else //{ // Console.WriteLine("未能识别条码,请检查图像质量或尝试其他方法"); //} //Dictionary keyValues = new Dictionary(); //keyValues.Add("key1", "value1"); //string result = keyValues["key1"]; //Console.WriteLine(result); Console.ReadKey(); } public static Result DecodeBarcode(string imagePath) { try { // 确保使用正确的图像格式加载 using (var bitmap = new Bitmap(imagePath)) { var barcodeReader = new BarcodeReader { Options = new ZXing.Common.DecodingOptions { TryHarder = true, // 更努力地尝试解码 PureBarcode = false } }; return barcodeReader.Decode(bitmap); } } catch (Exception ex) { Console.WriteLine($"解码错误: {ex.Message}"); return null; } } public static void DiagnoseBarcode(string imagePath) { Console.WriteLine($"正在诊断图像: {imagePath}"); try { using (var bitmap = new Bitmap(imagePath)) { Console.WriteLine($"图像尺寸: {bitmap.Width} x {bitmap.Height}"); Console.WriteLine($"像素格式: {bitmap.PixelFormat}"); // 检查图像是否为空或太小 if (bitmap.Width < 10 || bitmap.Height < 10) { Console.WriteLine("警告: 图像太小"); return; } var reader = new BarcodeReader(); // 尝试不同的配置 var configs = new[] { new { Name = "默认配置", TryHarder = false, PureBarcode = false }, new { Name = "TryHarder", TryHarder = true, PureBarcode = false }, new { Name = "PureBarcode", TryHarder = false, PureBarcode = true }, new { Name = "TryHarder+PureBarcode", TryHarder = true, PureBarcode = true } }; foreach (var config in configs) { reader.Options.TryHarder = config.TryHarder; reader.Options.PureBarcode = config.PureBarcode; var result = reader.Decode(bitmap); Console.WriteLine($"{config.Name}: {(result != null ? "成功" : "失败")}"); if (result != null) { Console.WriteLine($" 内容: {result.Text}"); Console.WriteLine($" 格式: {result.BarcodeFormat}"); return; } } Console.WriteLine("所有配置都未能识别条码"); } } catch (Exception ex) { Console.WriteLine($"诊断过程中发生错误: {ex.Message}"); } } public static Result DecodeBarcodeAdvanced(string imagePath) { var barcodeReader = new BarcodeReader { Options = new DecodingOptions { // 尝试所有可能的格式 PossibleFormats = new List { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128, BarcodeFormat.CODE_39, BarcodeFormat.EAN_13, BarcodeFormat.UPC_A, BarcodeFormat.UPC_E, BarcodeFormat.EAN_8, BarcodeFormat.DATA_MATRIX, BarcodeFormat.PDF_417, BarcodeFormat.AZTEC }, TryHarder = true, PureBarcode = false, } }; try { using (var bitmap = new Bitmap(imagePath)) { try { var result = barcodeReader.Decode(bitmap); if (result != null) return result; } catch (NullReferenceException nullEx) { Console.WriteLine($"空引用异常: {nullEx.Message}"); // 记录更详细的堆栈跟踪 Console.WriteLine($"堆栈跟踪: {nullEx.StackTrace}"); return null; } catch (Exception ex) { Console.WriteLine($"解码异常: {ex.Message}"); return null; } // 如果失败,尝试其他方法 return TryAlternativeMethods(bitmap, barcodeReader); } } catch (Exception ex) { Console.WriteLine($"解码异常: {ex.Message}"); return null; } } private static Result TryAlternativeMethods(Bitmap bitmap, BarcodeReader reader) { // 方法1: 转换为灰度图 var grayscaleBitmap = ConvertToGrayscale(bitmap); var result = reader.Decode(grayscaleBitmap); if (result != null) return result; // 方法2: 调整图像大小 var resizedBitmap = ResizeImage(bitmap, bitmap.Width *2, bitmap.Height *2); result = reader.Decode(resizedBitmap); if (result != null) return result; // 方法3: 旋转图像尝试不同角度 for (int i = 0; i < 4; i++) { var rotatedBitmap = RotateImage(bitmap, i * 90); result = reader.Decode(rotatedBitmap); if (result != null) return result; } return null; } private static Bitmap ConvertToGrayscale(Bitmap original) { var grayscale = new Bitmap(original.Width, original.Height); using (var g = Graphics.FromImage(grayscale)) { var colorMatrix = new ColorMatrix( new float[][] { new float[] {.3f, .3f, .3f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); using (var attributes = new ImageAttributes()) { attributes.SetColorMatrix(colorMatrix); g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); } } return grayscale; } private static Bitmap ResizeImage(Bitmap original, int width, int height) { var resized = new Bitmap(width, height); using (var g = Graphics.FromImage(resized)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(original, 0, 0, width, height); } return resized; } private static Bitmap RotateImage(Bitmap original, float angle) { var rotated = new Bitmap(original.Width, original.Height); using (var g = Graphics.FromImage(rotated)) { g.TranslateTransform(original.Width / 2f, original.Height / 2f); g.RotateTransform(angle); g.TranslateTransform(-original.Width / 2f, -original.Height / 2f); g.DrawImage(original, new Point(0, 0)); } return rotated; } public static Result DecodeLargeBarcode(string imagePath) { using (var originalBitmap = new Bitmap(imagePath)) { Console.WriteLine($"原始图像尺寸: {originalBitmap.Width} x {originalBitmap.Height}"); // 方法1: 调整尺寸 var result = DecodeBarcodeWithResizing(imagePath); if (result != null) return result; // 方法2: 裁剪识别 result = DecodeWithCropping(originalBitmap); if (result != null) return result; // 方法3: 综合处理 result = DecodeWithComprehensiveApproach(originalBitmap); if (result != null) return result; } return null; } private static Result DecodeWithComprehensiveApproach(Bitmap original) { var reader = new BarcodeReader { Options = new ZXing.Common.DecodingOptions { TryHarder = true, PureBarcode = false, PossibleFormats = new List { BarcodeFormat.CODE_128, BarcodeFormat.CODE_39, BarcodeFormat.EAN_13, BarcodeFormat.UPC_A } } }; // 组合多种策略 var strategies = new Func[] { // 原始图像 bmp => new Bitmap(bmp), // 调整尺寸 bmp => ResizeForBarcodeRecognition(bmp, 800), bmp => ResizeForBarcodeRecognition(bmp, 1200), // 裁剪 bmp => CropCenter(bmp, 0.8), bmp => CropCenter(bmp, 0.6), // 先裁剪再调整尺寸 bmp => ResizeForBarcodeRecognition( CropCenter(bmp, 0.7), 1000) }; foreach (var strategy in strategies) { try { using (var processed = strategy(original)) { var result = reader.Decode(processed); if (result != null) { Console.WriteLine("使用综合策略识别成功"); return result; } } } catch (Exception ex) { Console.WriteLine($"策略执行失败: {ex.Message}"); } } return null; } /// /// 调整图像尺寸以优化条码识别 /// /// 原始图像 /// 最大尺寸 /// 调整后的图像 public static Bitmap ResizeForBarcodeRecognition(Bitmap originalImage, int maxDimension = 800) { // 如果图像尺寸已经合适,则直接返回 if (originalImage.Width <= maxDimension && originalImage.Height <= maxDimension) { return originalImage; } // 计算缩放比例 double scale = Math.Min(maxDimension / (double)originalImage.Width, maxDimension / (double)originalImage.Height); int newWidth = (int)(originalImage.Width * scale); int newHeight = (int)(originalImage.Height * scale); var resizedImage = new Bitmap(newWidth, newHeight); using (var graphics = Graphics.FromImage(resizedImage)) { graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight); } return resizedImage; } /// /// 尝试多种尺寸识别条码 /// public static Result DecodeBarcodeWithResizing(string imagePath) { using (var originalBitmap = new Bitmap(imagePath)) { var reader = new BarcodeReader { Options = new ZXing.Common.DecodingOptions { TryHarder = true, PureBarcode = false } }; // 尝试不同尺寸 int[] sizes = { 0, 800, 1200, 1600 }; // 0 表示原始尺寸 foreach (int size in sizes) { using (Bitmap bitmap = size == 0 ? new Bitmap(originalBitmap) : ResizeForBarcodeRecognition(originalBitmap, size)) { var result = reader.Decode(bitmap); if (result != null) { Console.WriteLine($"在尺寸 {size} 下识别成功"); return result; } } } } return null; } /// /// 裁剪图像中心区域以优化识别 /// public static Bitmap CropCenter(Bitmap original, double cropRatio = 0.8) { int cropWidth = (int)(original.Width * cropRatio); int cropHeight = (int)(original.Height * cropRatio); int x = (original.Width - cropWidth) / 2; int y = (original.Height - cropHeight) / 2; var cropped = new Bitmap(cropWidth, cropHeight); using (var graphics = Graphics.FromImage(cropped)) { graphics.DrawImage(original, new Rectangle(0, 0, cropWidth, cropHeight), new Rectangle(x, y, cropWidth, cropHeight), GraphicsUnit.Pixel); } return cropped; } /// /// 多区域裁剪识别 /// public static Result DecodeWithCropping(Bitmap originalBitmap) { var reader = new BarcodeReader { Options = new ZXing.Common.DecodingOptions { TryHarder = true } }; // 尝试不同裁剪比例 double[] cropRatios = { 1.0, 0.9, 0.8, 0.7, 0.6 }; foreach (double ratio in cropRatios) { using (var cropped = ratio >= 1.0 ? new Bitmap(originalBitmap) : CropCenter(originalBitmap, ratio)) { var result = reader.Decode(cropped); if (result != null) { Console.WriteLine($"裁剪比例 {ratio} 识别成功"); return result; } } } return null; } } }