using System.IO; using System.Windows.Media; using System.Windows.Media.Imaging; using ZXing; using ZXing.QrCode; using ZXing.QrCode.Internal; namespace XFEToolBox.QuickTools; public static class QrService { public static BitmapSource Encode(string text, int size = 512) { if (string.IsNullOrEmpty(text) || System.Text.Encoding.UTF8.GetByteCount(text) > 2000) throw new ArgumentException("二维码内容不能为空,UTF-8 编码后最多 2000 字节。"); if (size is < 128 or > 4096) throw new ArgumentOutOfRangeException(nameof(size)); var writer = new BarcodeWriterPixelData { Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Width = size, Height = size, Margin = 4, CharacterSet = "UTF-8", ErrorCorrection = ErrorCorrectionLevel.M } }; var data = writer.Write(text); var image = BitmapSource.Create(data.Width, data.Height, 96, 96, PixelFormats.Bgra32, null, data.Pixels, data.Width * 4); image.Freeze(); return image; } public static string Decode(BitmapSource image) { if ((long)image.PixelWidth * image.PixelHeight > 24_000_000) throw new ArgumentException("图片最多 2400 万像素,请先裁切。"); var formatted = new FormatConvertedBitmap(image, PixelFormats.Bgra32, null, 0); byte[] pixels = new byte[formatted.PixelWidth * formatted.PixelHeight * 4]; formatted.CopyPixels(pixels, formatted.PixelWidth * 4, 0); var reader = new BarcodeReaderGeneric { AutoRotate = true, Options = new ZXing.Common.DecodingOptions { TryHarder = true, PossibleFormats = [BarcodeFormat.QR_CODE] } }; var result = reader.Decode(new RGBLuminanceSource(pixels, formatted.PixelWidth, formatted.PixelHeight, RGBLuminanceSource.BitmapFormat.BGRA32)); return result?.Text ?? throw new InvalidOperationException("没有识别到二维码;请使用清晰、完整的图片。"); } public static BitmapSource Load(string path) { if (new FileInfo(path).Length > 32 * 1024 * 1024) throw new IOException("图片文件最多 32 MiB。"); using var input = File.OpenRead(path); var frame = BitmapDecoder.Create(input, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None).Frames[0]; int width = frame.PixelWidth, height = frame.PixelHeight; if (width <= 0 || height <= 0) throw new IOException("无效的图片尺寸。"); input.Position = 0; var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; double scale = Math.Min(1, 3000d / Math.Max(width, height)); image.DecodePixelWidth = Math.Max(1, (int)(width * scale)); image.StreamSource = input; image.EndInit(); image.Freeze(); return image; } public static void Save(BitmapSource image, string path) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image)); using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write); encoder.Save(stream); } }