Program.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright 2024 Axel Waggershauser
  3. */
  4. // SPDX-License-Identifier: Apache-2.0
  5. using System.Collections.Generic;
  6. using ImageMagick;
  7. using SkiaSharp;
  8. using ZXingCpp;
  9. public static class MagickImageBarcodeReader
  10. {
  11. public static Barcode[] Read(MagickImage img, ReaderOptions? opts = null)
  12. {
  13. if (img.DetermineBitDepth() < 8)
  14. img.SetBitDepth(8);
  15. var bytes = img.ToByteArray(MagickFormat.Gray);
  16. var iv = new ImageView(bytes, img.Width, img.Height, ImageFormat.Lum);
  17. return BarcodeReader.Read(iv, opts);
  18. }
  19. public static Barcode[] From(this BarcodeReader reader, MagickImage img) => Read(img, reader);
  20. }
  21. public static class SkBitmapBarcodeReader
  22. {
  23. public static Barcode[] Read(SKBitmap img, ReaderOptions? opts = null)
  24. {
  25. var format = img.Info.ColorType switch
  26. {
  27. SKColorType.Gray8 => ImageFormat.Lum,
  28. SKColorType.Rgba8888 => ImageFormat.RGBA,
  29. SKColorType.Bgra8888 => ImageFormat.BGRA,
  30. _ => ImageFormat.None,
  31. };
  32. if (format == ImageFormat.None)
  33. {
  34. if (!img.CanCopyTo(SKColorType.Gray8))
  35. throw new Exception("Incompatible SKColorType");
  36. img = img.Copy(SKColorType.Gray8);
  37. format = ImageFormat.Lum;
  38. }
  39. var iv = new ImageView(img.GetPixels(), img.Info.Width, img.Info.Height, format);
  40. return BarcodeReader.Read(iv, opts);
  41. }
  42. public static Barcode[] From(this BarcodeReader reader, SKBitmap img) => Read(img, reader);
  43. }
  44. public class Program
  45. {
  46. public static void Main(string[] args)
  47. {
  48. #if false
  49. var img = new MagickImage(args[0]);
  50. #else
  51. var img = SKBitmap.Decode(args[0]);
  52. #endif
  53. Console.WriteLine(img);
  54. var readBarcodes = new BarcodeReader() {
  55. TryInvert = false,
  56. ReturnErrors = true,
  57. };
  58. if (args.Length >= 2)
  59. readBarcodes.Formats = Barcode.FormatsFromString(args[1]);
  60. foreach (var b in readBarcodes.From(img))
  61. Console.WriteLine($"{b.Format} ({b.ContentType}): {b.Text} / [{string.Join(", ", b.Bytes)}] {b.ErrorMsg}");
  62. }
  63. }