text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```java package jvmgo.book.ch10; public class ParseIntTest { public static void main(String[] args) { foo(args); } private static void foo(String[] args) { try { bar(args); } catch (NumberFormatException e) { System.out.println(e.getMessage()); } } private static void bar(String[] args) { if (args.length == 0) { throw new IndexOutOfBoundsException("no args!"); } int x = Integer.parseInt(args[0]); System.out.println(x); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch10/ParseIntTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
117
```java package jvmgo.book.ch10; public class StackTraceTest { public static void main(String[] args) { foo(); } private static void foo() { bar(); } private static void bar() { throw new RuntimeException("OH!"); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch10/StackTraceTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
59
```java package jvmgo.book.ch10; public class ExceptionTest2 { public static void main(String[] args) { safe(0); safe(1); } private static void safe(int x) { try { dangerous(x); System.out.println(x); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } private static void dangerous(int x) { if (x == 0) { throw new IllegalArgumentException("0!"); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch10/ExceptionTest2.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
108
```java package jvmgo.book.ch03; public class ClassFileTest { public static final boolean FLAG = true; public static final byte BYTE = 123; public static final char X = 'X'; public static final short SHORT = 12345; public static final int INT = 123456789; public static final long LONG = 12345678901L; public static final float PI = 3.14f; public static final double E = 2.71828; public static void main(String[] args) throws RuntimeException { System.out.println("Hello, World!"); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch03/ClassFileTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
134
```java package jvmgo.book.ch08; public class ArrayDemo { public static void main(String[] args) { int[] a1 = new int[10]; // newarray String[] a2 = new String[10]; // anewarray int[][] a3 = new int[10][10]; // multianewarray int x = a1.length; // arraylength a1[0] = 100; // iastore int y = a1[0]; // iaload a2[0] = "abc"; // aastore String s = a2[0]; // aaload } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch08/ArrayDemo.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
151
```java package jvmgo.book.ch08; public class PrintArgs { public static void main(String[] args) { for (String arg : args) { System.out.println(arg); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch08/PrintArgs.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
44
```java package jvmgo.book.ch08; public class Array3D { public static void main(String[] args) { int[][][] threeD = new int[5][4][3]; for (int i = 0; i < 5; ++i) { for (int j = 0; j < 4; ++j) { for (int k = 0; k < 3; ++k) { threeD[i][j][k] = i + j + k; } } } for (int i = 0; i < 5; ++i) { for (int j = 0; j < 4; ++j) { for (int k = 0; k < 3; ++k) { System.out.println(threeD[i][j][k]); } } } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch08/Array3D.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
193
```java package jvmgo.book.ch08; public class MultianewarrayDemo { public static void main(String[] args) { new MultianewarrayDemo().test(); } public void test() { int[][][] x = new int[3][4][5]; } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch08/MultianewarrayDemo.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
63
```java package jvmgo.book.ch08; public class BubbleSortTest { public static void main(String[] args) { int[] arr = { 22, 84, 77, 11, 95, 9, 78, 56, 36, 97, 65, 36, 10, 24 ,92, 48 }; //printArray(arr); bubbleSort(arr); //System.out.println(123456789); printArray(arr); } private static void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } private static void printArray(int[] arr) { for (int i : arr) { System.out.println(i); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch08/BubbleSortTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
263
```java package jvmgo.book.ch08; public class StringTest { public static final String STR = "abc"; public static void main(String[] args) { String s1 = "xyz"; // ldc System.out.println(STR); System.out.println(s1); //String s2 = "abc1"; //assertSame(s1, s2); //int x = 1; //String s3 = "abc" + x; //assertNotSame(s1, s3); //s3 = s3.intern(); //assertSame(s1, s3); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch08/StringTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
134
```java package jvmgo.book.ch06; public class Circle { public static float PI; public float r; public static void main(String[] args) { Circle.PI = 3.14f; Circle c = new Circle(); c.r = 5.5f; float area = Circle.PI * c.r * c.r; System.out.println(area); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch06/Circle.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
88
```java package jvmgo.book.ch06; public class FieldResolutionTest { private static interface I { static int x = 1; } private static class B { public int x; } private static class C extends B implements I { //public int x; } public static void main(String[] args) { C c = new C(); //System.out.println(c.x); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch06/FieldResolutionTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
90
```java package jvmgo.book.ch06; public class FieldInitTest { public static boolean Z; public static byte B; public static short S; public static int I; public static long L; public static char C; public static float F; public static double D; public boolean z; public byte b; public short s; public int i; public long l; public char c; public float f; public double d; public static void main(String[] args) { System.out.println(Z); System.out.println(B); System.out.println(S); System.out.println(I); System.out.println(L); System.out.println(C); System.out.println(F); System.out.println(D); FieldInitTest obj = new FieldInitTest(); System.out.println(obj.z); System.out.println(obj.b); System.out.println(obj.s); System.out.println(obj.i); System.out.println(obj.l); System.out.println(obj.c); System.out.println(obj.f); System.out.println(obj.d); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch06/FieldInitTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
231
```java package jvmgo.book.ch06; public class FieldTest { public static class Inner { private int x; } public static void main(String[] args) { Inner inner = new Inner(); inner.x = 100; System.out.println(inner.x); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch06/FieldTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
61
```java package jvmgo.book.ch01; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world!"); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch01/HelloWorld.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
37
```java package jvmgo.book.ch06; public class MyObject { public static int staticVar; public int instanceVar; public static void main(String[] args) { int x = 32768; // ldc MyObject myObj = new MyObject(); // new MyObject.staticVar = x; // putstatic x = MyObject.staticVar; // getstatic myObj.instanceVar = x; // putfield x = myObj.instanceVar; // getfield Object obj = myObj; if (obj instanceof MyObject) { // instanceof myObj = (MyObject) obj; // checkcast System.out.println(myObj.instanceVar); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch06/MyObject.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
156
```java package jvmgo.book.ch09; import java.util.ArrayList; import java.util.List; public class ArrayListTest { public static void main(String[] args) { List<String> strs = new ArrayList<>(); strs.add("hello"); strs.add("world"); for (String str : strs) { System.out.println(str); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/ArrayListTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
75
```java package jvmgo.book.ch09; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ArrayClassTest { public static void main(String[] args) { //Class<int[]> arrClass = int[].class; Class<?> arrClass = Object[].class; System.out.println(arrClass.getSuperclass()); for (Class<?> c : arrClass.getInterfaces()) { System.out.println(c); } for (Field f : arrClass.getDeclaredFields()) { System.out.println(f); } for (Method m : arrClass.getDeclaredMethods()) { System.out.println(m); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/ArrayClassTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
133
```java package jvmgo.book.ch09; public class ObjectTest { public static void main(String[] args) { Object obj1 = new ObjectTest(); Object obj2 = new ObjectTest(); System.out.println(obj1.hashCode()); System.out.println(obj1.toString()); System.out.println(obj1.equals(obj2)); System.out.println(obj1.equals(obj1)); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/ObjectTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
81
```java package jvmgo.book.ch09; public class GetClassTest { public static void main(String[] args) { System.out.println(void.class.getName()); // void System.out.println(boolean.class.getName()); // boolean System.out.println(byte.class.getName()); // byte System.out.println(char.class.getName()); // char System.out.println(short.class.getName()); // short System.out.println(int.class.getName()); // int System.out.println(long.class.getName()); // long System.out.println(float.class.getName()); // float System.out.println(double.class.getName()); // double System.out.println(Object.class.getName()); // java.lang.Object System.out.println(GetClassTest.class.getName()); // jvmgo.book.ch09.GetClassTest System.out.println(int[].class.getName()); // [I System.out.println(int[][].class.getName()); // [[I System.out.println(Object[].class.getName()); // [Ljava.lang.Object; System.out.println(Object[][].class.getName()); // [[Ljava.lang.Object; System.out.println(Runnable.class.getName()); // java.lang.Runnable System.out.println("abc".getClass().getName()); // java.lang.String System.out.println(new double[0].getClass().getName()); // [D System.out.println(new String[0].getClass().getName()); // [Ljava.lang.String; } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/GetClassTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
286
```java package jvmgo.book.ch09; public class StringBuilderTest { public static void main(String[] args) { String hello = "hello,"; String world = "world!"; String str = hello + world; System.out.println(str); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/StringBuilderTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
56
```java package jvmgo.book.ch09; import java.util.ArrayList; import java.util.List; public class BoxTest { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); System.out.println(list.toString()); for (int x : list) { System.out.println(x); } } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/BoxTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
88
```java package jvmgo.book.ch09; import java.util.HashMap; import java.util.Map; public class HashMapTest { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("abc", "123"); map.put("xyz", "987"); System.out.println(map.get("abc")); System.out.println(map.get("xyz")); System.out.println(map.toString()); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/HashMapTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
91
```java package jvmgo.book.ch09; public class CloneTest implements Cloneable { private double pi = 3.14; @Override public CloneTest clone() { try { return (CloneTest) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public static void main(String[] args) { CloneTest obj1 = new CloneTest(); CloneTest obj2 = obj1.clone(); obj1.pi = 3.1415926; System.out.println(obj1.pi); System.out.println(obj2.pi); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/CloneTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
130
```java package jvmgo.book.ch09; public class StringTest { public static void main(String[] args) { String s1 = "abc1"; String s2 = "abc1"; System.out.println(s1 == s2); int x = 1; String s3 = "abc" + x; System.out.println(s1 == s3); s3 = s3.intern(); System.out.println(s1 == s3); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/StringTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
104
```java package jvmgo.book.ch09; public class PrintlnTest { public static void main(String[] args) { System.out.println(false); System.out.println(true); System.out.println((byte)1); System.out.println((short)2); System.out.println('x'); System.out.println(3); System.out.println(4L); System.out.println(3.14f); System.out.println(3.14); System.out.println("abc"); } } ```
/content/code_sandbox/v1/code/java/example/src/main/java/jvmgo/book/ch09/PrintlnTest.java
java
2016-01-06T13:13:45
2024-08-16T13:42:58
jvmgo-book
zxh0/jvmgo-book
1,605
106
```qml /* */ import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.12 import QtQuick.Shapes 1.12 import QtMultimedia 5.12 import ZXing 1.0 Window { visible: true width: 640 height: 480 title: Qt.application.name property var nullPoints: [Qt.point(0,0), Qt.point(0,0), Qt.point(0,0), Qt.point(0,0)] property var points: nullPoints Timer { id: resetInfo interval: 1000 } BarcodeReader { id: barcodeReader formats: (linearSwitch.checked ? (ZXing.LinearCodes) : ZXing.None) | (matrixSwitch.checked ? (ZXing.MatrixCodes) : ZXing.None) tryRotate: tryRotateSwitch.checked tryHarder: tryHarderSwitch.checked tryInvert: tryInvertSwitch.checked tryDownscale: tryDownscaleSwitch.checked textMode: ZXing.HRI // callback with parameter 'barcode', called for every successfully processed frame onFoundBarcode: (barcode)=> { points = [barcode.position.topLeft, barcode.position.topRight, barcode.position.bottomRight, barcode.position.bottomLeft] info.text = qsTr("Format: \t %1 \nText: \t %2 \nType: \t %3 \nTime: \t %4 ms").arg(barcode.formatName).arg(barcode.text).arg(barcode.contentTypeName).arg(runTime) resetInfo.restart() // console.log(barcode) } // called for every processed frame where no barcode was detected onFailedRead: ()=> { points = nullPoints if (!resetInfo.running) info.text = "No barcode found (in %1 ms)".arg(runTime) } } Camera { id: camera captureMode: Camera.CaptureViewfinder deviceId: QtMultimedia.availableCameras[camerasComboBox.currentIndex] ? QtMultimedia.availableCameras[camerasComboBox.currentIndex].deviceId : "" onDeviceIdChanged: { focus.focusMode = CameraFocus.FocusContinuous focus.focusPointMode = CameraFocus.FocusPointAuto } onError: console.log("camera error:" + errorString) } ColumnLayout { anchors.fill: parent RowLayout { Layout.fillWidth: true Layout.fillHeight: false visible: QtMultimedia.availableCameras.length > 1 Label { text: qsTr("Camera: ") Layout.fillWidth: false } ComboBox { id: camerasComboBox Layout.fillWidth: true model: QtMultimedia.availableCameras textRole: "displayName" currentIndex: 0 } } VideoOutput { id: videoOutput Layout.fillHeight: true Layout.fillWidth: true filters: [barcodeReader] source: camera autoOrientation: true Shape { id: polygon anchors.fill: parent visible: points.length == 4 ShapePath { strokeWidth: 3 strokeColor: "red" strokeStyle: ShapePath.SolidLine fillColor: "transparent" //TODO: really? I don't know qml... startX: videoOutput.mapPointToItem(points[3]).x startY: videoOutput.mapPointToItem(points[3]).y PathLine { x: videoOutput.mapPointToItem(points[0]).x y: videoOutput.mapPointToItem(points[0]).y } PathLine { x: videoOutput.mapPointToItem(points[1]).x y: videoOutput.mapPointToItem(points[1]).y } PathLine { x: videoOutput.mapPointToItem(points[2]).x y: videoOutput.mapPointToItem(points[2]).y } PathLine { x: videoOutput.mapPointToItem(points[3]).x y: videoOutput.mapPointToItem(points[3]).y } } } Label { id: info color: "white" padding: 10 background: Rectangle { color: "#80808080" } } ColumnLayout { anchors.right: parent.right anchors.bottom: parent.bottom Switch {id: tryRotateSwitch; text: qsTr("Try Rotate"); checked: true } Switch {id: tryHarderSwitch; text: qsTr("Try Harder"); checked: true } Switch {id: tryInvertSwitch; text: qsTr("Try Invert"); checked: true } Switch {id: tryDownscaleSwitch; text: qsTr("Try Downscale"); checked: true } Switch {id: linearSwitch; text: qsTr("Linear Codes"); checked: true } Switch {id: matrixSwitch; text: qsTr("Matrix Codes"); checked: true } } } } } ```
/content/code_sandbox/example/ZXingQt5CamReader.qml
qml
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,157
```ruby Pod::Spec.new do |s| s.name = 'zxing-cpp' s.version = '2.2.0' s.summary = 'C++ port of ZXing' s.homepage = 'path_to_url s.author = 'axxel' s.readme = 'path_to_url s.license = { :file => 'LICENSE' } s.source = { :git => 'path_to_url :tag => "v#{s.version}" } s.module_name = 'ZXingCpp' s.platform = :ios, '11.0' s.library = ['c++'] s.compiler_flags = '-DZXING_READERS' s.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++20' } s.default_subspec = 'Wrapper' s.subspec 'Core' do |ss| ss.source_files = 'core/src/**/*.{h,c,cpp}' ss.exclude_files = [ 'core/src/libzint/**' ] ss.private_header_files = 'core/src/**/*.h' end s.subspec 'Wrapper' do |ss| ss.dependency 'zxing-cpp/Core' ss.frameworks = 'CoreGraphics', 'CoreImage', 'CoreVideo' ss.source_files = 'wrappers/ios/Sources/Wrapper/**/*.{h,m,mm}' ss.public_header_files = 'wrappers/ios/Sources/Wrapper/Reader/{ZXIBarcodeReader,ZXIResult,ZXIPosition,ZXIPoint,ZXIGTIN,ZXIReaderOptions}.h', 'wrappers/ios/Sources/Wrapper/Writer/{ZXIBarcodeWriter,ZXIWriterOptions}.h', 'wrappers/ios/Sources/Wrapper/{ZXIErrors,ZXIFormat}.h' ss.exclude_files = 'wrappers/ios/Sources/Wrapper/UmbrellaHeader.h' end end ```
/content/code_sandbox/zxing-cpp.podspec
ruby
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
424
```swift // swift-tools-version:5.7.1 import PackageDescription let package = Package( name: "ZXingCpp", platforms: [ .iOS(.v11) ], products: [ .library( name: "ZXingCpp", targets: ["ZXingCpp"]) ], targets: [ .target( name: "ZXingCppCore", path: "core/src", exclude: ["libzint"], publicHeadersPath: ".", cxxSettings: [ .define("ZXING_READERS") ] ), .target( name: "ZXingCpp", dependencies: ["ZXingCppCore"], path: "wrappers/ios/Sources/Wrapper", publicHeadersPath: ".", linkerSettings: [ .linkedFramework("CoreGraphics"), .linkedFramework("CoreImage"), .linkedFramework("CoreVideo") ] ) ], cxxLanguageStandard: CXXLanguageStandard.gnucxx20 ) ```
/content/code_sandbox/Package.swift
swift
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
219
```c++ /* */ #ifdef ZXING_EXPERIMENTAL_API #include "WriteBarcode.h" #else #include "BitMatrix.h" #include "BitMatrixIO.h" #include "CharacterSet.h" #include "MultiFormatWriter.h" #endif #include "Version.h" #include <algorithm> #include <cctype> #include <cstring> #include <fstream> #include <iostream> #include <string> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> using namespace ZXing; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [-size <width/height>] [-eclevel <level>] [-noqz] [-hrt] <format> <text> <output>\n" << " -size Size of generated image\n" // << " -margin Margin around barcode\n" // << " -encoding Encoding used to encode input text\n" << " -eclevel Error correction level, [0-8]\n" << " -binary Interpret <text> as a file name containing binary data\n" << " -noqz Print barcode witout quiet zone\n" << " -hrt Print human readable text below the barcode (if supported)\n" << " -help Print usage information\n" << " -version Print version information\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormatsFromString("Aztec Codabar Code39 Code93 Code128 DataMatrix EAN8 EAN13 ITF PDF417 QRCode UPCA UPCE")) std::cout << " " << ToString(f) << "\n"; std::cout << "Format can be lowercase letters, with or without '-'.\n" << "Output format is determined by file name, supported are png, jpg and svg.\n"; } static bool ParseSize(std::string str, int* width, int* height) { std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); }); auto xPos = str.find('x'); if (xPos != std::string::npos) { *width = std::stoi(str.substr(0, xPos)); *height = std::stoi(str.substr(xPos + 1)); return true; } return false; } struct CLI { BarcodeFormat format; int sizeHint = 0; std::string input; std::string outPath; std::string ecLevel; bool inputIsFile = false; bool withHRT = false; bool withQZ = true; bool verbose = false; // CharacterSet encoding = CharacterSet::Unknown; }; static bool ParseOptions(int argc, char* argv[], CLI& cli) { int nonOptArgCount = 0; for (int i = 1; i < argc; ++i) { auto is = [&](const char* str) { return strncmp(argv[i], str, strlen(argv[i])) == 0; }; if (is("-size")) { if (++i == argc) return false; cli.sizeHint = std::stoi(argv[i]); } else if (is("-eclevel")) { if (++i == argc) return false; cli.ecLevel = argv[i]; // } else if (is("-margin")) { // if (++i == argc) // return false; // cli.margin = std::stoi(argv[i]); // } else if (is("-encoding")) { // if (++i == argc) // return false; // cli.encoding = CharacterSetFromString(argv[i]); } else if (is("-binary")) { cli.inputIsFile = true; } else if (is("-hrt")) { cli.withHRT = true; } else if (is("-noqz")) { cli.withQZ = false; } else if (is("-verbose")) { cli.verbose = true; } else if (is("-help") || is("--help")) { PrintUsage(argv[0]); exit(0); } else if (is("-version") || is("--version")) { std::cout << "ZXingWriter " << ZXING_VERSION_STR << "\n"; exit(0); } else if (nonOptArgCount == 0) { cli.format = BarcodeFormatFromString(argv[i]); if (cli.format == BarcodeFormat::None) { std::cerr << "Unrecognized format: " << argv[i] << std::endl; return false; } ++nonOptArgCount; } else if (nonOptArgCount == 1) { cli.input = argv[i]; ++nonOptArgCount; } else if (nonOptArgCount == 2) { cli.outPath = argv[i]; ++nonOptArgCount; } else { return false; } } return nonOptArgCount == 3; } static std::string GetExtension(const std::string& path) { auto fileNameStart = path.find_last_of("/\\"); auto fileName = fileNameStart == std::string::npos ? path : path.substr(fileNameStart + 1); auto extStart = fileName.find_last_of('.'); auto ext = extStart == std::string::npos ? "" : fileName.substr(extStart + 1); std::transform(ext.begin(), ext.end(), ext.begin(), [](char c) { return std::tolower(c); }); return ext; } template <typename T = char> std::vector<T> ReadFile(const std::string& fn) { std::basic_ifstream<T> ifs(fn, std::ios::binary); if (!ifs.good()) throw std::runtime_error("failed to open/read file " + fn); return ifs ? std::vector(std::istreambuf_iterator<T>(ifs), std::istreambuf_iterator<T>()) : std::vector<T>(); }; int main(int argc, char* argv[]) { CLI cli; if (!ParseOptions(argc, argv, cli)) { PrintUsage(argv[0]); return -1; } try { #ifdef ZXING_EXPERIMENTAL_API auto cOpts = CreatorOptions(cli.format).ecLevel(cli.ecLevel); auto barcode = cli.inputIsFile ? CreateBarcodeFromBytes(ReadFile(cli.input), cOpts) : CreateBarcodeFromText(cli.input, cOpts); auto wOpts = WriterOptions().sizeHint(cli.sizeHint).withQuietZones(cli.withQZ).withHRT(cli.withHRT).rotate(0); auto bitmap = WriteBarcodeToImage(barcode, wOpts); if (cli.verbose) { std::cout << "Text: \"" << barcode.text() << "\"\n" << "Bytes: " << ToHex(barcode.bytes()) << "\n" << "Format: " << ToString(barcode.format()) << "\n" << "Identifier: " << barcode.symbologyIdentifier() << "\n" << "Content: " << ToString(barcode.contentType()) << "\n" << "HasECI: " << barcode.hasECI() << "\n" << "Position: " << ToString(barcode.position()) << "\n" << "Rotation: " << barcode.orientation() << " deg\n" << "IsMirrored: " << barcode.isMirrored() << "\n" << "IsInverted: " << barcode.isInverted() << "\n" << "ecLevel: " << barcode.ecLevel() << "\n"; std::cout << WriteBarcodeToUtf8(barcode); } #else auto writer = MultiFormatWriter(cli.format).setMargin(cli.withQZ ? 10 : 0); if (!cli.ecLevel.empty()) writer.setEccLevel(std::stoi(cli.ecLevel)); BitMatrix matrix; if (cli.inputIsFile) { auto file = ReadFile(cli.input); std::wstring bytes; for (uint8_t c : file) bytes.push_back(c); writer.setEncoding(CharacterSet::BINARY); matrix = writer.encode(bytes, cli.sizeHint, std::clamp(cli.sizeHint / 2, 50, 300)); } else { matrix = writer.encode(cli.input, cli.sizeHint, std::clamp(cli.sizeHint / 2, 50, 300)); } auto bitmap = ToMatrix<uint8_t>(matrix); #endif auto ext = GetExtension(cli.outPath); int success = 0; if (ext == "" || ext == "png") { success = stbi_write_png(cli.outPath.c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0); } else if (ext == "jpg" || ext == "jpeg") { success = stbi_write_jpg(cli.outPath.c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0); } else if (ext == "svg") { #ifdef ZXING_EXPERIMENTAL_API success = (std::ofstream(cli.outPath) << WriteBarcodeToSVG(barcode, wOpts)).good(); #else success = (std::ofstream(cli.outPath) << ToSVG(matrix)).good(); #endif } if (!success) { std::cerr << "Failed to write image: " << cli.outPath << std::endl; return -1; } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return -1; } return 0; } ```
/content/code_sandbox/example/ZXingWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,084
```cmake macro(zxing_add_package_stb) unset (STB_FOUND CACHE) if (ZXING_DEPENDENCIES STREQUAL "AUTO") find_package(PkgConfig) pkg_check_modules (STB IMPORTED_TARGET stb) elseif (ZXING_DEPENDENCIES STREQUAL "LOCAL") find_package(PkgConfig REQUIRED) pkg_check_modules (STB REQUIRED IMPORTED_TARGET stb) endif() if (NOT STB_FOUND) include(FetchContent) FetchContent_Declare (stb GIT_REPOSITORY path_to_url FetchContent_MakeAvailable (stb) add_library(stb::stb INTERFACE IMPORTED) target_include_directories(stb::stb INTERFACE ${stb_SOURCE_DIR}) else() add_library(stb::stb ALIAS PkgConfig::STB) endif() endmacro() macro(zxing_add_package name depname git_repo git_rev) unset(${name}_FOUND CACHE) # see path_to_url#commitcomment-66464026 if (ZXING_DEPENDENCIES STREQUAL "AUTO") find_package (${name} CONFIG) elseif (ZXING_DEPENDENCIES STREQUAL "LOCAL") find_package (${name} REQUIRED CONFIG) endif() if (NOT ${name}_FOUND) include(FetchContent) FetchContent_Declare (${depname} GIT_REPOSITORY ${git_repo} GIT_TAG ${git_rev}) if (${depname} STREQUAL "googletest") # Prevent overriding the parent project's compiler/linker settings on Windows set (gtest_force_shared_crt ON CACHE BOOL "" FORCE) endif() #FetchContent_MakeAvailable (${depname}) FetchContent_GetProperties(${depname}) if(NOT ${depname}_POPULATED) FetchContent_Populate(${depname}) add_subdirectory(${${depname}_SOURCE_DIR} ${${depname}_BINARY_DIR} EXCLUDE_FROM_ALL) # prevent installing of dependencies endif() set (${name}_POPULATED TRUE) # this is supposed to be done in MakeAvailable but it seems not to?!? endif() endmacro() ```
/content/code_sandbox/zxing.cmake
cmake
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
460
```unknown --- Language: Cpp Standard: c++17 BasedOnStyle: LLVM IndentWidth: 4 TabWidth: 4 UseTab: ForContinuationAndIndentation # ForIndentation AccessModifierOffset: -4 ColumnLimit: 135 #AlignConsecutiveAssignments: true AlignConsecutiveBitFields: true AlignEscapedNewlines: DontAlign AlignTrailingComments: true AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: Inline #AllowShortLambdasOnASingleLine: Inline AllowShortEnumsOnASingleLine: true AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakTemplateDeclarations: Yes BreakBeforeBraces: Custom BraceWrapping: AfterClass: true AfterEnum: true AfterStruct: true AfterUnion: true AfterFunction: true SplitEmptyFunction: false BreakBeforeBinaryOperators: NonAssignment BreakBeforeTernaryOperators: true ConstructorInitializerAllOnOneLineOrOnePerLine: true FixNamespaceComments: true IncludeBlocks: Regroup KeepEmptyLinesAtTheStartOfBlocks: false PointerAlignment: Left ReflowComments: true SortIncludes: true ```
/content/code_sandbox/.clang-format
unknown
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
288
```c++ /* */ #include "ZXingQtReader.h" #include <QDebug> using namespace ZXingQt; int main(int argc, char* argv[]) { if (argc != 2) { qDebug() << "Please supply exactly one image filename"; return 1; } QString filePath = argv[1]; QImage image = QImage(filePath); if (image.isNull()) { qDebug() << "Could not load the filename as an image:" << filePath; return 1; } auto options = ReaderOptions() .setFormats(BarcodeFormat::MatrixCodes) .setTryInvert(false) .setTextMode(TextMode::HRI) .setMaxNumberOfSymbols(10); auto barcodes = ReadBarcodes(image, options); for (auto& barcode : barcodes) { qDebug() << "Text: " << barcode.text(); qDebug() << "Format: " << barcode.format(); qDebug() << "Content:" << barcode.contentType(); qDebug() << ""; } return barcodes.isEmpty() ? 1 : 0; } ```
/content/code_sandbox/example/ZXingQtReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
228
```objective-c /* */ #pragma once #include "ReadBarcode.h" #include <QImage> #include <QDebug> #include <QMetaType> #include <QScopeGuard> #ifdef QT_MULTIMEDIA_LIB #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include <QAbstractVideoFilter> #else #include <QVideoFrame> #include <QVideoSink> #endif #include <QElapsedTimer> #endif // This is some sample code to start a discussion about how a minimal and header-only Qt wrapper/helper could look like. namespace ZXingQt { Q_NAMESPACE //TODO: find a better way to export these enums to QML than to duplicate their definition // #ifdef Q_MOC_RUN produces meta information in the moc output but it does end up working in qml #ifdef QT_QML_LIB enum class BarcodeFormat { None = 0, ///< Used as a return value if no valid barcode has been detected Aztec = (1 << 0), ///< Aztec Codabar = (1 << 1), ///< Codabar Code39 = (1 << 2), ///< Code39 Code93 = (1 << 3), ///< Code93 Code128 = (1 << 4), ///< Code128 DataBar = (1 << 5), ///< GS1 DataBar, formerly known as RSS 14 DataBarExpanded = (1 << 6), ///< GS1 DataBar Expanded, formerly known as RSS EXPANDED DataMatrix = (1 << 7), ///< DataMatrix EAN8 = (1 << 8), ///< EAN-8 EAN13 = (1 << 9), ///< EAN-13 ITF = (1 << 10), ///< ITF (Interleaved Two of Five) MaxiCode = (1 << 11), ///< MaxiCode PDF417 = (1 << 12), ///< PDF417 or QRCode = (1 << 13), ///< QR Code UPCA = (1 << 14), ///< UPC-A UPCE = (1 << 15), ///< UPC-E MicroQRCode = (1 << 16), ///< Micro QR Code RMQRCode = (1 << 17), ///< Rectangular Micro QR Code DXFilmEdge = (1 << 18), ///< DX Film Edge Barcode LinearCodes = Codabar | Code39 | Code93 | Code128 | EAN8 | EAN13 | ITF | DataBar | DataBarExpanded | DXFilmEdge | UPCA | UPCE, MatrixCodes = Aztec | DataMatrix | MaxiCode | PDF417 | QRCode | MicroQRCode | RMQRCode, }; enum class ContentType { Text, Binary, Mixed, GS1, ISO15434, UnknownECI }; enum class TextMode { Plain, ECI, HRI, Hex, Escaped }; #else using ZXing::BarcodeFormat; using ZXing::ContentType; using ZXing::TextMode; #endif using ZXing::ReaderOptions; using ZXing::Binarizer; using ZXing::BarcodeFormats; Q_ENUM_NS(BarcodeFormat) Q_ENUM_NS(ContentType) Q_ENUM_NS(TextMode) template<typename T, typename = decltype(ZXing::ToString(T()))> QDebug operator<<(QDebug dbg, const T& v) { return dbg.noquote() << QString::fromStdString(ToString(v)); } class Position : public ZXing::Quadrilateral<QPoint> { Q_GADGET Q_PROPERTY(QPoint topLeft READ topLeft) Q_PROPERTY(QPoint topRight READ topRight) Q_PROPERTY(QPoint bottomRight READ bottomRight) Q_PROPERTY(QPoint bottomLeft READ bottomLeft) using Base = ZXing::Quadrilateral<QPoint>; public: using Base::Base; }; class Barcode : private ZXing::Barcode { Q_GADGET Q_PROPERTY(BarcodeFormat format READ format) Q_PROPERTY(QString formatName READ formatName) Q_PROPERTY(QString text READ text) Q_PROPERTY(QByteArray bytes READ bytes) Q_PROPERTY(bool isValid READ isValid) Q_PROPERTY(ContentType contentType READ contentType) Q_PROPERTY(QString contentTypeName READ contentTypeName) Q_PROPERTY(Position position READ position) QString _text; QByteArray _bytes; Position _position; public: Barcode() = default; // required for qmetatype machinery explicit Barcode(ZXing::Barcode&& r) : ZXing::Barcode(std::move(r)) { _text = QString::fromStdString(ZXing::Barcode::text()); _bytes = QByteArray(reinterpret_cast<const char*>(ZXing::Barcode::bytes().data()), Size(ZXing::Barcode::bytes())); auto& pos = ZXing::Barcode::position(); auto qp = [&pos](int i) { return QPoint(pos[i].x, pos[i].y); }; _position = {qp(0), qp(1), qp(2), qp(3)}; } using ZXing::Barcode::isValid; BarcodeFormat format() const { return static_cast<BarcodeFormat>(ZXing::Barcode::format()); } ContentType contentType() const { return static_cast<ContentType>(ZXing::Barcode::contentType()); } QString formatName() const { return QString::fromStdString(ZXing::ToString(ZXing::Barcode::format())); } QString contentTypeName() const { return QString::fromStdString(ZXing::ToString(ZXing::Barcode::contentType())); } const QString& text() const { return _text; } const QByteArray& bytes() const { return _bytes; } const Position& position() const { return _position; } }; inline QList<Barcode> ZXBarcodesToQBarcodes(ZXing::Barcodes&& zxres) { QList<Barcode> res; for (auto&& r : zxres) #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) res.push_back(Barcode(std::move(r))); #else res.emplace_back(std::move(r)); #endif return res; } inline QList<Barcode> ReadBarcodes(const QImage& img, const ReaderOptions& opts = {}) { using namespace ZXing; auto ImgFmtFromQImg = [](const QImage& img) { switch (img.format()) { case QImage::Format_ARGB32: case QImage::Format_RGB32: #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN return ImageFormat::BGRA; #else return ImageFormat::ARGB; #endif case QImage::Format_RGB888: return ImageFormat::RGB; case QImage::Format_RGBX8888: case QImage::Format_RGBA8888: return ImageFormat::RGBA; case QImage::Format_Grayscale8: return ImageFormat::Lum; default: return ImageFormat::None; } }; auto exec = [&](const QImage& img) { return ZXBarcodesToQBarcodes(ZXing::ReadBarcodes( {img.bits(), img.width(), img.height(), ImgFmtFromQImg(img), static_cast<int>(img.bytesPerLine())}, opts)); }; return ImgFmtFromQImg(img) == ImageFormat::None ? exec(img.convertToFormat(QImage::Format_Grayscale8)) : exec(img); } inline Barcode ReadBarcode(const QImage& img, const ReaderOptions& opts = {}) { auto res = ReadBarcodes(img, ReaderOptions(opts).setMaxNumberOfSymbols(1)); return !res.isEmpty() ? res.takeFirst() : Barcode(); } #ifdef QT_MULTIMEDIA_LIB inline QList<Barcode> ReadBarcodes(const QVideoFrame& frame, const ReaderOptions& opts = {}) { using namespace ZXing; ImageFormat fmt = ImageFormat::None; int pixStride = 0; int pixOffset = 0; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #define FORMAT(F5, F6) QVideoFrame::Format_##F5 #define FIRST_PLANE #else #define FORMAT(F5, F6) QVideoFrameFormat::Format_##F6 #define FIRST_PLANE 0 #endif switch (frame.pixelFormat()) { case FORMAT(ARGB32, ARGB8888): case FORMAT(ARGB32_Premultiplied, ARGB8888_Premultiplied): case FORMAT(RGB32, RGBX8888): #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN fmt = ImageFormat::BGRA; #else fmt = ImageFormat::ARGB; #endif break; case FORMAT(BGRA32, BGRA8888): case FORMAT(BGRA32_Premultiplied, BGRA8888_Premultiplied): case FORMAT(BGR32, BGRX8888): #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN fmt = ImageFormat::RGBA; #else fmt = ImageFormat::ABGR; #endif break; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) case QVideoFrame::Format_RGB24: fmt = ImageFormat::RGB; break; case QVideoFrame::Format_BGR24: fmt = ImageFormat::BGR; break; case QVideoFrame::Format_YUV444: fmt = ImageFormat::Lum, pixStride = 3; break; #else case QVideoFrameFormat::Format_P010: case QVideoFrameFormat::Format_P016: fmt = ImageFormat::Lum, pixStride = 1; break; #endif case FORMAT(AYUV444, AYUV): case FORMAT(AYUV444_Premultiplied, AYUV_Premultiplied): #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN fmt = ImageFormat::Lum, pixStride = 4, pixOffset = 3; #else fmt = ImageFormat::Lum, pixStride = 4, pixOffset = 2; #endif break; case FORMAT(YUV420P, YUV420P): case FORMAT(NV12, NV12): case FORMAT(NV21, NV21): case FORMAT(IMC1, IMC1): case FORMAT(IMC2, IMC2): case FORMAT(IMC3, IMC3): case FORMAT(IMC4, IMC4): case FORMAT(YV12, YV12): fmt = ImageFormat::Lum; break; case FORMAT(UYVY, UYVY): fmt = ImageFormat::Lum, pixStride = 2, pixOffset = 1; break; case FORMAT(YUYV, YUYV): fmt = ImageFormat::Lum, pixStride = 2; break; case FORMAT(Y8, Y8): fmt = ImageFormat::Lum; break; case FORMAT(Y16, Y16): fmt = ImageFormat::Lum, pixStride = 2, pixOffset = 1; break; #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) case FORMAT(ABGR32, ABGR8888): #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN fmt = ImageFormat::RGBA; #else fmt = ImageFormat::ABGR; #endif break; #endif #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) case FORMAT(YUV422P, YUV422P): fmt = ImageFormat::Lum; break; #endif default: break; } if (fmt != ImageFormat::None) { auto img = frame; // shallow copy just get access to non-const map() function #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) if (!img.isValid() || !img.map(QAbstractVideoBuffer::ReadOnly)){ #else if (!img.isValid() || !img.map(QVideoFrame::ReadOnly)){ #endif qWarning() << "invalid QVideoFrame: could not map memory"; return {}; } QScopeGuard unmap([&] { img.unmap(); }); return ZXBarcodesToQBarcodes(ZXing::ReadBarcodes( {img.bits(FIRST_PLANE) + pixOffset, img.width(), img.height(), fmt, img.bytesPerLine(FIRST_PLANE), pixStride}, opts)); } else { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) if (QVideoFrame::imageFormatFromPixelFormat(frame.pixelFormat()) != QImage::Format_Invalid) { qWarning() << "unsupported QVideoFrame::pixelFormat"; return {}; } auto qimg = frame.image(); #else auto qimg = frame.toImage(); #endif if (qimg.format() != QImage::Format_Invalid) return ReadBarcodes(qimg, opts); qWarning() << "failed to convert QVideoFrame to QImage"; return {}; } } inline Barcode ReadBarcode(const QVideoFrame& frame, const ReaderOptions& opts = {}) { auto res = ReadBarcodes(frame, ReaderOptions(opts).setMaxNumberOfSymbols(1)); return !res.isEmpty() ? res.takeFirst() : Barcode(); } #define ZQ_PROPERTY(Type, name, setter) \ public: \ Q_PROPERTY(Type name READ name WRITE setter NOTIFY name##Changed) \ Type name() const noexcept { return ReaderOptions::name(); } \ Q_SLOT void setter(const Type& newVal) \ { \ if (name() != newVal) { \ ReaderOptions::setter(newVal); \ emit name##Changed(); \ } \ } \ Q_SIGNAL void name##Changed(); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) class BarcodeReader : public QAbstractVideoFilter, private ReaderOptions #else class BarcodeReader : public QObject, private ReaderOptions #endif { Q_OBJECT public: #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) BarcodeReader(QObject* parent = nullptr) : QAbstractVideoFilter(parent) {} #else BarcodeReader(QObject* parent = nullptr) : QObject(parent) {} #endif // TODO: find out how to properly expose QFlags to QML // simply using ZQ_PROPERTY(BarcodeFormats, formats, setFormats) // results in the runtime error "can't assign int to formats" Q_PROPERTY(int formats READ formats WRITE setFormats NOTIFY formatsChanged) int formats() const noexcept { auto fmts = ReaderOptions::formats(); return *reinterpret_cast<int*>(&fmts); } Q_SLOT void setFormats(int newVal) { if (formats() != newVal) { ReaderOptions::setFormats(static_cast<ZXing::BarcodeFormat>(newVal)); emit formatsChanged(); qDebug() << ReaderOptions::formats(); } } Q_SIGNAL void formatsChanged(); Q_PROPERTY(TextMode textMode READ textMode WRITE setTextMode NOTIFY textModeChanged) TextMode textMode() const noexcept { return static_cast<TextMode>(ReaderOptions::textMode()); } Q_SLOT void setTextMode(TextMode newVal) { if (textMode() != newVal) { ReaderOptions::setTextMode(static_cast<ZXing::TextMode>(newVal)); emit textModeChanged(); } } Q_SIGNAL void textModeChanged(); ZQ_PROPERTY(bool, tryRotate, setTryRotate) ZQ_PROPERTY(bool, tryHarder, setTryHarder) ZQ_PROPERTY(bool, tryInvert, setTryInvert) ZQ_PROPERTY(bool, tryDownscale, setTryDownscale) ZQ_PROPERTY(bool, isPure, setIsPure) // For debugging/development int runTime = 0; Q_PROPERTY(int runTime MEMBER runTime) public slots: ZXingQt::Barcode process(const QVideoFrame& image) { QElapsedTimer t; t.start(); auto res = ReadBarcode(image, *this); runTime = t.elapsed(); if (res.isValid()) emit foundBarcode(res); else emit failedRead(); return res; } signals: void failedRead(); void foundBarcode(ZXingQt::Barcode barcode); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) public: QVideoFilterRunnable *createFilterRunnable() override; #else private: QVideoSink *_sink = nullptr; public: void setVideoSink(QVideoSink* sink) { if (_sink == sink) return; if (_sink) disconnect(_sink, nullptr, this, nullptr); _sink = sink; connect(_sink, &QVideoSink::videoFrameChanged, this, &BarcodeReader::process); } Q_PROPERTY(QVideoSink* videoSink MEMBER _sink WRITE setVideoSink) #endif }; #undef ZX_PROPERTY #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) class VideoFilterRunnable : public QVideoFilterRunnable { BarcodeReader* _filter = nullptr; public: explicit VideoFilterRunnable(BarcodeReader* filter) : _filter(filter) {} QVideoFrame run(QVideoFrame* input, const QVideoSurfaceFormat& /*surfaceFormat*/, RunFlags /*flags*/) override { _filter->process(*input); return *input; } }; inline QVideoFilterRunnable* BarcodeReader::createFilterRunnable() { return new VideoFilterRunnable(this); } #endif #endif // QT_MULTIMEDIA_LIB } // namespace ZXingQt Q_DECLARE_METATYPE(ZXingQt::Position) Q_DECLARE_METATYPE(ZXingQt::Barcode) #ifdef QT_QML_LIB #include <QQmlEngine> namespace ZXingQt { inline void registerQmlAndMetaTypes() { qRegisterMetaType<ZXingQt::BarcodeFormat>("BarcodeFormat"); qRegisterMetaType<ZXingQt::ContentType>("ContentType"); qRegisterMetaType<ZXingQt::TextMode>("TextMode"); // supposedly the Q_DECLARE_METATYPE should be used with the overload without a custom name // but then the qml side complains about "unregistered type" qRegisterMetaType<ZXingQt::Position>("Position"); qRegisterMetaType<ZXingQt::Barcode>("Barcode"); qmlRegisterUncreatableMetaObject( ZXingQt::staticMetaObject, "ZXing", 1, 0, "ZXing", "Access to enums & flags only"); qmlRegisterType<ZXingQt::BarcodeReader>("ZXing", 1, 0, "BarcodeReader"); } } // namespace ZXingQt #endif // QT_QML_LIB ```
/content/code_sandbox/example/ZXingQtReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,867
```c++ /* */ #include "ZXingOpenCV.h" #include <iostream> using namespace cv; int main() { namedWindow("Display window"); Mat image; VideoCapture cap(0); if (!cap.isOpened()) std::cout << "cannot open camera"; else while (waitKey(25) != 27) { cap >> image; auto barcodes = ReadBarcodes(image); for (auto& barcode : barcodes) DrawBarcode(image, barcode); imshow("Display window", image); } return 0; } ```
/content/code_sandbox/example/ZXingOpenCV.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
121
```c++ /* */ #include "GTIN.h" #include "ReadBarcode.h" #include "Version.h" #ifdef ZXING_EXPERIMENTAL_API #include "WriteBarcode.h" #endif #include <cctype> #include <chrono> #include <cstring> #include <iostream> #include <iterator> #include <memory> #include <string> #include <vector> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> using namespace ZXing; struct CLI { std::vector<std::string> filePaths; std::string outPath; int forceChannels = 0; int rotate = 0; bool oneLine = false; bool bytesOnly = false; bool showSymbol = false; }; static void PrintUsage(const char* exePath) { std::cout << "Usage: " << exePath << " [options] <image file>...\n" << " -fast Skip some lines/pixels during detection (faster)\n" << " -norotate Don't try rotated image during detection (faster)\n" << " -noinvert Don't search for inverted codes during detection (faster)\n" << " -noscale Don't try downscaled images during detection (faster)\n" << " -formats <FORMAT[,...]>\n" << " Only detect given format(s) (faster)\n" << " -single Stop after the first barcode is detected (faster)\n" << " -ispure Assume the image contains only a 'pure'/perfect code (faster)\n" << " -errors Include barcodes with errors (like checksum error)\n" << " -binarizer <local|global|fixed>\n" << " Binarizer to be used for gray to binary conversion\n" << " -mode <plain|eci|hri|escaped>\n" << " Text mode used to render the raw byte content into text\n" << " -1 Print only file name, content/error on one line per file/barcode (implies '-mode Escaped')\n" #ifdef ZXING_EXPERIMENTAL_API << " -symbol Print the detected symbol (if available)\n" #endif << " -bytes Write (only) the bytes content of the symbol(s) to stdout\n" << " -pngout <file name>\n" << " Write a copy of the input image with barcodes outlined by a green line\n" << " -help Print usage information\n" << " -version Print version information\n" << "\n" << "Supported formats are:\n"; for (auto f : BarcodeFormats::all()) { std::cout << " " << ToString(f) << "\n"; } std::cout << "Formats can be lowercase, with or without '-', separated by ',' and/or '|'\n"; } static bool ParseOptions(int argc, char* argv[], ReaderOptions& options, CLI& cli) { #ifdef ZXING_EXPERIMENTAL_API options.setTryDenoise(true); #endif for (int i = 1; i < argc; ++i) { auto is = [&](const char* str) { return strncmp(argv[i], str, strlen(argv[i])) == 0; }; if (is("-fast")) { options.setTryHarder(false); #ifdef ZXING_EXPERIMENTAL_API options.setTryDenoise(false); #endif } else if (is("-norotate")) { options.setTryRotate(false); } else if (is("-noinvert")) { options.setTryInvert(false); } else if (is("-noscale")) { options.setTryDownscale(false); } else if (is("-single")) { options.setMaxNumberOfSymbols(1); } else if (is("-ispure")) { options.setIsPure(true); options.setBinarizer(Binarizer::FixedThreshold); } else if (is("-errors")) { options.setReturnErrors(true); } else if (is("-formats")) { if (++i == argc) return false; try { options.setFormats(BarcodeFormatsFromString(argv[i])); } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return false; } } else if (is("-binarizer")) { if (++i == argc) return false; else if (is("local")) options.setBinarizer(Binarizer::LocalAverage); else if (is("global")) options.setBinarizer(Binarizer::GlobalHistogram); else if (is("fixed")) options.setBinarizer(Binarizer::FixedThreshold); else return false; } else if (is("-mode")) { if (++i == argc) return false; else if (is("plain")) options.setTextMode(TextMode::Plain); else if (is("eci")) options.setTextMode(TextMode::ECI); else if (is("hri")) options.setTextMode(TextMode::HRI); else if (is("escaped")) options.setTextMode(TextMode::Escaped); else return false; } else if (is("-1")) { cli.oneLine = true; } else if (is("-bytes")) { cli.bytesOnly = true; } else if (is("-symbol")) { cli.showSymbol = true; } else if (is("-pngout")) { if (++i == argc) return false; cli.outPath = argv[i]; } else if (is("-channels")) { if (++i == argc) return false; cli.forceChannels = atoi(argv[i]); } else if (is("-rotate")) { if (++i == argc) return false; cli.rotate = atoi(argv[i]); } else if (is("-help") || is("--help")) { PrintUsage(argv[0]); exit(0); } else if (is("-version") || is("--version")) { std::cout << "ZXingReader " << ZXING_VERSION_STR << "\n"; exit(0); } else { cli.filePaths.push_back(argv[i]); } } return !cli.filePaths.empty(); } void drawLine(const ImageView& iv, PointI a, PointI b, bool error) { int steps = maxAbsComponent(b - a); PointF dir = bresenhamDirection(PointF(b - a)); int R = RedIndex(iv.format()), G = GreenIndex(iv.format()), B = BlueIndex(iv.format()); for (int i = 0; i < steps; ++i) { auto p = PointI(centered(a + i * dir)); auto* dst = const_cast<uint8_t*>(iv.data(p.x, p.y)); if (dst < iv.data(0, 0) || dst > iv.data(iv.width() - 1, iv.height() - 1)) continue; dst[R] = error ? 0xff : 0; dst[G] = error ? 0 : 0xff; dst[B] = 0; } } void drawRect(const ImageView& image, const Position& pos, bool error) { for (int i = 0; i < 4; ++i) drawLine(image, pos[i], pos[(i + 1) % 4], error); } int main(int argc, char* argv[]) { ReaderOptions options; CLI cli; Barcodes allBarcodes; int ret = 0; options.setTextMode(TextMode::HRI); options.setEanAddOnSymbol(EanAddOnSymbol::Read); if (!ParseOptions(argc, argv, options, cli)) { PrintUsage(argv[0]); return -1; } std::cout.setf(std::ios::boolalpha); if (!cli.outPath.empty()) cli.forceChannels = 3; // the drawing code only works for RGB data for (const auto& filePath : cli.filePaths) { int width, height, channels; std::unique_ptr<stbi_uc, void (*)(void*)> buffer(stbi_load(filePath.c_str(), &width, &height, &channels, cli.forceChannels), stbi_image_free); if (buffer == nullptr) { std::cerr << "Failed to read image: " << filePath << " (" << stbi_failure_reason() << ")" << "\n"; return -1; } channels = cli.forceChannels ? cli.forceChannels : channels; auto ImageFormatFromChannels = std::array{ImageFormat::None, ImageFormat::Lum, ImageFormat::LumA, ImageFormat::RGB, ImageFormat::RGBA}; ImageView image{buffer.get(), width, height, ImageFormatFromChannels.at(channels)}; auto barcodes = ReadBarcodes(image.rotated(cli.rotate), options); // if we did not find anything, insert a dummy to produce some output for each file if (barcodes.empty()) barcodes.emplace_back(); allBarcodes.insert(allBarcodes.end(), barcodes.begin(), barcodes.end()); if (filePath == cli.filePaths.back()) { auto merged = MergeStructuredAppendSequences(allBarcodes); // report all merged sequences as part of the last file to make the logic not overly complicated here barcodes.insert(barcodes.end(), std::make_move_iterator(merged.begin()), std::make_move_iterator(merged.end())); } for (auto&& barcode : barcodes) { if (!cli.outPath.empty()) drawRect(image, barcode.position(), bool(barcode.error())); ret |= static_cast<int>(barcode.error().type()); if (cli.bytesOnly) { std::cout.write(reinterpret_cast<const char*>(barcode.bytes().data()), barcode.bytes().size()); continue; } if (cli.oneLine) { std::cout << filePath << " " << ToString(barcode.format()); if (barcode.isValid()) std::cout << " \"" << barcode.text(TextMode::Escaped) << "\""; else if (barcode.error()) std::cout << " " << ToString(barcode.error()); std::cout << "\n"; continue; } if (cli.filePaths.size() > 1 || barcodes.size() > 1) { static bool firstFile = true; if (!firstFile) std::cout << "\n"; if (cli.filePaths.size() > 1) std::cout << "File: " << filePath << "\n"; firstFile = false; } if (barcode.format() == BarcodeFormat::None) { std::cout << "No barcode found\n"; continue; } std::cout << "Text: \"" << barcode.text() << "\"\n" << "Bytes: " << ToHex(options.textMode() == TextMode::ECI ? barcode.bytesECI() : barcode.bytes()) << "\n" << "Format: " << ToString(barcode.format()) << "\n" << "Identifier: " << barcode.symbologyIdentifier() << "\n" << "Content: " << ToString(barcode.contentType()) << "\n" << "HasECI: " << barcode.hasECI() << "\n" << "Position: " << ToString(barcode.position()) << "\n" << "Rotation: " << barcode.orientation() << " deg\n" << "IsMirrored: " << barcode.isMirrored() << "\n" << "IsInverted: " << barcode.isInverted() << "\n"; auto printOptional = [](const char* key, const std::string& v) { if (!v.empty()) std::cout << key << v << "\n"; }; printOptional("EC Level: ", barcode.ecLevel()); printOptional("Version: ", barcode.version()); printOptional("Error: ", ToString(barcode.error())); if (barcode.lineCount()) std::cout << "Lines: " << barcode.lineCount() << "\n"; if ((BarcodeFormat::EAN13 | BarcodeFormat::EAN8 | BarcodeFormat::UPCA | BarcodeFormat::UPCE) .testFlag(barcode.format())) { printOptional("Country: ", GTIN::LookupCountryIdentifier(barcode.text(), barcode.format())); printOptional("Add-On: ", GTIN::EanAddOn(barcode)); printOptional("Price: ", GTIN::Price(GTIN::EanAddOn(barcode))); printOptional("Issue #: ", GTIN::IssueNr(GTIN::EanAddOn(barcode))); } else if (barcode.format() == BarcodeFormat::ITF && Size(barcode.bytes()) == 14) { printOptional("Country: ", GTIN::LookupCountryIdentifier(barcode.text(), barcode.format())); } if (barcode.isPartOfSequence()) std::cout << "Structured Append: symbol " << barcode.sequenceIndex() + 1 << " of " << barcode.sequenceSize() << " (parity/id: '" << barcode.sequenceId() << "')\n"; else if (barcode.sequenceSize() > 0) std::cout << "Structured Append: merged result from " << barcode.sequenceSize() << " symbols (parity/id: '" << barcode.sequenceId() << "')\n"; if (barcode.readerInit()) std::cout << "Reader Initialisation/Programming\n"; #ifdef ZXING_EXPERIMENTAL_API if (cli.showSymbol && barcode.symbol().data()) std::cout << "Symbol:\n" << WriteBarcodeToUtf8(barcode); #endif } if (Size(cli.filePaths) == 1 && !cli.outPath.empty()) stbi_write_png(cli.outPath.c_str(), image.width(), image.height(), 3, image.data(), image.rowStride()); #ifdef NDEBUG if (getenv("MEASURE_PERF")) { auto startTime = std::chrono::high_resolution_clock::now(); auto duration = startTime - startTime; int N = 0; int blockSize = 1; do { for (int i = 0; i < blockSize; ++i) ReadBarcodes(image, options); N += blockSize; duration = std::chrono::high_resolution_clock::now() - startTime; if (blockSize < 1000 && duration < std::chrono::milliseconds(100)) blockSize *= 10; } while (duration < std::chrono::seconds(1)); printf("time: %5.2f ms per frame\n", double(std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()) / N); } #endif } return ret; } ```
/content/code_sandbox/example/ZXingReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,232
```objective-c /* */ #pragma once #include "ReadBarcode.h" #include <opencv2/opencv.hpp> inline ZXing::ImageView ImageViewFromMat(const cv::Mat& image) { using ZXing::ImageFormat; auto fmt = ImageFormat::None; switch (image.channels()) { case 1: fmt = ImageFormat::Lum; break; case 2: fmt = ImageFormat::LumA; break; case 3: fmt = ImageFormat::BGR; break; case 4: fmt = ImageFormat::BGRA; break; } if (image.depth() != CV_8U || fmt == ImageFormat::None) return {nullptr, 0, 0, ImageFormat::None}; return {image.data, image.cols, image.rows, fmt}; } inline ZXing::Barcodes ReadBarcodes(const cv::Mat& image, const ZXing::ReaderOptions& options = {}) { return ZXing::ReadBarcodes(ImageViewFromMat(image), options); } inline void DrawBarcode(cv::Mat& img, ZXing::Barcode barcode) { auto pos = barcode.position(); auto zx2cv = [](ZXing::PointI p) { return cv::Point(p.x, p.y); }; auto contour = std::vector<cv::Point>{zx2cv(pos[0]), zx2cv(pos[1]), zx2cv(pos[2]), zx2cv(pos[3])}; const auto* pts = contour.data(); int npts = contour.size(); cv::polylines(img, &pts, &npts, 1, true, CV_RGB(0, 255, 0)); cv::putText(img, barcode.text(), zx2cv(pos[3]) + cv::Point(0, 20), cv::FONT_HERSHEY_DUPLEX, 0.5, CV_RGB(0, 255, 0)); } ```
/content/code_sandbox/example/ZXingOpenCV.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
390
```unknown <RCC> <qresource prefix="/"> <file>ZXingQt5CamReader.qml</file> <file>ZXingQt6CamReader.qml</file> </qresource> </RCC> ```
/content/code_sandbox/example/ZXingQtCamReader.qrc
unknown
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
47
```qml /* */ import QtQuick import QtQuick.Window import QtQuick.Controls import QtQuick.Layouts import QtQuick.Shapes import QtMultimedia import ZXing Window { visible: true width: 640 height: 480 title: Qt.application.name property var nullPoints: [Qt.point(0,0), Qt.point(0,0), Qt.point(0,0), Qt.point(0,0)] property var points: nullPoints Timer { id: resetInfo interval: 1000 } BarcodeReader { id: barcodeReader videoSink: videoOutput.videoSink formats: (linearSwitch.checked ? (ZXing.LinearCodes) : ZXing.None) | (matrixSwitch.checked ? (ZXing.MatrixCodes) : ZXing.None) tryRotate: tryRotateSwitch.checked tryHarder: tryHarderSwitch.checked tryInvert: tryInvertSwitch.checked tryDownscale: tryDownscaleSwitch.checked textMode: ZXing.TextMode.HRI // callback with parameter 'barcode', called for every successfully processed frame onFoundBarcode: (barcode)=> { points = [barcode.position.topLeft, barcode.position.topRight, barcode.position.bottomRight, barcode.position.bottomLeft] info.text = qsTr("Format: \t %1 \nText: \t %2 \nType: \t %3 \nTime: \t %4 ms").arg(barcode.formatName).arg(barcode.text).arg(barcode.contentTypeName).arg(runTime) resetInfo.restart() // console.log(barcode) } // called for every processed frame where no barcode was detected onFailedRead: ()=> { points = nullPoints if (!resetInfo.running) info.text = "No barcode found (in %1 ms)".arg(runTime) } } MediaDevices { id: devices } Camera { id: camera cameraDevice: devices.videoInputs[camerasComboBox.currentIndex] ? devices.videoInputs[camerasComboBox.currentIndex] : devices.defaultVideoInput focusMode: Camera.FocusModeAutoNear onErrorOccurred: console.log("camera error:" + errorString) active: true } CaptureSession { id: captureSession camera: camera videoOutput: videoOutput } ColumnLayout { anchors.fill: parent RowLayout { Layout.fillWidth: true Layout.fillHeight: false visible: devices.videoInputs.length > 1 Label { text: qsTr("Camera: ") Layout.fillWidth: false } ComboBox { id: camerasComboBox Layout.fillWidth: true model: devices.videoInputs textRole: "description" currentIndex: 0 } } VideoOutput { id: videoOutput Layout.fillHeight: true Layout.fillWidth: true function mapPointToItem(point) { if (videoOutput.sourceRect.width === 0 || videoOutput.sourceRect.height === 0) return Qt.point(0, 0); let dx = point.x; let dy = point.y; if ((videoOutput.orientation % 180) == 0) { dx = dx * videoOutput.contentRect.width / videoOutput.sourceRect.width; dy = dy * videoOutput.contentRect.height / videoOutput.sourceRect.height; } else { dx = dx * videoOutput.contentRect.height / videoOutput.sourceRect.height; dy = dx * videoOutput.contentRect.width / videoOutput.sourceRect.width; } switch ((videoOutput.orientation + 360) % 360) { case 0: default: return Qt.point(videoOutput.contentRect.x + dx, videoOutput.contentRect.y + dy); case 90: return Qt.point(videoOutput.contentRect.x + dy, videoOutput.contentRect.y + videoOutput.contentRect.height - dx); case 180: return Qt.point(videoOutput.contentRect.x + videoOutput.contentRect.width - dx, videoOutput.contentRect.y + videoOutput.contentRect.height -dy); case 270: return Qt.point(videoOutput.contentRect.x + videoOutput.contentRect.width - dy, videoOutput.contentRect.y + dx); } } Shape { id: polygon anchors.fill: parent visible: points.length === 4 ShapePath { strokeWidth: 3 strokeColor: "red" strokeStyle: ShapePath.SolidLine fillColor: "transparent" //TODO: really? I don't know qml... startX: videoOutput.mapPointToItem(points[3]).x startY: videoOutput.mapPointToItem(points[3]).y PathLine { x: videoOutput.mapPointToItem(points[0]).x y: videoOutput.mapPointToItem(points[0]).y } PathLine { x: videoOutput.mapPointToItem(points[1]).x y: videoOutput.mapPointToItem(points[1]).y } PathLine { x: videoOutput.mapPointToItem(points[2]).x y: videoOutput.mapPointToItem(points[2]).y } PathLine { x: videoOutput.mapPointToItem(points[3]).x y: videoOutput.mapPointToItem(points[3]).y } } } Label { id: info color: "white" padding: 10 background: Rectangle { color: "#80808080" } } ColumnLayout { anchors.right: parent.right anchors.bottom: parent.bottom Switch {id: tryRotateSwitch; text: qsTr("Try Rotate"); checked: true } Switch {id: tryHarderSwitch; text: qsTr("Try Harder"); checked: true } Switch {id: tryInvertSwitch; text: qsTr("Try Invert"); checked: true } Switch {id: tryDownscaleSwitch; text: qsTr("Try Downscale"); checked: true } Switch {id: linearSwitch; text: qsTr("Linear Codes"); checked: true } Switch {id: matrixSwitch; text: qsTr("Matrix Codes"); checked: true } } } } } ```
/content/code_sandbox/example/ZXingQt6CamReader.qml
qml
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,424
```c++ /* */ #include <QGuiApplication> #include <QQmlApplicationEngine> #include "ZXingQtReader.h" int main(int argc, char *argv[]) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif ZXingQt::registerQmlAndMetaTypes(); QGuiApplication app(argc, argv); app.setApplicationName("ZXingQtCamReader"); QQmlApplicationEngine engine; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) engine.load(QUrl(QStringLiteral("qrc:/ZXingQt5CamReader.qml"))); #else engine.load(QUrl(QStringLiteral("qrc:/ZXingQt6CamReader.qml"))); #endif if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } ```
/content/code_sandbox/example/ZXingQtCamReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
175
```unknown @PACKAGE_INIT@ include("${CMAKE_CURRENT_LIST_DIR}/ZXingTargets.cmake") # this does not work: add_library(ZXing::Core ALIAS ZXing::ZXing) # this is a workaround available since 3.11 : if(NOT(CMAKE_VERSION VERSION_LESS 3.11)) add_library(ZXing::Core INTERFACE IMPORTED) target_link_libraries(ZXing::Core INTERFACE ZXing::ZXing) endif() ```
/content/code_sandbox/core/ZXingConfig.cmake.in
unknown
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
96
```c++ /* */ #include "BarcodeFormat.h" #ifdef ZXING_EXPERIMENTAL_API #include "WriteBarcode.h" #else #include "BitMatrix.h" #include "MultiFormatWriter.h" #endif #include <QDebug> #include <QImage> namespace ZXingQt { QImage WriteBarcode(QStringView text, ZXing::BarcodeFormat format) { using namespace ZXing; #ifdef ZXING_EXPERIMENTAL_API auto barcode = CreateBarcodeFromText(text.toString().toStdString(), format); auto bitmap = WriteBarcodeToImage(barcode); #else auto writer = MultiFormatWriter(format); auto matrix = writer.encode(text.toString().toStdString(), 0, 0); auto bitmap = ToMatrix<uint8_t>(matrix); #endif return QImage(bitmap.data(), bitmap.width(), bitmap.height(), bitmap.width(), QImage::Format::Format_Grayscale8).copy(); } } // namespace ZXingQt int main(int argc, char* argv[]) { if (argc != 4) { qDebug() << "usage: ZXingQtWriter <format> <text> <filename>"; return 1; } auto format = ZXing::BarcodeFormatFromString(argv[1]); auto text = QString(argv[2]); auto filename = QString(argv[3]); auto result = ZXingQt::WriteBarcode(text, format); result.save(filename); return 0; } ```
/content/code_sandbox/example/ZXingQtWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
281
```unknown /* */ #pragma once #cmakedefine ZXING_READERS #cmakedefine ZXING_WRITERS // Version numbering #define ZXING_VERSION_MAJOR @PROJECT_VERSION_MAJOR@ #define ZXING_VERSION_MINOR @PROJECT_VERSION_MINOR@ #define ZXING_VERSION_PATCH @PROJECT_VERSION_PATCH@ #define ZXING_VERSION_STR "@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@" ```
/content/code_sandbox/core/Version.h.in
unknown
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
81
```unknown libdir=@CMAKE_INSTALL_FULL_LIBDIR@ includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ Name: ZXing Description: ZXing-C++ library Version: @PROJECT_VERSION@ Libs: -L${libdir} -lZXing Cflags: -I${includedir} -I${includedir}/ZXing ```
/content/code_sandbox/core/zxing.pc.in
unknown
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
72
```objective-c #pragma once #ifdef ZXING_BUILD_FOR_TEST #define ZXING_EXPORT_TEST_ONLY #define ZXING_IF_NOT_TEST(x) #else #define ZXING_EXPORT_TEST_ONLY static #define ZXING_IF_NOT_TEST(x) x #endif ```
/content/code_sandbox/core/src/ZXTestSupport.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
48
```objective-c /* */ #pragma once #include "Flags.h" #include <string> #include <string_view> namespace ZXing { /** * Enumerates barcode formats known to this package. */ enum class BarcodeFormat { // The values are an implementation detail. The c++ use-case (ZXing::Flags) could have been designed such that it // would not have been necessary to explicitly set the values to single bit constants. This has been done to ease // the interoperability with C-like interfaces, the python and the Qt wrapper. None = 0, ///< Used as a return value if no valid barcode has been detected Aztec = (1 << 0), ///< Aztec Codabar = (1 << 1), ///< Codabar Code39 = (1 << 2), ///< Code39 Code93 = (1 << 3), ///< Code93 Code128 = (1 << 4), ///< Code128 DataBar = (1 << 5), ///< GS1 DataBar, formerly known as RSS 14 DataBarExpanded = (1 << 6), ///< GS1 DataBar Expanded, formerly known as RSS EXPANDED DataMatrix = (1 << 7), ///< DataMatrix EAN8 = (1 << 8), ///< EAN-8 EAN13 = (1 << 9), ///< EAN-13 ITF = (1 << 10), ///< ITF (Interleaved Two of Five) MaxiCode = (1 << 11), ///< MaxiCode PDF417 = (1 << 12), ///< PDF417 QRCode = (1 << 13), ///< QR Code UPCA = (1 << 14), ///< UPC-A UPCE = (1 << 15), ///< UPC-E MicroQRCode = (1 << 16), ///< Micro QR Code RMQRCode = (1 << 17), ///< Rectangular Micro QR Code DXFilmEdge = (1 << 18), ///< DX Film Edge Barcode LinearCodes = Codabar | Code39 | Code93 | Code128 | EAN8 | EAN13 | ITF | DataBar | DataBarExpanded | DXFilmEdge | UPCA | UPCE, MatrixCodes = Aztec | DataMatrix | MaxiCode | PDF417 | QRCode | MicroQRCode | RMQRCode, Any = LinearCodes | MatrixCodes, _max = DXFilmEdge, ///> implementation detail, don't use }; ZX_DECLARE_FLAGS(BarcodeFormats, BarcodeFormat) std::string ToString(BarcodeFormat format); std::string ToString(BarcodeFormats formats); /** * @brief Parse a string into a BarcodeFormat. '-' and '_' are optional. * @return None if str can not be parsed as a valid enum value */ BarcodeFormat BarcodeFormatFromString(std::string_view str); /** * @brief Parse a string into a set of BarcodeFormats. * Separators can be (any combination of) '|', ',' or ' '. * Underscores are optional and input can be lower case. * e.g. "EAN-8 qrcode, Itf" would be parsed into [EAN8, QRCode, ITF]. * @throws std::invalid_parameter if the string can not be fully parsed. */ BarcodeFormats BarcodeFormatsFromString(std::string_view str); } // ZXing ```
/content/code_sandbox/core/src/BarcodeFormat.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
741
```c++ /* */ #include "PerspectiveTransform.h" #include <array> namespace ZXing { PerspectiveTransform PerspectiveTransform::inverse() const { // Here, the adjoint serves as the inverse: // Adjoint is the transpose of the cofactor matrix: return { a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21 }; } PerspectiveTransform PerspectiveTransform::times(const PerspectiveTransform& other) const { return { a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33 }; } PerspectiveTransform PerspectiveTransform::UnitSquareTo(const QuadrilateralF& q) { auto [x0, y0, x1, y1, x2, y2, x3, y3] = reinterpret_cast<const std::array<PointF::value_t, 8>&>(q); auto d3 = q[0] - q[1] + q[2] - q[3]; if (d3 == PointF(0, 0)) { // Affine return {x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f}; } else { auto d1 = q[1] - q[2]; auto d2 = q[3] - q[2]; auto denominator = cross(d1, d2); auto a13 = cross(d3, d2) / denominator; auto a23 = cross(d1, d3) / denominator; return {x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f}; } } PerspectiveTransform::PerspectiveTransform(const QuadrilateralF& src, const QuadrilateralF& dst) { if (!IsConvex(src) || !IsConvex(dst)) return; *this = UnitSquareTo(dst).times(UnitSquareTo(src).inverse()); } PointF PerspectiveTransform::operator()(PointF p) const { auto denominator = a13 * p.x + a23 * p.y + a33; return {(a11 * p.x + a21 * p.y + a31) / denominator, (a12 * p.x + a22 * p.y + a32) / denominator}; } } // ZXing ```
/content/code_sandbox/core/src/PerspectiveTransform.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
830
```objective-c /* */ #pragma once #include <string> #include <cstdint> namespace ZXing { class Error { public: enum class Type : uint8_t { None, Format, Checksum, Unsupported }; Type type() const noexcept { return _type; } const std::string& msg() const noexcept { return _msg; } explicit operator bool() const noexcept { return _type != Type::None; } std::string location() const; Error() = default; Error(Type type, std::string msg = {}) : _msg(std::move(msg)), _type(type) {} Error(const char* file, short line, Type type, std::string msg = {}) : _msg(std::move(msg)), _file(file), _line(line), _type(type) {} static constexpr auto Format = Type::Format; static constexpr auto Checksum = Type::Checksum; static constexpr auto Unsupported = Type::Unsupported; inline bool operator==(const Error& o) const noexcept { return _type == o._type && _msg == o._msg && _file == o._file && _line == o._line; } inline bool operator!=(const Error& o) const noexcept { return !(*this == o); } protected: std::string _msg; const char* _file = nullptr; short _line = -1; Type _type = Type::None; }; inline bool operator==(const Error& e, Error::Type t) noexcept { return e.type() == t; } inline bool operator!=(const Error& e, Error::Type t) noexcept { return !(e == t); } inline bool operator==(Error::Type t, const Error& e) noexcept { return e.type() == t; } inline bool operator!=(Error::Type t, const Error& e) noexcept { return !(t == e); } #define FormatError(...) Error(__FILE__, __LINE__, Error::Format, std::string(__VA_ARGS__)) #define ChecksumError(...) Error(__FILE__, __LINE__, Error::Checksum, std::string(__VA_ARGS__)) #define UnsupportedError(...) Error(__FILE__, __LINE__, Error::Unsupported, std::string(__VA_ARGS__)) std::string ToString(const Error& e); } ```
/content/code_sandbox/core/src/Error.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
455
```c++ /* */ #include "TextDecoder.h" #include "CharacterSet.h" #include "ECI.h" #include "Utf.h" #include "ZXAlgorithms.h" #include "libzueci/zueci.h" #include <cassert> #include <stdexcept> namespace ZXing { void TextDecoder::Append(std::string& str, const uint8_t* bytes, size_t length, CharacterSet charset, bool sjisASCII) { int eci = ToInt(ToECI(charset)); const size_t str_len = str.length(); const int bytes_len = narrow_cast<int>(length); constexpr unsigned int replacement = 0xFFFD; const unsigned int flags = ZUECI_FLAG_SB_STRAIGHT_THRU | (sjisASCII ? ZUECI_FLAG_SJIS_STRAIGHT_THRU : 0); int utf8_len; if (eci == -1) eci = 899; // Binary int error_number = zueci_dest_len_utf8(eci, bytes, bytes_len, replacement, flags, &utf8_len); if (error_number >= ZUECI_ERROR) throw std::runtime_error("zueci_dest_len_utf8 failed"); str.resize(str_len + utf8_len); // Precise length unsigned char *utf8_buf = reinterpret_cast<unsigned char *>(str.data()) + str_len; error_number = zueci_eci_to_utf8(eci, bytes, bytes_len, replacement, flags, utf8_buf, &utf8_len); if (error_number >= ZUECI_ERROR) { str.resize(str_len); throw std::runtime_error("zueci_eci_to_utf8 failed"); } assert(str.length() == str_len + utf8_len); } void TextDecoder::Append(std::wstring& str, const uint8_t* bytes, size_t length, CharacterSet charset) { std::string u8str; Append(u8str, bytes, length, charset); str.append(FromUtf8(u8str)); } /** * @param bytes bytes encoding a string, whose encoding should be guessed * @return name of guessed encoding; at the moment will only guess one of: * {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform * default encoding if none of these can possibly be correct */ CharacterSet TextDecoder::GuessEncoding(const uint8_t* bytes, size_t length, CharacterSet fallback) { // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. bool canBeISO88591 = true; bool canBeShiftJIS = true; bool canBeUTF8 = true; int utf8BytesLeft = 0; //int utf8LowChars = 0; int utf2BytesChars = 0; int utf3BytesChars = 0; int utf4BytesChars = 0; int sjisBytesLeft = 0; //int sjisLowChars = 0; int sjisKatakanaChars = 0; //int sjisDoubleBytesChars = 0; int sjisCurKatakanaWordLength = 0; int sjisCurDoubleBytesWordLength = 0; int sjisMaxKatakanaWordLength = 0; int sjisMaxDoubleBytesWordLength = 0; //int isoLowChars = 0; //int isoHighChars = 0; int isoHighOther = 0; bool utf8bom = length > 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; for (size_t i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); ++i) { int value = bytes[i]; // UTF-8 stuff if (canBeUTF8) { if (utf8BytesLeft > 0) { if ((value & 0x80) == 0) { canBeUTF8 = false; } else { utf8BytesLeft--; } } else if ((value & 0x80) != 0) { if ((value & 0x40) == 0) { canBeUTF8 = false; } else { utf8BytesLeft++; if ((value & 0x20) == 0) { utf2BytesChars++; } else { utf8BytesLeft++; if ((value & 0x10) == 0) { utf3BytesChars++; } else { utf8BytesLeft++; if ((value & 0x08) == 0) { utf4BytesChars++; } else { canBeUTF8 = false; } } } } } //else { //utf8LowChars++; //} } // ISO-8859-1 stuff if (canBeISO88591) { if (value > 0x7F && value < 0xA0) { canBeISO88591 = false; } else if (value > 0x9F) { if (value < 0xC0 || value == 0xD7 || value == 0xF7) { isoHighOther++; } //else { //isoHighChars++; //} } //else { //isoLowChars++; //} } // Shift_JIS stuff if (canBeShiftJIS) { if (sjisBytesLeft > 0) { if (value < 0x40 || value == 0x7F || value > 0xFC) { canBeShiftJIS = false; } else { sjisBytesLeft--; } } else if (value == 0x80 || value == 0xA0 || value > 0xEF) { canBeShiftJIS = false; } else if (value < 0x20 && value != 0xa && value != 0xd) { canBeShiftJIS = false; // use non-printable ASCII as indication for binary content } else if (value > 0xA0 && value < 0xE0) { sjisKatakanaChars++; sjisCurDoubleBytesWordLength = 0; sjisCurKatakanaWordLength++; if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) { sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength; } } else if (value > 0x7F) { sjisBytesLeft++; //sjisDoubleBytesChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength++; if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) { sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength; } } else { //sjisLowChars++; sjisCurKatakanaWordLength = 0; sjisCurDoubleBytesWordLength = 0; } } } if (canBeUTF8 && utf8BytesLeft > 0) { canBeUTF8 = false; } if (canBeShiftJIS && sjisBytesLeft > 0) { canBeShiftJIS = false; } // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) { return CharacterSet::UTF8; } bool assumeShiftJIS = fallback == CharacterSet::Shift_JIS || fallback == CharacterSet::EUC_JP; // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done if (canBeShiftJIS && (assumeShiftJIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) { return CharacterSet::Shift_JIS; } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is: // - If we saw // - only two consecutive katakana chars in the whole text, or // - at least 10% of bytes that could be "upper" not-alphanumeric Latin1, // - then we conclude Shift_JIS, else ISO-8859-1 if (canBeISO88591 && canBeShiftJIS) { return (sjisMaxKatakanaWordLength == 2 && sjisKatakanaChars == 2) || isoHighOther * 10 >= (int)length ? CharacterSet::Shift_JIS : CharacterSet::ISO8859_1; } // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding if (canBeISO88591) { return CharacterSet::ISO8859_1; } if (canBeShiftJIS) { return CharacterSet::Shift_JIS; } if (canBeUTF8) { return CharacterSet::UTF8; } // Otherwise, we take a wild guess with platform encoding return fallback; } CharacterSet TextDecoder::DefaultEncoding() { return CharacterSet::ISO8859_1; } } // ZXing ```
/content/code_sandbox/core/src/TextDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,142
```objective-c /* */ #pragma once #include "Barcode.h" #pragma message("Header `Result.h` is deprecated, please include `Barcode.h` and use the new name `Barcode`.") ```
/content/code_sandbox/core/src/Result.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
37
```objective-c /* */ #pragma once #ifdef ZXING_EXPERIMENTAL_API #include "Barcode.h" #include "ImageView.h" #include <memory> #include <string_view> extern "C" struct zint_symbol; namespace ZXing { class CreatorOptions { struct Data; std::unique_ptr<Data> d; friend Barcode CreateBarcode(const void* data, int size, int mode, const CreatorOptions& options); public: CreatorOptions(BarcodeFormat format); ~CreatorOptions(); CreatorOptions(CreatorOptions&&); CreatorOptions& operator=(CreatorOptions&&); zint_symbol* zint() const; #define ZX_PROPERTY(TYPE, NAME) \ TYPE NAME() const noexcept; \ CreatorOptions& NAME(TYPE v)&; \ CreatorOptions&& NAME(TYPE v)&&; ZX_PROPERTY(BarcodeFormat, format) ZX_PROPERTY(bool, readerInit) ZX_PROPERTY(bool, forceSquareDataMatrix) ZX_PROPERTY(std::string, ecLevel) #undef ZX_PROPERTY }; /** * Generate barcode from unicode text * * @param contents UTF-8 string to encode into a barcode * @param options CreatorOptions (including BarcodeFormat) * @return #Barcode generated barcode */ Barcode CreateBarcodeFromText(std::string_view contents, const CreatorOptions& options); /** * Generate barcode from raw binary data * * @param data array of bytes to encode into a barcode * @param size size of byte array * @param options CreatorOptions (including BarcodeFormat) * @return #Barcode generated barcode */ Barcode CreateBarcodeFromBytes(const void* data, int size, const CreatorOptions& options); #if __cplusplus > 201703L Barcode CreateBarcodeFromText(std::u8string_view contents, const CreatorOptions& options); template <typename R> requires std::ranges::contiguous_range<R> && std::ranges::sized_range<R> && (sizeof(std::ranges::range_value_t<R>) == 1) Barcode CreateBarcodeFromBytes(const R& contents, const CreatorOptions& options) { return CreateBarcodeFromBytes(std::ranges::data(contents), std::ranges::size(contents), options); } #else template <typename R> Barcode CreateBarcodeFromBytes(const R& contents, const CreatorOptions& options) { return CreateBarcodeFromBytes(std::data(contents), std::size(contents), options); } #endif // ================================================================================= class WriterOptions { struct Data; std::unique_ptr<Data> d; public: WriterOptions(); ~WriterOptions(); WriterOptions(WriterOptions&&); WriterOptions& operator=(WriterOptions&&); #define ZX_PROPERTY(TYPE, NAME) \ TYPE NAME() const noexcept; \ WriterOptions& NAME(TYPE v)&; \ WriterOptions&& NAME(TYPE v)&&; ZX_PROPERTY(int, scale) ZX_PROPERTY(int, sizeHint) ZX_PROPERTY(int, rotate) ZX_PROPERTY(bool, withHRT) ZX_PROPERTY(bool, withQuietZones) #undef ZX_PROPERTY }; /** * Write barcode symbol to SVG * * @param barcode Barcode to write * @param options WriterOptions to parameterize rendering * @return std::string SVG representation of barcode symbol */ std::string WriteBarcodeToSVG(const Barcode& barcode, const WriterOptions& options = {}); /** * Write barcode symbol to a utf8 string using graphical characters (e.g. '') * * @param barcode Barcode to write * @param options WriterOptions to parameterize rendering * @return std::string Utf8 string representation of barcode symbol */ std::string WriteBarcodeToUtf8(const Barcode& barcode, const WriterOptions& options = {}); /** * Write barcode symbol to Image (Bitmap) * * @param barcode Barcode to write * @param options WriterOptions to parameterize rendering * @return Image Bitmap reprentation of barcode symbol */ Image WriteBarcodeToImage(const Barcode& barcode, const WriterOptions& options = {}); } // ZXing #endif // ZXING_EXPERIMENTAL_API ```
/content/code_sandbox/core/src/WriteBarcode.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
840
```c++ /* */ #include "HybridBinarizer.h" #include "BitMatrix.h" #include "Matrix.h" #include <algorithm> #include <cstdint> #include <fstream> #include <memory> #define USE_NEW_ALGORITHM namespace ZXing { // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels. // So this is the smallest dimension in each axis we can accept. static constexpr int BLOCK_SIZE = 8; static constexpr int WINDOW_SIZE = BLOCK_SIZE * (1 + 2 * 2); static constexpr int MIN_DYNAMIC_RANGE = 24; HybridBinarizer::HybridBinarizer(const ImageView& iv) : GlobalHistogramBinarizer(iv) {} HybridBinarizer::~HybridBinarizer() = default; bool HybridBinarizer::getPatternRow(int row, int rotation, PatternRow& res) const { #if 1 // This is the original "hybrid" behavior: use GlobalHistogram for the 1D case return GlobalHistogramBinarizer::getPatternRow(row, rotation, res); #else // This is an alternative that can be faster in general and perform better in unevenly lit sitations like // path_to_url That said, it fairs // worse in borderline low resolution situations. With the current black box sample set we'd loose 94 // test cases while gaining 53 others. auto bits = getBitMatrix(); if (bits) GetPatternRow(*bits, row, res, rotation % 180 != 0); return bits != nullptr; #endif } using T_t = uint8_t; /** * Applies a single threshold to a block of pixels. */ static void ThresholdBlock(const uint8_t* __restrict luminances, int xoffset, int yoffset, T_t threshold, int rowStride, BitMatrix& matrix) { for (int y = yoffset; y < yoffset + BLOCK_SIZE; ++y) { auto* src = luminances + y * rowStride + xoffset; auto* const dstBegin = matrix.row(y).begin() + xoffset; // TODO: fix pixelStride > 1 case for (auto* dst = dstBegin; dst < dstBegin + BLOCK_SIZE; ++dst, ++src) *dst = (*src <= threshold) * BitMatrix::SET_V; } } #ifndef USE_NEW_ALGORITHM /** * Calculates a single black point for each block of pixels and saves it away. * See the following thread for a discussion of this algorithm: * path_to_url */ static Matrix<T_t> CalculateBlackPoints(const uint8_t* __restrict luminances, int subWidth, int subHeight, int width, int height, int rowStride) { Matrix<T_t> blackPoints(subWidth, subHeight); for (int y = 0; y < subHeight; y++) { int yoffset = std::min(y * BLOCK_SIZE, height - BLOCK_SIZE); for (int x = 0; x < subWidth; x++) { int xoffset = std::min(x * BLOCK_SIZE, width - BLOCK_SIZE); int sum = 0; uint8_t min = luminances[yoffset * rowStride + xoffset]; uint8_t max = min; for (int yy = 0, offset = yoffset * rowStride + xoffset; yy < BLOCK_SIZE; yy++, offset += rowStride) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { auto pixel = luminances[offset + xx]; sum += pixel; if (pixel < min) min = pixel; if (pixel > max) max = pixel; } // short-circuit min/max tests once dynamic range is met if (max - min > MIN_DYNAMIC_RANGE) { // finish the rest of the rows quickly for (yy++, offset += rowStride; yy < BLOCK_SIZE; yy++, offset += rowStride) { for (int xx = 0; xx < BLOCK_SIZE; xx++) { sum += luminances[offset + xx]; } } } } // The default estimate is the average of the values in the block. int average = sum / (BLOCK_SIZE * BLOCK_SIZE); if (max - min <= MIN_DYNAMIC_RANGE) { // If variation within the block is low, assume this is a block with only light or only // dark pixels. In that case we do not want to use the average, as it would divide this // low contrast area into black and white pixels, essentially creating data out of noise. // // The default assumption is that the block is light/background. Since no estimate for // the level of dark pixels exists locally, use half the min for the block. average = min / 2; if (y > 0 && x > 0) { // Correct the "white background" assumption for blocks that have neighbors by comparing // the pixels in this block to the previously calculated black points. This is based on // the fact that dark barcode symbology is always surrounded by some amount of light // background for which reasonable black point estimates were made. The bp estimated at // the boundaries is used for the interior. // The (min < bp) is arbitrary but works better than other heuristics that were tried. int averageNeighborBlackPoint = (blackPoints(x, y - 1) + (2 * blackPoints(x - 1, y)) + blackPoints(x - 1, y - 1)) / 4; if (min < averageNeighborBlackPoint) { average = averageNeighborBlackPoint; } } } blackPoints(x, y) = average; } } return blackPoints; } /** * For each block in the image, calculate the average black point using a 5x5 grid * of the blocks around it. Also handles the corner cases (fractional blocks are computed based * on the last pixels in the row/column which are also used in the previous block). */ static std::shared_ptr<BitMatrix> CalculateMatrix(const uint8_t* __restrict luminances, int subWidth, int subHeight, int width, int height, int rowStride, const Matrix<T_t>& blackPoints) { auto matrix = std::make_shared<BitMatrix>(width, height); #ifndef NDEBUG Matrix<uint8_t> out(width, height); Matrix<uint8_t> out2(width, height); #endif for (int y = 0; y < subHeight; y++) { int yoffset = std::min(y * BLOCK_SIZE, height - BLOCK_SIZE); for (int x = 0; x < subWidth; x++) { int xoffset = std::min(x * BLOCK_SIZE, width - BLOCK_SIZE); int left = std::clamp(x, 2, subWidth - 3); int top = std::clamp(y, 2, subHeight - 3); int sum = 0; for (int dy = -2; dy <= 2; ++dy) { for (int dx = -2; dx <= 2; ++dx) { sum += blackPoints(left + dx, top + dy); } } int average = sum / 25; ThresholdBlock(luminances, xoffset, yoffset, average, rowStride, *matrix); #ifndef NDEBUG for (int yy = 0; yy < 8; ++yy) for (int xx = 0; xx < 8; ++xx) { out.set(xoffset + xx, yoffset + yy, blackPoints(x, y)); out2.set(xoffset + xx, yoffset + yy, average); } #endif } } #ifndef NDEBUG std::ofstream file("thresholds.pnm"); file << "P5\n" << out.width() << ' ' << out.height() << "\n255\n"; file.write(reinterpret_cast<const char*>(out.data()), out.size()); std::ofstream file2("thresholds_avg.pnm"); file2 << "P5\n" << out.width() << ' ' << out.height() << "\n255\n"; file2.write(reinterpret_cast<const char*>(out2.data()), out2.size()); #endif return matrix; } #else // Subdivide the image in blocks of BLOCK_SIZE and calculate one treshold value per block as // (max - min > MIN_DYNAMIC_RANGE) ? (max + min) / 2 : 0 static Matrix<T_t> BlockThresholds(const ImageView iv) { int subWidth = (iv.width() + BLOCK_SIZE - 1) / BLOCK_SIZE; // ceil(width/BS) int subHeight = (iv.height() + BLOCK_SIZE - 1) / BLOCK_SIZE; // ceil(height/BS) Matrix<T_t> thresholds(subWidth, subHeight); for (int y = 0; y < subHeight; y++) { int y0 = std::min(y * BLOCK_SIZE, iv.height() - BLOCK_SIZE); for (int x = 0; x < subWidth; x++) { int x0 = std::min(x * BLOCK_SIZE, iv.width() - BLOCK_SIZE); uint8_t min = 255; uint8_t max = 0; for (int yy = 0; yy < BLOCK_SIZE; yy++) { auto line = iv.data(x0, y0 + yy); for (int xx = 0; xx < BLOCK_SIZE; xx++) UpdateMinMax(min, max, line[xx]); } thresholds(x, y) = (max - min > MIN_DYNAMIC_RANGE) ? (int(max) + min) / 2 : 0; } } return thresholds; } // Apply gaussian-like smoothing filter over all non-zero thresholds and fill any remainig gaps with nearest neighbor static Matrix<T_t> SmoothThresholds(Matrix<T_t>&& in) { Matrix<T_t> out(in.width(), in.height()); constexpr int R = WINDOW_SIZE / BLOCK_SIZE / 2; for (int y = 0; y < in.height(); y++) { for (int x = 0; x < in.width(); x++) { int left = std::clamp(x, R, in.width() - R - 1); int top = std::clamp(y, R, in.height() - R - 1); int sum = in(x, y) * 2; int n = (sum > 0) * 2; auto add = [&](int x, int y) { int t = in(x, y); sum += t; n += t > 0; }; for (int dy = -R; dy <= R; ++dy) for (int dx = -R; dx <= R; ++dx) add(left + dx, top + dy); out(x, y) = n > 0 ? sum / n : 0; } } // flood fill any remaing gaps of (very large) no-contrast regions auto last = out.begin() - 1; for (auto* i = out.begin(); i != out.end(); ++i) { if (*i) { if (last != i - 1) std::fill(last + 1, i, *i); last = i; } } std::fill(last + 1, out.end(), *(std::max(last, out.begin()))); return out; } static std::shared_ptr<BitMatrix> ThresholdImage(const ImageView iv, const Matrix<T_t>& thresholds) { auto matrix = std::make_shared<BitMatrix>(iv.width(), iv.height()); #ifndef NDEBUG Matrix<uint8_t> out(iv.width(), iv.height()); #endif for (int y = 0; y < thresholds.height(); y++) { int yoffset = std::min(y * BLOCK_SIZE, iv.height() - BLOCK_SIZE); for (int x = 0; x < thresholds.width(); x++) { int xoffset = std::min(x * BLOCK_SIZE, iv.width() - BLOCK_SIZE); ThresholdBlock(iv.data(), xoffset, yoffset, thresholds(x, y), iv.rowStride(), *matrix); #ifndef NDEBUG for (int yy = 0; yy < 8; ++yy) for (int xx = 0; xx < 8; ++xx) out.set(xoffset + xx, yoffset + yy, thresholds(x, y)); #endif } } #ifndef NDEBUG std::ofstream file("thresholds_new.pnm"); file << "P5\n" << out.width() << ' ' << out.height() << "\n255\n"; file.write(reinterpret_cast<const char*>(out.data()), out.size()); #endif return matrix; } #endif std::shared_ptr<const BitMatrix> HybridBinarizer::getBlackMatrix() const { if (width() >= WINDOW_SIZE && height() >= WINDOW_SIZE) { #ifdef USE_NEW_ALGORITHM auto thrs = SmoothThresholds(BlockThresholds(_buffer)); return ThresholdImage(_buffer, thrs); #else const uint8_t* luminances = _buffer.data(); int subWidth = (width() + BLOCK_SIZE - 1) / BLOCK_SIZE; // ceil(width/BS) int subHeight = (height() + BLOCK_SIZE - 1) / BLOCK_SIZE; // ceil(height/BS) auto blackPoints = CalculateBlackPoints(luminances, subWidth, subHeight, width(), height(), _buffer.rowStride()); return CalculateMatrix(luminances, subWidth, subHeight, width(), height(), _buffer.rowStride(), blackPoints); #endif } else { // If the image is too small, fall back to the global histogram approach. return GlobalHistogramBinarizer::getBlackMatrix(); } } } // ZXing ```
/content/code_sandbox/core/src/HybridBinarizer.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,003
```c++ /* */ #include "MultiFormatWriter.h" #include "BitMatrix.h" #include "aztec/AZWriter.h" #include "datamatrix/DMWriter.h" #include "oned/ODCodabarWriter.h" #include "oned/ODCode128Writer.h" #include "oned/ODCode39Writer.h" #include "oned/ODCode93Writer.h" #include "oned/ODEAN13Writer.h" #include "oned/ODEAN8Writer.h" #include "oned/ODITFWriter.h" #include "oned/ODUPCAWriter.h" #include "oned/ODUPCEWriter.h" #include "pdf417/PDFWriter.h" #include "qrcode/QRErrorCorrectionLevel.h" #include "qrcode/QRWriter.h" #include "Utf.h" #include <stdexcept> namespace ZXing { BitMatrix MultiFormatWriter::encode(const std::wstring& contents, int width, int height) const { auto exec0 = [&](auto&& writer) { if (_margin >=0) writer.setMargin(_margin); return writer.encode(contents, width, height); }; auto AztecEccLevel = [&](Aztec::Writer& writer, int eccLevel) { writer.setEccPercent(eccLevel * 100 / 8); }; auto Pdf417EccLevel = [&](Pdf417::Writer& writer, int eccLevel) { writer.setErrorCorrectionLevel(eccLevel); }; auto QRCodeEccLevel = [&](QRCode::Writer& writer, int eccLevel) { writer.setErrorCorrectionLevel(static_cast<QRCode::ErrorCorrectionLevel>(--eccLevel / 2)); }; auto exec1 = [&](auto&& writer, auto setEccLevel) { if (_encoding != CharacterSet::Unknown) writer.setEncoding(_encoding); if (_eccLevel >= 0 && _eccLevel <= 8) setEccLevel(writer, _eccLevel); return exec0(std::move(writer)); }; auto exec2 = [&](auto&& writer) { if (_encoding != CharacterSet::Unknown) writer.setEncoding(_encoding); return exec0(std::move(writer)); }; switch (_format) { case BarcodeFormat::Aztec: return exec1(Aztec::Writer(), AztecEccLevel); case BarcodeFormat::DataMatrix: return exec2(DataMatrix::Writer()); case BarcodeFormat::PDF417: return exec1(Pdf417::Writer(), Pdf417EccLevel); case BarcodeFormat::QRCode: return exec1(QRCode::Writer(), QRCodeEccLevel); case BarcodeFormat::Codabar: return exec0(OneD::CodabarWriter()); case BarcodeFormat::Code39: return exec0(OneD::Code39Writer()); case BarcodeFormat::Code93: return exec0(OneD::Code93Writer()); case BarcodeFormat::Code128: return exec0(OneD::Code128Writer()); case BarcodeFormat::EAN8: return exec0(OneD::EAN8Writer()); case BarcodeFormat::EAN13: return exec0(OneD::EAN13Writer()); case BarcodeFormat::ITF: return exec0(OneD::ITFWriter()); case BarcodeFormat::UPCA: return exec0(OneD::UPCAWriter()); case BarcodeFormat::UPCE: return exec0(OneD::UPCEWriter()); default: throw std::invalid_argument(std::string("Unsupported format: ") + ToString(_format)); } } BitMatrix MultiFormatWriter::encode(const std::string& contents, int width, int height) const { return encode(FromUtf8(contents), width, height); } } // ZXing ```
/content/code_sandbox/core/src/MultiFormatWriter.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
761
```c++ /* */ #include "GridSampler.h" #ifdef PRINT_DEBUG #include "LogMatrix.h" #include "BitMatrixIO.h" #endif namespace ZXing { #ifdef PRINT_DEBUG LogMatrix log; #endif DetectorResult SampleGrid(const BitMatrix& image, int width, int height, const PerspectiveTransform& mod2Pix) { return SampleGrid(image, width, height, {ROI{0, width, 0, height, mod2Pix}}); } DetectorResult SampleGrid(const BitMatrix& image, int width, int height, const ROIs& rois) { #ifdef PRINT_DEBUG LogMatrix log; static int i = 0; LogMatrixWriter lmw(log, image, 5, "grid" + std::to_string(i++) + ".pnm"); #endif if (width <= 0 || height <= 0) return {}; for (auto&& [x0, x1, y0, y1, mod2Pix] : rois) { // Precheck the corners of every roi to bail out early if the grid is "obviously" not completely inside the image auto isInside = [&mod2Pix = mod2Pix, &image](int x, int y) { return image.isIn(mod2Pix(centered(PointI(x, y)))); }; if (!mod2Pix.isValid() || !isInside(x0, y0) || !isInside(x1 - 1, y0) || !isInside(x1 - 1, y1 - 1) || !isInside(x0, y1 - 1)) return {}; } BitMatrix res(width, height); for (auto&& [x0, x1, y0, y1, mod2Pix] : rois) { for (int y = y0; y < y1; ++y) for (int x = x0; x < x1; ++x) { auto p = mod2Pix(centered(PointI{x, y})); // Due to a "numerical instability" in the PerspectiveTransform generation/application it has been observed // that even though all boundary grid points get projected inside the image, it can still happen that an // inner grid points is not. See #563. A true perspective transformation cannot have this property. // The following check takes 100% care of the issue and turned out to be less of a performance impact than feared. // TODO: Check some mathematical/numercial property of mod2Pix to determine if it is a perspective transforation. if (!image.isIn(p)) return {}; #ifdef PRINT_DEBUG log(p, 3); #endif #if 0 int sum = 0; for (int dy = -1; dy <= 1; ++dy) for (int dx = -1; dx <= 1; ++dx) sum += image.get(p + PointF(dx, dy)); if (sum >= 5) #else if (image.get(p)) #endif res.set(x, y); } } #ifdef PRINT_DEBUG printf("width: %d, height: %d\n", width, height); // printf("%s", ToString(res).c_str()); #endif auto projectCorner = [&](PointI p) { for (auto&& [x0, x1, y0, y1, mod2Pix] : rois) if (x0 <= p.x && p.x <= x1 && y0 <= p.y && p.y <= y1) return PointI(mod2Pix(PointF(p)) + PointF(0.5, 0.5)); return PointI(); }; return {std::move(res), {projectCorner({0, 0}), projectCorner({width, 0}), projectCorner({width, height}), projectCorner({0, height})}}; } } // ZXing ```
/content/code_sandbox/core/src/GridSampler.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
828
```objective-c /* */ #pragma once #include <algorithm> #include <cmath> namespace ZXing { template <typename T> struct PointT { using value_t = T; T x = 0, y = 0; constexpr PointT() = default; constexpr PointT(T x, T y) : x(x), y(y) {} template <typename U> constexpr explicit PointT(const PointT<U>& p) : x(static_cast<T>(p.x)), y(static_cast<T>(p.y)) {} template <typename U> PointT& operator+=(const PointT<U>& b) { x += b.x; y += b.y; return *this; } }; template <typename T> bool operator==(const PointT<T>& a, const PointT<T>& b) { return a.x == b.x && a.y == b.y; } template <typename T> bool operator!=(const PointT<T>& a, const PointT<T>& b) { return !(a == b); } template <typename T> auto operator-(const PointT<T>& a) -> PointT<T> { return {-a.x, -a.y}; } template <typename T, typename U> auto operator+(const PointT<T>& a, const PointT<U>& b) -> PointT<decltype(a.x + b.x)> { return {a.x + b.x, a.y + b.y}; } template <typename T, typename U> auto operator-(const PointT<T>& a, const PointT<U>& b) -> PointT<decltype(a.x - b.x)> { return {a.x - b.x, a.y - b.y}; } template <typename T, typename U> auto operator*(const PointT<T>& a, const PointT<U>& b) -> PointT<decltype(a.x * b.x)> { return {a.x * b.x, a.y * b.y}; } template <typename T, typename U> PointT<T> operator*(U s, const PointT<T>& a) { return {s * a.x, s * a.y}; } template <typename T, typename U> PointT<T> operator/(const PointT<T>& a, U d) { return {a.x / d, a.y / d}; } template <typename T, typename U> auto dot(const PointT<T>& a, const PointT<U>& b) -> decltype (a.x * b.x) { return a.x * b.x + a.y * b.y; } template <typename T> auto cross(PointT<T> a, PointT<T> b) -> decltype(a.x * b.x) { return a.x * b.y - b.x * a.y; } /// L1 norm template <typename T> T sumAbsComponent(PointT<T> p) { return std::abs(p.x) + std::abs(p.y); } /// L2 norm template <typename T> auto length(PointT<T> p) -> decltype(std::sqrt(dot(p, p))) { return std::sqrt(dot(p, p)); } /// L-inf norm template <typename T> T maxAbsComponent(PointT<T> p) { return std::max(std::abs(p.x), std::abs(p.y)); } template <typename T> auto distance(PointT<T> a, PointT<T> b) -> decltype(length(a - b)) { return length(a - b); } using PointI = PointT<int>; using PointF = PointT<double>; /// Calculate a floating point pixel coordinate representing the 'center' of the pixel. /// This is sort of the inverse operation of the PointI(PointF) conversion constructor. /// See also the documentation of the GridSampler API. inline PointF centered(PointI p) { return p + PointF(0.5f, 0.5f); } inline PointF centered(PointF p) { return {std::floor(p.x) + 0.5f, std::floor(p.y) + 0.5f}; } template <typename T> PointF normalized(PointT<T> d) { return PointF(d) / length(PointF(d)); } template <typename T> PointT<T> bresenhamDirection(PointT<T> d) { return d / maxAbsComponent(d); } template <typename T> PointT<T> mainDirection(PointT<T> d) { return std::abs(d.x) > std::abs(d.y) ? PointT<T>(d.x, 0) : PointT<T>(0, d.y); } } // ZXing ```
/content/code_sandbox/core/src/Point.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
943
```objective-c /* */ #pragma once #include "ReaderOptions.h" #include "Barcode.h" namespace ZXing { class BinaryBitmap; class ReaderOptions; class Reader { protected: const ReaderOptions& _opts; public: const bool supportsInversion; explicit Reader(const ReaderOptions& opts, bool supportsInversion = false) : _opts(opts), supportsInversion(supportsInversion) {} explicit Reader(ReaderOptions&& opts) = delete; virtual ~Reader() = default; virtual Barcode decode(const BinaryBitmap& image) const = 0; // WARNING: this API is experimental and may change/disappear virtual Barcodes decode(const BinaryBitmap& image, [[maybe_unused]] int maxSymbols) const { auto res = decode(image); return res.isValid() || (_opts.returnErrors() && res.format() != BarcodeFormat::None) ? Barcodes{std::move(res)} : Barcodes{}; } }; } // ZXing ```
/content/code_sandbox/core/src/Reader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
195
```objective-c /* */ #ifndef _ZXING_C_H #define _ZXING_C_H #include <stdbool.h> #include <stdint.h> #ifdef __cplusplus #include "ZXingCpp.h" typedef ZXing::Barcode ZXing_Barcode; typedef ZXing::Barcodes ZXing_Barcodes; typedef ZXing::ImageView ZXing_ImageView; typedef ZXing::Image ZXing_Image; typedef ZXing::ReaderOptions ZXing_ReaderOptions; #ifdef ZXING_EXPERIMENTAL_API typedef ZXing::CreatorOptions ZXing_CreatorOptions; typedef ZXing::WriterOptions ZXing_WriterOptions; #endif extern "C" { #else typedef struct ZXing_Barcode ZXing_Barcode; typedef struct ZXing_Barcodes ZXing_Barcodes; typedef struct ZXing_ImageView ZXing_ImageView; typedef struct ZXing_Image ZXing_Image; typedef struct ZXing_ReaderOptions ZXing_ReaderOptions; typedef struct ZXing_CreatorOptions ZXing_CreatorOptions; typedef struct ZXing_WriterOptions ZXing_WriterOptions; #endif /* * ZXing/ImageView.h */ typedef enum { ZXing_ImageFormat_None = 0, ZXing_ImageFormat_Lum = 0x01000000, ZXing_ImageFormat_LumA = 0x02000000, ZXing_ImageFormat_RGB = 0x03000102, ZXing_ImageFormat_BGR = 0x03020100, ZXing_ImageFormat_RGBA = 0x04000102, ZXing_ImageFormat_ARGB = 0x04010203, ZXing_ImageFormat_BGRA = 0x04020100, ZXing_ImageFormat_ABGR = 0x04030201, } ZXing_ImageFormat; ZXing_ImageView* ZXing_ImageView_new(const uint8_t* data, int width, int height, ZXing_ImageFormat format, int rowStride, int pixStride); ZXing_ImageView* ZXing_ImageView_new_checked(const uint8_t* data, int size, int width, int height, ZXing_ImageFormat format, int rowStride, int pixStride); void ZXing_ImageView_delete(ZXing_ImageView* iv); void ZXing_ImageView_crop(ZXing_ImageView* iv, int left, int top, int width, int height); void ZXing_ImageView_rotate(ZXing_ImageView* iv, int degree); void ZXing_Image_delete(ZXing_Image* img); const uint8_t* ZXing_Image_data(const ZXing_Image* img); int ZXing_Image_width(const ZXing_Image* img); int ZXing_Image_height(const ZXing_Image* img); ZXing_ImageFormat ZXing_Image_format(const ZXing_Image* img); /* * ZXing/BarcodeFormat.h */ typedef enum { ZXing_BarcodeFormat_None = 0, ZXing_BarcodeFormat_Aztec = (1 << 0), ZXing_BarcodeFormat_Codabar = (1 << 1), ZXing_BarcodeFormat_Code39 = (1 << 2), ZXing_BarcodeFormat_Code93 = (1 << 3), ZXing_BarcodeFormat_Code128 = (1 << 4), ZXing_BarcodeFormat_DataBar = (1 << 5), ZXing_BarcodeFormat_DataBarExpanded = (1 << 6), ZXing_BarcodeFormat_DataMatrix = (1 << 7), ZXing_BarcodeFormat_EAN8 = (1 << 8), ZXing_BarcodeFormat_EAN13 = (1 << 9), ZXing_BarcodeFormat_ITF = (1 << 10), ZXing_BarcodeFormat_MaxiCode = (1 << 11), ZXing_BarcodeFormat_PDF417 = (1 << 12), ZXing_BarcodeFormat_QRCode = (1 << 13), ZXing_BarcodeFormat_UPCA = (1 << 14), ZXing_BarcodeFormat_UPCE = (1 << 15), ZXing_BarcodeFormat_MicroQRCode = (1 << 16), ZXing_BarcodeFormat_RMQRCode = (1 << 17), ZXing_BarcodeFormat_DXFilmEdge = (1 << 18), ZXing_BarcodeFormat_LinearCodes = ZXing_BarcodeFormat_Codabar | ZXing_BarcodeFormat_Code39 | ZXing_BarcodeFormat_Code93 | ZXing_BarcodeFormat_Code128 | ZXing_BarcodeFormat_EAN8 | ZXing_BarcodeFormat_EAN13 | ZXing_BarcodeFormat_ITF | ZXing_BarcodeFormat_DataBar | ZXing_BarcodeFormat_DataBarExpanded | ZXing_BarcodeFormat_DXFilmEdge | ZXing_BarcodeFormat_UPCA | ZXing_BarcodeFormat_UPCE, ZXing_BarcodeFormat_MatrixCodes = ZXing_BarcodeFormat_Aztec | ZXing_BarcodeFormat_DataMatrix | ZXing_BarcodeFormat_MaxiCode | ZXing_BarcodeFormat_PDF417 | ZXing_BarcodeFormat_QRCode | ZXing_BarcodeFormat_MicroQRCode | ZXing_BarcodeFormat_RMQRCode, ZXing_BarcodeFormat_Any = ZXing_BarcodeFormat_LinearCodes | ZXing_BarcodeFormat_MatrixCodes, ZXing_BarcodeFormat_Invalid = 0xFFFFFFFFu /* return value when BarcodeFormatsFromString() throws */ } ZXing_BarcodeFormat; typedef ZXing_BarcodeFormat ZXing_BarcodeFormats; ZXing_BarcodeFormats ZXing_BarcodeFormatsFromString(const char* str); ZXing_BarcodeFormat ZXing_BarcodeFormatFromString(const char* str); char* ZXing_BarcodeFormatToString(ZXing_BarcodeFormat format); /* * ZXing/ZXingCpp.h */ #ifdef ZXING_EXPERIMENTAL_API typedef enum { ZXing_Operation_Create, ZXing_Operation_Read, ZXing_Operation_CreateAndRead, ZXing_Operation_CreateOrRead, } ZXing_Operation; ZXing_BarcodeFormats ZXing_SupportedBarcodeFormats(ZXing_Operation op); #endif /* * ZXing/Barcode.h */ typedef enum { ZXing_ContentType_Text, ZXing_ContentType_Binary, ZXing_ContentType_Mixed, ZXing_ContentType_GS1, ZXing_ContentType_ISO15434, ZXing_ContentType_UnknownECI } ZXing_ContentType; typedef enum { ZXing_ErrorType_None, ZXing_ErrorType_Format, ZXing_ErrorType_Checksum, ZXing_ErrorType_Unsupported } ZXing_ErrorType; char* ZXing_ContentTypeToString(ZXing_ContentType type); typedef struct ZXing_PointI { int x, y; } ZXing_PointI; typedef struct ZXing_Position { ZXing_PointI topLeft, topRight, bottomRight, bottomLeft; } ZXing_Position; char* ZXing_PositionToString(ZXing_Position position); bool ZXing_Barcode_isValid(const ZXing_Barcode* barcode); ZXing_ErrorType ZXing_Barcode_errorType(const ZXing_Barcode* barcode); char* ZXing_Barcode_errorMsg(const ZXing_Barcode* barcode); ZXing_BarcodeFormat ZXing_Barcode_format(const ZXing_Barcode* barcode); ZXing_ContentType ZXing_Barcode_contentType(const ZXing_Barcode* barcode); uint8_t* ZXing_Barcode_bytes(const ZXing_Barcode* barcode, int* len); uint8_t* ZXing_Barcode_bytesECI(const ZXing_Barcode* barcode, int* len); char* ZXing_Barcode_text(const ZXing_Barcode* barcode); char* ZXing_Barcode_ecLevel(const ZXing_Barcode* barcode); char* ZXing_Barcode_symbologyIdentifier(const ZXing_Barcode* barcode); ZXing_Position ZXing_Barcode_position(const ZXing_Barcode* barcode); int ZXing_Barcode_orientation(const ZXing_Barcode* barcode); bool ZXing_Barcode_hasECI(const ZXing_Barcode* barcode); bool ZXing_Barcode_isInverted(const ZXing_Barcode* barcode); bool ZXing_Barcode_isMirrored(const ZXing_Barcode* barcode); int ZXing_Barcode_lineCount(const ZXing_Barcode* barcode); void ZXing_Barcode_delete(ZXing_Barcode* barcode); void ZXing_Barcodes_delete(ZXing_Barcodes* barcodes); int ZXing_Barcodes_size(const ZXing_Barcodes* barcodes); const ZXing_Barcode* ZXing_Barcodes_at(const ZXing_Barcodes* barcodes, int i); ZXing_Barcode* ZXing_Barcodes_move(ZXing_Barcodes* barcodes, int i); /* * ZXing/ReaderOptions.h */ typedef enum { ZXing_Binarizer_LocalAverage, ZXing_Binarizer_GlobalHistogram, ZXing_Binarizer_FixedThreshold, ZXing_Binarizer_BoolCast, } ZXing_Binarizer; typedef enum { ZXing_EanAddOnSymbol_Ignore, ZXing_EanAddOnSymbol_Read, ZXing_EanAddOnSymbol_Require, } ZXing_EanAddOnSymbol; typedef enum { ZXing_TextMode_Plain, ZXing_TextMode_ECI, ZXing_TextMode_HRI, ZXing_TextMode_Hex, ZXing_TextMode_Escaped, } ZXing_TextMode; ZXing_ReaderOptions* ZXing_ReaderOptions_new(); void ZXing_ReaderOptions_delete(ZXing_ReaderOptions* opts); void ZXing_ReaderOptions_setTryHarder(ZXing_ReaderOptions* opts, bool tryHarder); void ZXing_ReaderOptions_setTryRotate(ZXing_ReaderOptions* opts, bool tryRotate); void ZXing_ReaderOptions_setTryInvert(ZXing_ReaderOptions* opts, bool tryInvert); void ZXing_ReaderOptions_setTryDownscale(ZXing_ReaderOptions* opts, bool tryDownscale); void ZXing_ReaderOptions_setIsPure(ZXing_ReaderOptions* opts, bool isPure); void ZXing_ReaderOptions_setReturnErrors(ZXing_ReaderOptions* opts, bool returnErrors); void ZXing_ReaderOptions_setFormats(ZXing_ReaderOptions* opts, ZXing_BarcodeFormats formats); void ZXing_ReaderOptions_setBinarizer(ZXing_ReaderOptions* opts, ZXing_Binarizer binarizer); void ZXing_ReaderOptions_setEanAddOnSymbol(ZXing_ReaderOptions* opts, ZXing_EanAddOnSymbol eanAddOnSymbol); void ZXing_ReaderOptions_setTextMode(ZXing_ReaderOptions* opts, ZXing_TextMode textMode); void ZXing_ReaderOptions_setMinLineCount(ZXing_ReaderOptions* opts, int n); void ZXing_ReaderOptions_setMaxNumberOfSymbols(ZXing_ReaderOptions* opts, int n); bool ZXing_ReaderOptions_getTryHarder(const ZXing_ReaderOptions* opts); bool ZXing_ReaderOptions_getTryRotate(const ZXing_ReaderOptions* opts); bool ZXing_ReaderOptions_getTryInvert(const ZXing_ReaderOptions* opts); bool ZXing_ReaderOptions_getTryDownscale(const ZXing_ReaderOptions* opts); bool ZXing_ReaderOptions_getIsPure(const ZXing_ReaderOptions* opts); bool ZXing_ReaderOptions_getReturnErrors(const ZXing_ReaderOptions* opts); ZXing_BarcodeFormats ZXing_ReaderOptions_getFormats(const ZXing_ReaderOptions* opts); ZXing_Binarizer ZXing_ReaderOptions_getBinarizer(const ZXing_ReaderOptions* opts); ZXing_EanAddOnSymbol ZXing_ReaderOptions_getEanAddOnSymbol(const ZXing_ReaderOptions* opts); ZXing_TextMode ZXing_ReaderOptions_getTextMode(const ZXing_ReaderOptions* opts); int ZXing_ReaderOptions_getMinLineCount(const ZXing_ReaderOptions* opts); int ZXing_ReaderOptions_getMaxNumberOfSymbols(const ZXing_ReaderOptions* opts); /* * ZXing/ReadBarcode.h */ /** Note: opts is optional, i.e. it can be NULL, which will imply default settings. */ ZXing_Barcode* ZXing_ReadBarcode(const ZXing_ImageView* iv, const ZXing_ReaderOptions* opts); ZXing_Barcodes* ZXing_ReadBarcodes(const ZXing_ImageView* iv, const ZXing_ReaderOptions* opts); #ifdef ZXING_EXPERIMENTAL_API /* * ZXing/WriteBarcode.h */ ZXing_CreatorOptions* ZXing_CreatorOptions_new(ZXing_BarcodeFormat format); void ZXing_CreatorOptions_delete(ZXing_CreatorOptions* opts); void ZXing_CreatorOptions_setFormat(ZXing_CreatorOptions* opts, ZXing_BarcodeFormat format); ZXing_BarcodeFormat ZXing_CreatorOptions_getFormat(const ZXing_CreatorOptions* opts); void ZXing_CreatorOptions_setReaderInit(ZXing_CreatorOptions* opts, bool readerInit); bool ZXing_CreatorOptions_getReaderInit(const ZXing_CreatorOptions* opts); void ZXing_CreatorOptions_setForceSquareDataMatrix(ZXing_CreatorOptions* opts, bool forceSquareDataMatrix); bool ZXing_CreatorOptions_getForceSquareDataMatrix(const ZXing_CreatorOptions* opts); void ZXing_CreatorOptions_setEcLevel(ZXing_CreatorOptions* opts, const char* ecLevel); char* ZXing_CreatorOptions_getEcLevel(const ZXing_CreatorOptions* opts); ZXing_WriterOptions* ZXing_WriterOptions_new(); void ZXing_WriterOptions_delete(ZXing_WriterOptions* opts); void ZXing_WriterOptions_setScale(ZXing_WriterOptions* opts, int scale); int ZXing_WriterOptions_getScale(const ZXing_WriterOptions* opts); void ZXing_WriterOptions_setSizeHint(ZXing_WriterOptions* opts, int sizeHint); int ZXing_WriterOptions_getSizeHint(const ZXing_WriterOptions* opts); void ZXing_WriterOptions_setRotate(ZXing_WriterOptions* opts, int rotate); int ZXing_WriterOptions_getRotate(const ZXing_WriterOptions* opts); void ZXing_WriterOptions_setWithHRT(ZXing_WriterOptions* opts, bool withHRT); bool ZXing_WriterOptions_getWithHRT(const ZXing_WriterOptions* opts); void ZXing_WriterOptions_setWithQuietZones(ZXing_WriterOptions* opts, bool withQuietZones); bool ZXing_WriterOptions_getWithQuietZones(const ZXing_WriterOptions* opts); ZXing_Barcode* ZXing_CreateBarcodeFromText(const char* data, int size, const ZXing_CreatorOptions* opts); ZXing_Barcode* ZXing_CreateBarcodeFromBytes(const void* data, int size, const ZXing_CreatorOptions* opts); /** Note: opts is optional, i.e. it can be NULL, which will imply default settings. */ char* ZXing_WriteBarcodeToSVG(const ZXing_Barcode* barcode, const ZXing_WriterOptions* opts); ZXing_Image* ZXing_WriteBarcodeToImage(const ZXing_Barcode* barcode, const ZXing_WriterOptions* opts); #endif /* ZXING_EXPERIMENTAL_API */ /* ZXing_LastErrorMsg() returns NULL in case there is no last error and a copy of the string otherwise. */ char* ZXing_LastErrorMsg(); void ZXing_free(void* ptr); #ifdef __cplusplus } #endif #endif /* _ZXING_C_H */ ```
/content/code_sandbox/core/src/ZXingC.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,289
```c++ /* */ #include "BitArray.h" #include "ByteArray.h" #include <cstddef> #include <stdexcept> namespace ZXing { void BitArray::bitwiseXOR(const BitArray& other) { if (size() != other.size()) { throw std::invalid_argument("BitArray::xor(): Sizes don't match"); } for (size_t i = 0; i < _bits.size(); i++) { // The last int could be incomplete (i.e. not have 32 bits in // it) but there is no problem since 0 XOR 0 == 0. _bits[i] ^= other._bits[i]; } } ByteArray BitArray::toBytes(int bitOffset, int numBytes) const { ByteArray res(numBytes == -1 ? (size() - bitOffset + 7) / 8 : numBytes); for (int i = 0; i < Size(res); i++) for (int j = 0; j < 8; j++) AppendBit(res[i], (numBytes != -1 || bitOffset < size()) ? get(bitOffset++) : 0); return res; } } // ZXing ```
/content/code_sandbox/core/src/BitArray.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
254
```c++ /* */ #include "WhiteRectDetector.h" #include "BitMatrix.h" #include "BitMatrixCursor.h" #include "ResultPoint.h" namespace ZXing { static const int INIT_SIZE = 10; static const int CORR = 1; bool DetectWhiteRect(const BitMatrix& image, ResultPoint& p0, ResultPoint& p1, ResultPoint& p2, ResultPoint& p3) { return DetectWhiteRect(image, INIT_SIZE, image.width() / 2, image.height() / 2, p0, p1, p2, p3); } /** * Determines whether a segment contains a black point * * @param a min value of the scanned coordinate * @param b max value of the scanned coordinate * @param fixed value of fixed coordinate * @param horizontal set to true if scan must be horizontal, false if vertical * @return true if a black point has been found, else false. */ static bool ContainsBlackPoint(const BitMatrix& image, int a, int b, int fixed, bool horizontal) { a = std::max(a, 0); if (horizontal) { if (fixed < 0 || fixed >= image.height()) return false; b = std::min(b, image.width() - 1); for (int x = a; x <= b; x++) { if (image.get(x, fixed)) { return true; } } } else { if (fixed < 0 || fixed >= image.width()) return false; b = std::min(b, image.height() - 1); for (int y = a; y <= b; y++) { if (image.get(fixed, y)) { return true; } } } return false; } static bool GetBlackPointOnSegment(const BitMatrix& image, int aX, int aY, int bX, int bY, ResultPoint& result) { PointF a(aX, aY), b(bX, bY); BitMatrixCursorF cur(image, a, b - a); auto dist = std::lround(distance(a, b) / length(cur.d)); for (int i = 0; i < dist; i++) { if (cur.isBlack()) { result = cur.p; return true; } cur.step(); } return false; } /** * recenters the points of a constant distance towards the center * * p0 to p3 describing the corners of the rectangular * region. The first and last points are opposed on the diagonal, as * are the second and third. The first point will be the topmost * point and the last, the bottommost. The second point will be * leftmost and the third, the rightmost * * @param y bottom most point * @param z left most point * @param x right most point * @param t top most point */ static void CenterEdges(const ResultPoint& y, const ResultPoint& z, const ResultPoint& x, const ResultPoint& t, int width, ResultPoint& p0, ResultPoint& p1, ResultPoint& p2, ResultPoint& p3) { // // t t // z x // x OR z // y y // float yi = y.x(); float yj = y.y(); float zi = z.x(); float zj = z.y(); float xi = x.x(); float xj = x.y(); float ti = t.x(); float tj = t.y(); if (yi < width / 2.0f) { p0 = ResultPoint(ti - CORR, tj + CORR); p1 = ResultPoint(zi + CORR, zj + CORR); p2 = ResultPoint(xi - CORR, xj - CORR); p3 = ResultPoint(yi + CORR, yj - CORR); } else { p0 = ResultPoint(ti + CORR, tj + CORR); p1 = ResultPoint(zi + CORR, zj - CORR); p2 = ResultPoint(xi - CORR, xj + CORR); p3 = ResultPoint(yi - CORR, yj - CORR); } } bool DetectWhiteRect(const BitMatrix& image, int initSize, int x, int y, ResultPoint& p0, ResultPoint& p1, ResultPoint& p2, ResultPoint& p3) { int height = image.height(); int width = image.width(); int halfsize = initSize / 2; int left = x - halfsize; int right = x + halfsize; int up = y - halfsize; int down = y + halfsize; if (up < 0 || left < 0 || down >= height || right >= width) { return false; } bool aBlackPointFoundOnBorder = true; bool atLeastOneBlackPointFoundOnBorder = false; bool atLeastOneBlackPointFoundOnRight = false; bool atLeastOneBlackPointFoundOnBottom = false; bool atLeastOneBlackPointFoundOnLeft = false; bool atLeastOneBlackPointFoundOnTop = false; while (aBlackPointFoundOnBorder) { aBlackPointFoundOnBorder = false; // ..... // . | // ..... bool rightBorderNotWhite = true; while ((rightBorderNotWhite || !atLeastOneBlackPointFoundOnRight) && right < width) { rightBorderNotWhite = ContainsBlackPoint(image, up, down, right, false); if (rightBorderNotWhite) { right++; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnRight = true; } else if (!atLeastOneBlackPointFoundOnRight) { right++; } } // ..... // . . // .___. bool bottomBorderNotWhite = true; while ((bottomBorderNotWhite || !atLeastOneBlackPointFoundOnBottom) && down < height) { bottomBorderNotWhite = ContainsBlackPoint(image, left, right, down, true); if (bottomBorderNotWhite) { down++; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnBottom = true; } else if (!atLeastOneBlackPointFoundOnBottom) { down++; } } // ..... // | . // ..... bool leftBorderNotWhite = true; while ((leftBorderNotWhite || !atLeastOneBlackPointFoundOnLeft) && left >= 0) { leftBorderNotWhite = ContainsBlackPoint(image, up, down, left, false); if (leftBorderNotWhite) { left--; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnLeft = true; } else if (!atLeastOneBlackPointFoundOnLeft) { left--; } } // .___. // . . // ..... bool topBorderNotWhite = true; while ((topBorderNotWhite || !atLeastOneBlackPointFoundOnTop) && up >= 0) { topBorderNotWhite = ContainsBlackPoint(image, left, right, up, true); if (topBorderNotWhite) { up--; aBlackPointFoundOnBorder = true; atLeastOneBlackPointFoundOnTop = true; } else if (!atLeastOneBlackPointFoundOnTop) { up--; } } if (aBlackPointFoundOnBorder) { atLeastOneBlackPointFoundOnBorder = true; } } if (up < 0 || left < 0 || down >= height || right >= width) return false; if (atLeastOneBlackPointFoundOnBorder) { int maxSize = right - left; ResultPoint z; bool found = false; for (int i = 1; !found && i < maxSize; i++) { found = GetBlackPointOnSegment(image, left, down - i, left + i, down, z); } if (!found) { return false; } ResultPoint t; found = false; //go down right for (int i = 1; !found && i < maxSize; i++) { found = GetBlackPointOnSegment(image, left, up + i, left + i, up, t); } if (!found) { return false; } ResultPoint x; found = false; //go down left for (int i = 1; !found && i < maxSize; i++) { found = GetBlackPointOnSegment(image, right, up + i, right - i, up, x); } if (!found) { return false; } ResultPoint y; found = false; //go up left for (int i = 1; !found && i < maxSize; i++) { found = GetBlackPointOnSegment(image, right, down - i, right - i, down, y); } if (!found) { return false; } CenterEdges(y, z, x, t, width, p0, p1, p2, p3); return true; } else { return false; } } } // ZXing ```
/content/code_sandbox/core/src/WhiteRectDetector.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,085
```objective-c /* */ #pragma once #include "Point.h" #include "ZXAlgorithms.h" #include <array> #include <cmath> #include <string> namespace ZXing { template <typename T> class Quadrilateral : public std::array<T, 4> { using Base = std::array<T, 4>; using Base::at; public: using Point = T; Quadrilateral() = default; Quadrilateral(T tl, T tr, T br, T bl) : Base{tl, tr, br, bl} {} template <typename U> Quadrilateral(PointT<U> tl, PointT<U> tr, PointT<U> br, PointT<U> bl) : Quadrilateral(Point(tl), Point(tr), Point(br), Point(bl)) {} constexpr Point topLeft() const noexcept { return at(0); } constexpr Point topRight() const noexcept { return at(1); } constexpr Point bottomRight() const noexcept { return at(2); } constexpr Point bottomLeft() const noexcept { return at(3); } double orientation() const { auto centerLine = (topRight() + bottomRight()) - (topLeft() + bottomLeft()); if (centerLine == Point{}) return 0.; auto centerLineF = normalized(centerLine); return std::atan2(centerLineF.y, centerLineF.x); } }; using QuadrilateralF = Quadrilateral<PointF>; using QuadrilateralI = Quadrilateral<PointI>; template <typename PointT = PointF> Quadrilateral<PointT> Rectangle(int width, int height, typename PointT::value_t margin = 0) { return { PointT{margin, margin}, {width - margin, margin}, {width - margin, height - margin}, {margin, height - margin}}; } template <typename PointT = PointF> Quadrilateral<PointT> CenteredSquare(int size) { return Scale(Quadrilateral(PointT{-1, -1}, {1, -1}, {1, 1}, {-1, 1}), size / 2); } template <typename PointT = PointI> Quadrilateral<PointT> Line(int y, int xStart, int xStop) { return {PointT{xStart, y}, {xStop, y}, {xStop, y}, {xStart, y}}; } template <typename PointT> bool IsConvex(const Quadrilateral<PointT>& poly) { const int N = Size(poly); bool sign = false; typename PointT::value_t m = INFINITY, M = 0; for(int i = 0; i < N; i++) { auto d1 = poly[(i + 2) % N] - poly[(i + 1) % N]; auto d2 = poly[i] - poly[(i + 1) % N]; auto cp = cross(d1, d2); // TODO: see if the isInside check for all boundary points in GridSampler is still required after fixing the wrong fabs() // application in the following line UpdateMinMax(m, M, std::fabs(cp)); if (i == 0) sign = cp > 0; else if (sign != (cp > 0)) return false; } // It turns out being convex is not enough to prevent a "numerical instability" // that can cause the corners being projected inside the image boundaries but // some points near the corners being projected outside. This has been observed // where one corner is almost in line with two others. The M/m ratio is below 2 // for the complete existing sample set. For very "skewed" QRCodes a value of // around 3 is realistic. A value of 14 has been observed to trigger the // instability. return M / m < 4.0; } template <typename PointT> Quadrilateral<PointT> Scale(const Quadrilateral<PointT>& q, int factor) { return {factor * q[0], factor * q[1], factor * q[2], factor * q[3]}; } template <typename PointT> PointT Center(const Quadrilateral<PointT>& q) { return Reduce(q) / Size(q); } template <typename PointT> Quadrilateral<PointT> RotatedCorners(const Quadrilateral<PointT>& q, int n = 1, bool mirror = false) { Quadrilateral<PointT> res; std::rotate_copy(q.begin(), q.begin() + ((n + 4) % 4), q.end(), res.begin()); if (mirror) std::swap(res[1], res[3]); return res; } template <typename PointT> bool IsInside(const PointT& p, const Quadrilateral<PointT>& q) { // Test if p is on the same side (right or left) of all polygon segments int pos = 0, neg = 0; for (int i = 0; i < Size(q); ++i) (cross(p - q[i], q[(i + 1) % Size(q)] - q[i]) < 0 ? neg : pos)++; return pos == 0 || neg == 0; } template <typename PointT> Quadrilateral<PointT> BoundingBox(const Quadrilateral<PointT>& q) { auto [minX, maxX] = std::minmax({q[0].x, q[1].x, q[2].x, q[3].x}); auto [minY, maxY] = std::minmax({q[0].y, q[1].y, q[2].y, q[3].y}); return {PointT{minX, minY}, {maxX, minY}, {maxX, maxY}, {minX, maxY}}; } template <typename PointT> bool HaveIntersectingBoundingBoxes(const Quadrilateral<PointT>& a, const Quadrilateral<PointT>& b) { auto bba = BoundingBox(a), bbb = BoundingBox(b); bool x = bbb.topRight().x < bba.topLeft().x || bbb.topLeft().x > bba.topRight().x; bool y = bbb.bottomLeft().y < bba.topLeft().y || bbb.topLeft().y > bba.bottomLeft().y; return !(x || y); } template <typename PointT> Quadrilateral<PointT> Blend(const Quadrilateral<PointT>& a, const Quadrilateral<PointT>& b) { auto dist2First = [c = a[0]](auto a, auto b) { return distance(a, c) < distance(b, c); }; // rotate points such that the the two topLeft points are closest to each other auto offset = std::min_element(b.begin(), b.end(), dist2First) - b.begin(); Quadrilateral<PointT> res; for (int i = 0; i < 4; ++i) res[i] = (a[i] + b[(i + offset) % 4]) / 2; return res; } template <typename T> std::string ToString(const Quadrilateral<PointT<T>>& points) { std::string res; for (const auto& p : points) res += std::to_string(p.x) + "x" + std::to_string(p.y) + (&p == &points.back() ? "" : " "); return res; } } // ZXing ```
/content/code_sandbox/core/src/Quadrilateral.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,579
```c++ /* */ #ifdef ZXING_EXPERIMENTAL_API #include "ZXingCpp.h" namespace ZXing { BarcodeFormats SupportedBarcodeFormats(Operation op) { switch (op) { case Operation::Read: #ifdef ZXING_READERS return BarcodeFormat::Any; #else return BarcodeFormat::None; #endif case Operation::Create: #if defined(ZXING_WRITERS) && defined(ZXING_EXPERIMENTAL_API) return BarcodeFormats(BarcodeFormat::Any).setFlag(BarcodeFormat::DXFilmEdge, false); #else return BarcodeFormat::None; #endif case Operation::CreateAndRead: return SupportedBarcodeFormats(Operation::Create) & SupportedBarcodeFormats(Operation::Read); case Operation::CreateOrRead: return SupportedBarcodeFormats(Operation::Create) | SupportedBarcodeFormats(Operation::Read); } return {}; // unreachable code } } // namespace ZXing #endif // ZXING_EXPERIMENTAL_API ```
/content/code_sandbox/core/src/ZXingCpp.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
195
```objective-c /* */ #pragma once #include "Barcode.h" #include "BarcodeFormat.h" #include "ZXAlgorithms.h" #include <string> namespace ZXing::GTIN { template <typename T> T ComputeCheckDigit(const std::basic_string<T>& digits, bool skipTail = false) { int sum = 0, N = Size(digits) - skipTail; for (int i = N - 1; i >= 0; i -= 2) sum += digits[i] - '0'; sum *= 3; for (int i = N - 2; i >= 0; i -= 2) sum += digits[i] - '0'; return ToDigit<T>((10 - (sum % 10)) % 10); } template <typename T> bool IsCheckDigitValid(const std::basic_string<T>& s) { return ComputeCheckDigit(s, true) == s.back(); } /** * Evaluate the prefix of the GTIN to estimate the country of origin. See * <a href="path_to_url"> * path_to_url and * <a href="path_to_url"> * path_to_url * * `format` required for EAN-8 (UPC-E assumed if not given) */ std::string LookupCountryIdentifier(const std::string& GTIN, const BarcodeFormat format = BarcodeFormat::None); std::string EanAddOn(const Barcode& barcode); std::string IssueNr(const std::string& ean2AddOn); std::string Price(const std::string& ean5AddOn); } // namespace ZXing::GTIN ```
/content/code_sandbox/core/src/GTIN.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
335
```objective-c /* */ #pragma once #include "ReaderOptions.h" // TODO: remove this backward compatibility header once the deprecated name DecodeHints has been removed (3.0) ```
/content/code_sandbox/core/src/DecodeHints.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
34
```c++ /* */ #include "TextEncoder.h" #include "CharacterSet.h" #include "ECI.h" #include "Utf.h" #include "ZXAlgorithms.h" #include "libzueci/zueci.h" #include <stdexcept> namespace ZXing { void TextEncoder::GetBytes(const std::string& str, CharacterSet charset, std::string& bytes) { int eci = ToInt(ToECI(charset)); const int str_len = narrow_cast<int>(str.length()); int eci_len; if (eci == -1) eci = 899; // Binary bytes.clear(); int error_number = zueci_dest_len_eci(eci, reinterpret_cast<const unsigned char *>(str.data()), str_len, &eci_len); if (error_number >= ZUECI_ERROR) // Shouldn't happen throw std::logic_error("Internal error `zueci_dest_len_eci()`"); bytes.resize(eci_len); // Sufficient but approximate length error_number = zueci_utf8_to_eci(eci, reinterpret_cast<const unsigned char *>(str.data()), str_len, reinterpret_cast<unsigned char *>(bytes.data()), &eci_len); if (error_number >= ZUECI_ERROR) { bytes.clear(); throw std::invalid_argument("Unexpected charcode"); } bytes.resize(eci_len); // Actual length } void TextEncoder::GetBytes(const std::wstring& str, CharacterSet charset, std::string& bytes) { GetBytes(ToUtf8(str), charset, bytes); } } // ZXing ```
/content/code_sandbox/core/src/TextEncoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
323
```c++ /* */ #include "Content.h" #include "CharacterSet.h" #include "ECI.h" #include "HRI.h" #include "TextDecoder.h" #include "Utf.h" #include "ZXAlgorithms.h" #if !defined(ZXING_READERS) && !defined(ZXING_WRITERS) #include "Version.h" #endif #include <cctype> namespace ZXing { std::string ToString(ContentType type) { const char* t2s[] = {"Text", "Binary", "Mixed", "GS1", "ISO15434", "UnknownECI"}; return t2s[static_cast<int>(type)]; } template <typename FUNC> void Content::ForEachECIBlock(FUNC func) const { ECI defaultECI = hasECI ? ECI::ISO8859_1 : ECI::Unknown; if (encodings.empty()) func(defaultECI, 0, Size(bytes)); else if (encodings.front().pos != 0) func(defaultECI, 0, encodings.front().pos); for (int i = 0; i < Size(encodings); ++i) { auto [eci, start] = encodings[i]; int end = i + 1 == Size(encodings) ? Size(bytes) : encodings[i + 1].pos; if (start != end) func(eci, start, end); } } void Content::switchEncoding(ECI eci, bool isECI) { // remove all non-ECI entries on first ECI entry if (isECI && !hasECI) encodings.clear(); if (isECI || !hasECI) encodings.push_back({eci, Size(bytes)}); hasECI |= isECI; } Content::Content() {} Content::Content(ByteArray&& bytes, SymbologyIdentifier si) : bytes(std::move(bytes)), symbology(si) {} void Content::switchEncoding(CharacterSet cs) { switchEncoding(ToECI(cs), false); } void Content::append(const Content& other) { if (!hasECI && other.hasECI) encodings.clear(); if (other.hasECI || !hasECI) for (auto& e : other.encodings) encodings.push_back({e.eci, Size(bytes) + e.pos}); append(other.bytes); hasECI |= other.hasECI; } void Content::erase(int pos, int n) { bytes.erase(bytes.begin() + pos, bytes.begin() + pos + n); for (auto& e : encodings) if (e.pos > pos) pos -= n; } void Content::insert(int pos, const std::string& str) { bytes.insert(bytes.begin() + pos, str.begin(), str.end()); for (auto& e : encodings) if (e.pos > pos) pos += Size(str); } bool Content::canProcess() const { return std::all_of(encodings.begin(), encodings.end(), [](Encoding e) { return CanProcess(e.eci); }); } std::string Content::render(bool withECI) const { if (empty() || !canProcess()) return {}; #ifdef ZXING_READERS std::string res; if (withECI) res = symbology.toString(true); ECI lastECI = ECI::Unknown; auto fallbackCS = defaultCharset; if (!hasECI && fallbackCS == CharacterSet::Unknown) fallbackCS = guessEncoding(); ForEachECIBlock([&](ECI eci, int begin, int end) { // first determine how to decode the content (choose character set) // * eci == ECI::Unknown implies !hasECI and we guess // * if !IsText(eci) the ToCharcterSet(eci) will return Unknown and we decode as binary CharacterSet cs = eci == ECI::Unknown ? fallbackCS : ToCharacterSet(eci); if (withECI) { // then find the eci to report back in the ECI designator if (IsText(ToECI(cs))) // everything decoded as text is reported as utf8 eci = ECI::UTF8; else if (eci == ECI::Unknown) // implies !hasECI and fallbackCS is Unknown or Binary eci = ECI::Binary; if (lastECI != eci) res += ToString(eci); lastECI = eci; std::string tmp; TextDecoder::Append(tmp, bytes.data() + begin, end - begin, cs); for (auto c : tmp) { res += c; if (c == '\\') // in the ECI protocol a '\' has to be doubled res += c; } } else { TextDecoder::Append(res, bytes.data() + begin, end - begin, cs); } }); return res; #else //TODO: replace by proper construction from encoded data from within zint return std::string(bytes.asString()); #endif } std::string Content::text(TextMode mode) const { switch (mode) { case TextMode::Plain: return render(false); case TextMode::ECI: return render(true); case TextMode::HRI: switch (type()) { #ifdef ZXING_READERS case ContentType::GS1: { auto plain = render(false); auto hri = HRIFromGS1(plain); return hri.empty() ? plain : hri; } case ContentType::ISO15434: return HRIFromISO15434(render(false)); case ContentType::Text: return render(false); #endif default: return text(TextMode::Escaped); } case TextMode::Hex: return ToHex(bytes); case TextMode::Escaped: return EscapeNonGraphical(render(false)); } return {}; // silence compiler warning } std::wstring Content::utfW() const { return FromUtf8(render(false)); } ByteArray Content::bytesECI() const { if (empty()) return {}; std::string res = symbology.toString(true); ForEachECIBlock([&](ECI eci, int begin, int end) { if (hasECI) res += ToString(eci); for (int i = begin; i != end; ++i) { char c = static_cast<char>(bytes[i]); res += c; if (c == '\\') // in the ECI protocol a '\' has to be doubled res += c; } }); return ByteArray(res); } CharacterSet Content::guessEncoding() const { #ifdef ZXING_READERS // assemble all blocks with unknown encoding ByteArray input; ForEachECIBlock([&](ECI eci, int begin, int end) { if (eci == ECI::Unknown) input.insert(input.end(), bytes.begin() + begin, bytes.begin() + end); }); if (input.empty()) return CharacterSet::Unknown; return TextDecoder::GuessEncoding(input.data(), input.size(), CharacterSet::ISO8859_1); #else return CharacterSet::Unknown; #endif } ContentType Content::type() const { #ifdef ZXING_READERS if (empty()) return ContentType::Text; if (!canProcess()) return ContentType::UnknownECI; if (symbology.aiFlag == AIFlag::GS1) return ContentType::GS1; // check for the absolut minimum of a ISO 15434 conforming message ("[)>" + RS + digit + digit) if (bytes.size() > 6 && bytes.asString(0, 4) == "[)>\x1E" && std::isdigit(bytes[4]) && std::isdigit(bytes[5])) return ContentType::ISO15434; ECI fallback = ToECI(guessEncoding()); std::vector<bool> binaryECIs; ForEachECIBlock([&](ECI eci, int begin, int end) { if (eci == ECI::Unknown) eci = fallback; binaryECIs.push_back((!IsText(eci) || (ToInt(eci) > 0 && ToInt(eci) < 28 && ToInt(eci) != 25 && std::any_of(bytes.begin() + begin, bytes.begin() + end, [](auto c) { return c < 0x20 && c != 0x9 && c != 0xa && c != 0xd; })))); }); if (!Contains(binaryECIs, true)) return ContentType::Text; if (!Contains(binaryECIs, false)) return ContentType::Binary; return ContentType::Mixed; #else //TODO: replace by proper construction from encoded data from within zint return ContentType::Text; #endif } } // namespace ZXing ```
/content/code_sandbox/core/src/Content.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,895
```objective-c /* */ #pragma once #include <string> #include "BitMatrix.h" namespace ZXing { std::string ToString(const BitMatrix& matrix, bool inverted = false); std::string ToString(const BitMatrix& matrix, char one, char zero = ' ', bool addSpace = true, bool printAsCString = false); std::string ToSVG(const BitMatrix& matrix); BitMatrix ParseBitMatrix(const std::string& str, char one = 'X', bool expectSpace = true); void SaveAsPBM(const BitMatrix& matrix, const std::string filename, int quietZone = 0); } // ZXing ```
/content/code_sandbox/core/src/BitMatrixIO.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
130
```c++ /* */ #include "BitMatrixIO.h" #include <array> #include <fstream> #include <sstream> namespace ZXing { std::string ToString(const BitMatrix& matrix, char one, char zero, bool addSpace, bool printAsCString) { std::string result; result.reserve((addSpace ? 2 : 1) * (matrix.width() * matrix.height()) + matrix.height()); for (int y = 0; y < matrix.height(); ++y) { if (printAsCString) result += '"'; for (auto bit : matrix.row(y)) { result += bit ? one : zero; if (addSpace) result += ' '; } if (printAsCString) result += "\\n\""; result += '\n'; } return result; } std::string ToString(const BitMatrix& matrix, bool inverted) { constexpr auto map = std::array{" ", "", "", ""}; std::string res; for (int y = 0; y < matrix.height(); y += 2) { for (int x = 0; x < matrix.width(); ++x) { int tp = matrix.get(x, y) ^ inverted; int bt = (matrix.height() == 1 && tp) || (y + 1 < matrix.height() && (matrix.get(x, y + 1) ^ inverted)); res += map[tp | (bt << 1)]; } res.push_back('\n'); } return res; } std::string ToSVG(const BitMatrix& matrix) { // see path_to_url#60638350 const int width = matrix.width(); const int height = matrix.height(); std::ostringstream out; out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" << "<svg xmlns=\"path_to_url" version=\"1.1\" viewBox=\"0 0 " << width << " " << height << "\" stroke=\"none\">\n" << "<path d=\""; for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x) if (matrix.get(x, y)) out << "M" << x << "," << y << "h1v1h-1z"; out << "\"/>\n</svg>"; return out.str(); } BitMatrix ParseBitMatrix(const std::string& str, char one, bool expectSpace) { auto lineLength = str.find('\n'); if (lineLength == std::string::npos) return {}; int strStride = expectSpace ? 2 : 1; int height = narrow_cast<int>(str.length() / (lineLength + 1)); int width = narrow_cast<int>(lineLength / strStride); BitMatrix mat(width, height); for (int y = 0; y < height; ++y) { size_t offset = y * (lineLength + 1); for (int x = 0; x < width; ++x, offset += strStride) { if (str[offset] == one) mat.set(x, y); } } return mat; } void SaveAsPBM(const BitMatrix& matrix, const std::string filename, int quietZone) { auto out = ToMatrix<uint8_t>(Inflate(matrix.copy(), 0, 0, quietZone)); std::ofstream file(filename); file << "P5\n" << out.width() << ' ' << out.height() << "\n255\n"; file.write(reinterpret_cast<const char*>(out.data()), out.size()); } } // ZXing ```
/content/code_sandbox/core/src/BitMatrixIO.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
771
```objective-c /* */ #pragma once #include "ImageView.h" #include <cstdint> #include <memory> #include <vector> namespace ZXing { class BitMatrix; using PatternRow = std::vector<uint16_t>; /** * This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects * accept a BinaryBitmap and attempt to decode it. */ class BinaryBitmap { struct Cache; std::unique_ptr<Cache> _cache; bool _inverted = false; bool _closed = false; protected: const ImageView _buffer; /** * Converts a 2D array of luminance data to 1 bit (true means black). * * @return The 2D array of bits for the image, nullptr on error. */ virtual std::shared_ptr<const BitMatrix> getBlackMatrix() const = 0; BitMatrix binarize(const uint8_t threshold) const; public: BinaryBitmap(const ImageView& buffer); virtual ~BinaryBitmap(); int width() const { return _buffer.width(); } int height() const { return _buffer.height(); } /** * Converts one row of luminance data to a vector of ints denoting the widths of the bars and spaces. */ virtual bool getPatternRow(int row, int rotation, PatternRow& res) const = 0; const BitMatrix* getBitMatrix() const; void invert(); bool inverted() const { return _inverted; } void close(); bool closed() const { return _closed; } }; } // ZXing ```
/content/code_sandbox/core/src/BinaryBitmap.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
322
```objective-c /* */ #pragma once #include "CharacterSet.h" #include <cstddef> #include <cstdint> #include <string> namespace ZXing { class TextDecoder { public: static CharacterSet DefaultEncoding(); static CharacterSet GuessEncoding(const uint8_t* bytes, size_t length, CharacterSet fallback = DefaultEncoding()); // If `sjisASCII` set then for Shift_JIS maps ASCII directly (straight-thru), i.e. does not map ASCII backslash & tilde // to Yen sign & overline resp. (JIS X 0201 Roman) static void Append(std::string& str, const uint8_t* bytes, size_t length, CharacterSet charset, bool sjisASCII = true); static void Append(std::wstring& str, const uint8_t* bytes, size_t length, CharacterSet charset); static void AppendLatin1(std::wstring& str, const std::string& latin1) { auto ptr = (const uint8_t*)latin1.data(); str.append(ptr, ptr + latin1.length()); } static std::wstring FromLatin1(const std::string& latin1) { auto ptr = (const uint8_t*)latin1.data(); return std::wstring(ptr, ptr + latin1.length()); } }; } // ZXing ```
/content/code_sandbox/core/src/TextDecoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
272
```c++ /* */ #include "BitMatrix.h" #include "Pattern.h" #include <algorithm> #include <stdexcept> #include <utility> namespace ZXing { void BitMatrix::setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw std::invalid_argument("BitMatrix::setRegion(): Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw std::invalid_argument("BitMatrix::setRegion(): Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > _height || right > _width) { throw std::invalid_argument("BitMatrix::setRegion(): The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { auto offset = y * _width; for (int x = left; x < right; x++) { _bits[offset + x] = SET_V; } } } void BitMatrix::rotate90() { BitMatrix result(height(), width()); for (int x = 0; x < width(); ++x) { for (int y = 0; y < height(); ++y) { if (get(x, y)) { result.set(y, width() - x - 1); } } } *this = std::move(result); } void BitMatrix::rotate180() { std::reverse(_bits.begin(), _bits.end()); } void BitMatrix::mirror() { for (int x = 0; x < _width; x++) { for (int y = x + 1; y < _height; y++) { if (get(x, y) != get(y, x)) { flip(y, x); flip(x, y); } } } } bool BitMatrix::findBoundingBox(int &left, int& top, int& width, int& height, int minSize) const { int right, bottom; if (!getTopLeftOnBit(left, top) || !getBottomRightOnBit(right, bottom) || bottom - top + 1 < minSize) return false; for (int y = top; y <= bottom; y++ ) { for (int x = 0; x < left; ++x) if (get(x, y)) { left = x; break; } for (int x = _width-1; x > right; x--) if (get(x, y)) { right = x; break; } } width = right - left + 1; height = bottom - top + 1; return width >= minSize && height >= minSize; } static auto isSet = [](auto v) { return bool(v); }; bool BitMatrix::getTopLeftOnBit(int& left, int& top) const { int bitsOffset = (int)std::distance(_bits.begin(), std::find_if(_bits.begin(), _bits.end(), isSet)); if (bitsOffset == Size(_bits)) { return false; } top = bitsOffset / _width; left = (bitsOffset % _width); return true; } bool BitMatrix::getBottomRightOnBit(int& right, int& bottom) const { int bitsOffset = Size(_bits) - 1 - (int)std::distance(_bits.rbegin(), std::find_if(_bits.rbegin(), _bits.rend(), isSet)); if (bitsOffset < 0) { return false; } bottom = bitsOffset / _width; right = (bitsOffset % _width); return true; } void GetPatternRow(const BitMatrix& matrix, int r, std::vector<uint16_t>& pr, bool transpose) { if (transpose) GetPatternRow(matrix.col(r), pr); else GetPatternRow(matrix.row(r), pr); } BitMatrix Inflate(BitMatrix&& input, int width, int height, int quietZone) { const int codeWidth = input.width(); const int codeHeight = input.height(); const int outputWidth = std::max(width, codeWidth + 2 * quietZone); const int outputHeight = std::max(height, codeHeight + 2 * quietZone); if (input.width() == outputWidth && input.height() == outputHeight) return std::move(input); const int scale = std::min((outputWidth - 2*quietZone) / codeWidth, (outputHeight - 2*quietZone) / codeHeight); // Padding includes both the quiet zone and the extra white pixels to // accommodate the requested dimensions. const int leftPadding = (outputWidth - (codeWidth * scale)) / 2; const int topPadding = (outputHeight - (codeHeight * scale)) / 2; BitMatrix result(outputWidth, outputHeight); for (int inputY = 0, outputY = topPadding; inputY < input.height(); ++inputY, outputY += scale) { for (int inputX = 0, outputX = leftPadding; inputX < input.width(); ++inputX, outputX += scale) { if (input.get(inputX, inputY)) result.setRegion(outputX, outputY, scale, scale); } } return result; } BitMatrix Deflate(const BitMatrix& input, int width, int height, float top, float left, float subSampling) { BitMatrix result(width, height); for (int y = 0; y < result.height(); y++) { auto yOffset = top + y * subSampling; for (int x = 0; x < result.width(); x++) { if (input.get(PointF(left + x * subSampling, yOffset))) result.set(x, y); } } return result; } } // ZXing ```
/content/code_sandbox/core/src/BitMatrix.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,279
```objective-c /* */ #pragma once #include "DetectorResult.h" #include "PerspectiveTransform.h" namespace ZXing { /** * Samples an image for a rectangular matrix of bits of the given dimension. The sampling * transformation is determined by the coordinates of 4 points, in the original and transformed * image space. * * The following figure is showing the layout a 'pixel'. The point (0,0) is the upper left corner * of the first pixel. (1,1) is its lower right corner. * * 0 1 ... w * 0 #----#-- ... --# * | | ... | * | | ... | * 1 #----# ... --# * | | ... | * * | | ... | * h #----#-- ... --# * * @param image image to sample * @param width width of {@link BitMatrix} to sample from image * @param height height of {@link BitMatrix} to sample from image * @param mod2Pix transforming a module (grid) coordinate into an image (pixel) coordinate * @return {@link DetectorResult} representing a grid of points sampled from the image within a region * defined by the "src" parameters. Result is empty if transformation is invalid (out of bound access). */ DetectorResult SampleGrid(const BitMatrix& image, int width, int height, const PerspectiveTransform& mod2Pix); template <typename PointT = PointF> Quadrilateral<PointT> Rectangle(int x0, int x1, int y0, int y1, typename PointT::value_t o = 0.5) { return {PointT{x0 + o, y0 + o}, {x1 + o, y0 + o}, {x1 + o, y1 + o}, {x0 + o, y1 + o}}; } class ROI { public: int x0, x1, y0, y1; PerspectiveTransform mod2Pix; }; using ROIs = std::vector<ROI>; DetectorResult SampleGrid(const BitMatrix& image, int width, int height, const ROIs& rois); } // ZXing ```
/content/code_sandbox/core/src/GridSampler.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
475
```objective-c /* */ #pragma once #include <string> namespace ZXing { struct StructuredAppendInfo { int index = -1; int count = -1; std::string id; }; } // ZXing ```
/content/code_sandbox/core/src/StructuredAppend.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
44
```c++ /* */ #include "Utf.h" #include "ZXTestSupport.h" #include "ZXAlgorithms.h" #include <iomanip> #include <cstdint> #include <sstream> namespace ZXing { // TODO: c++20 has char8_t #if __cplusplus <= 201703L using char8_t = uint8_t; #endif using utf8_t = std::basic_string_view<char8_t>; using state_t = uint8_t; constexpr state_t kAccepted = 0; constexpr state_t kRejected [[maybe_unused]] = 12; inline char32_t Utf8Decode(char8_t byte, state_t& state, char32_t& codep) { // See path_to_url for details. static constexpr const state_t kUtf8Data[] = { /* The first part of the table maps bytes to character classes that * reduce the size of the transition table and create bitmasks. */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8, /* The second part is a transition table that maps a combination * of a state of the automaton and a character class to a state. */ 0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12, 12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12, 12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12, 12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,12,12,12,12,12, }; state_t type = kUtf8Data[byte]; codep = (state != kAccepted) ? (byte & 0x3fu) | (codep << 6) : (0xff >> type) & (byte); state = kUtf8Data[256 + state + type]; return state; } static_assert(sizeof(wchar_t) == 4 || sizeof(wchar_t) == 2, "wchar_t needs to be 2 or 4 bytes wide"); inline bool IsUtf16SurrogatePair(std::wstring_view str) { return sizeof(wchar_t) == 2 && str.size() >= 2 && (str[0] & 0xfc00) == 0xd800 && (str[1] & 0xfc00) == 0xdc00; } inline char32_t Utf32FromUtf16Surrogates(std::wstring_view str) { return (static_cast<char32_t>(str[0]) << 10) + str[1] - 0x35fdc00; } static size_t Utf8CountCodePoints(utf8_t utf8) { size_t count = 0; for (size_t i = 0; i < utf8.size();) { if (utf8[i] < 128) { ++i; } else { switch (utf8[i] & 0xf0) { case 0xc0: [[fallthrough]]; case 0xd0: i += 2; break; case 0xe0: i += 3; break; case 0xf0: i += 4; break; default: // we are in middle of a sequence ++i; while (i < utf8.size() && (utf8[i] & 0xc0) == 0x80) ++i; break; } } ++count; } return count; } static void AppendFromUtf8(utf8_t utf8, std::wstring& buffer) { buffer.reserve(buffer.size() + Utf8CountCodePoints(utf8)); char32_t codePoint = 0; state_t state = kAccepted; for (auto b : utf8) { if (Utf8Decode(b, state, codePoint) != kAccepted) continue; if (sizeof(wchar_t) == 2 && codePoint > 0xffff) { // surrogate pair buffer.push_back(narrow_cast<wchar_t>(0xd7c0 + (codePoint >> 10))); buffer.push_back(narrow_cast<wchar_t>(0xdc00 + (codePoint & 0x3ff))); } else { buffer.push_back(narrow_cast<wchar_t>(codePoint)); } } } std::wstring FromUtf8(std::string_view utf8) { std::wstring str; AppendFromUtf8({reinterpret_cast<const char8_t*>(utf8.data()), utf8.size()}, str); return str; } #if __cplusplus > 201703L std::wstring FromUtf8(std::u8string_view utf8) { std::wstring str; AppendFromUtf8(utf8, str); return str; } #endif // Count the number of bytes required to store given code points in UTF-8. static size_t Utf8CountBytes(std::wstring_view str) { int result = 0; for (; str.size(); str.remove_prefix(1)) { if (str.front() < 0x80) result += 1; else if (str.front() < 0x800) result += 2; else if (sizeof(wchar_t) == 4) { if (str.front() < 0x10000) result += 3; else result += 4; } else { if (IsUtf16SurrogatePair(str)) { result += 4; str.remove_prefix(1); } else result += 3; } } return result; } ZXING_EXPORT_TEST_ONLY int Utf32ToUtf8(char32_t utf32, char* out) { if (utf32 < 0x80) { *out++ = narrow_cast<char8_t>(utf32); return 1; } if (utf32 < 0x800) { *out++ = narrow_cast<char8_t>((utf32 >> 6) | 0xc0); *out++ = narrow_cast<char8_t>((utf32 & 0x3f) | 0x80); return 2; } if (utf32 < 0x10000) { *out++ = narrow_cast<char8_t>((utf32 >> 12) | 0xe0); *out++ = narrow_cast<char8_t>(((utf32 >> 6) & 0x3f) | 0x80); *out++ = narrow_cast<char8_t>((utf32 & 0x3f) | 0x80); return 3; } *out++ = narrow_cast<char8_t>((utf32 >> 18) | 0xf0); *out++ = narrow_cast<char8_t>(((utf32 >> 12) & 0x3f) | 0x80); *out++ = narrow_cast<char8_t>(((utf32 >> 6) & 0x3f) | 0x80); *out++ = narrow_cast<char8_t>((utf32 & 0x3f) | 0x80); return 4; } static void AppendToUtf8(std::wstring_view str, std::string& utf8) { utf8.reserve(utf8.size() + Utf8CountBytes(str)); char buffer[4]; for (; str.size(); str.remove_prefix(1)) { uint32_t cp; if (IsUtf16SurrogatePair(str)) { cp = Utf32FromUtf16Surrogates(str); str.remove_prefix(1); } else cp = str.front(); auto bufLength = Utf32ToUtf8(cp, buffer); utf8.append(buffer, bufLength); } } std::string ToUtf8(std::wstring_view str) { std::string utf8; AppendToUtf8(str, utf8); return utf8; } static bool iswgraph(wchar_t wc) { /* Consider all legal codepoints as graphical except for: * - whitespace * - C0 and C1 control characters * - U+2028 and U+2029 (line/para break) * - U+FFF9 through U+FFFB (interlinear annotation controls) * The following code is based on libmusls implementation */ if (wc == ' ' || (unsigned)wc - '\t' < 5) return false; if (wc < 0xff) return ((wc + 1) & 0x7f) >= 0x21; if (wc < 0x2028 || wc - 0x202a < 0xd800 - 0x202a || wc - 0xe000 < 0xfff9 - 0xe000) return true; if (wc - 0xfffc > 0x10ffff - 0xfffc || (wc & 0xfffe) == 0xfffe) return false; return true; } std::wstring EscapeNonGraphical(std::wstring_view str) { static const char* const ascii_nongraphs[33] = { "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", "DEL", }; std::wostringstream ws; ws.fill(L'0'); for (; str.size(); str.remove_prefix(1)) { wchar_t wc = str.front(); if (wc < 32 || wc == 127) // Non-graphical ASCII, excluding space ws << "<" << ascii_nongraphs[wc == 127 ? 32 : wc] << ">"; else if (wc < 128) // ASCII ws << wc; else if (IsUtf16SurrogatePair(str)) { ws.write(str.data(), 2); str.remove_prefix(1); } // Exclude unpaired surrogates and NO-BREAK spaces NBSP and NUMSP else if ((wc < 0xd800 || wc >= 0xe000) && (iswgraph(wc) && wc != 0xA0 && wc != 0x2007 && wc != 0x2000 && wc != 0xfffd)) ws << wc; else // Non-graphical Unicode ws << "<U+" << std::setw(wc < 256 ? 2 : 4) << std::uppercase << std::hex << static_cast<uint32_t>(wc) << ">"; } return ws.str(); } std::string EscapeNonGraphical(std::string_view utf8) { return ToUtf8(EscapeNonGraphical(FromUtf8(utf8))); } } // namespace ZXing ```
/content/code_sandbox/core/src/Utf.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
3,064
```objective-c /* */ #pragma once #include <algorithm> #include <cstdint> #include <cstdio> #include <memory> #include <stdexcept> namespace ZXing { enum class ImageFormat : uint32_t { None = 0, Lum = 0x01000000, LumA = 0x02000000, RGB = 0x03000102, BGR = 0x03020100, RGBA = 0x04000102, ARGB = 0x04010203, BGRA = 0x04020100, ABGR = 0x04030201, RGBX [[deprecated("use RGBA")]] = RGBA, XRGB [[deprecated("use ARGB")]] = ARGB, BGRX [[deprecated("use BGRA")]] = BGRA, XBGR [[deprecated("use ABGR")]] = ABGR, }; constexpr inline int PixStride(ImageFormat format) { return (static_cast<uint32_t>(format) >> 3*8) & 0xFF; } constexpr inline int RedIndex(ImageFormat format) { return (static_cast<uint32_t>(format) >> 2*8) & 0xFF; } constexpr inline int GreenIndex(ImageFormat format) { return (static_cast<uint32_t>(format) >> 1*8) & 0xFF; } constexpr inline int BlueIndex(ImageFormat format) { return (static_cast<uint32_t>(format) >> 0*8) & 0xFF; } constexpr inline uint8_t RGBToLum(unsigned r, unsigned g, unsigned b) { // .299R + 0.587G + 0.114B (YUV/YIQ for PAL and NTSC), // (306*R) >> 10 is approximately equal to R*0.299, and so on. // 0x200 >> 10 is 0.5, it implements rounding. return static_cast<uint8_t>((306 * r + 601 * g + 117 * b + 0x200) >> 10); } /** * Simple class that stores a non-owning const pointer to image data plus layout and format information. */ class ImageView { protected: const uint8_t* _data = nullptr; ImageFormat _format = ImageFormat::None; int _width = 0, _height = 0, _pixStride = 0, _rowStride = 0; public: /** ImageView default constructor creates a 'null' image view */ ImageView() = default; /** * ImageView constructor * * @param data pointer to image buffer * @param width image width in pixels * @param height image height in pixels * @param format image/pixel format * @param rowStride optional row stride in bytes, default is width * pixStride * @param pixStride optional pixel stride in bytes, default is calculated from format */ ImageView(const uint8_t* data, int width, int height, ImageFormat format, int rowStride = 0, int pixStride = 0) : _data(data), _format(format), _width(width), _height(height), _pixStride(pixStride ? pixStride : PixStride(format)), _rowStride(rowStride ? rowStride : width * _pixStride) { // TODO: [[deprecated]] this check is to prevent exising code from suddenly throwing, remove in 3.0 if (_data == nullptr && _width == 0 && _height == 0 && rowStride == 0 && pixStride == 0) { fprintf(stderr, "zxing-cpp deprecation warning: ImageView(nullptr, ...) will throw in the future, use ImageView()\n"); return; } if (_data == nullptr) throw std::invalid_argument("Can not construct an ImageView from a NULL pointer"); if (_width <= 0 || _height <= 0) throw std::invalid_argument("Neither width nor height of ImageView can be less or equal to 0"); } /** * ImageView constructor with bounds checking */ ImageView(const uint8_t* data, int size, int width, int height, ImageFormat format, int rowStride = 0, int pixStride = 0) : ImageView(data, width, height, format, rowStride, pixStride) { if (_rowStride < 0 || _pixStride < 0 || size < _height * _rowStride) throw std::invalid_argument("ImageView parameters are inconsistent (out of bounds)"); } int width() const { return _width; } int height() const { return _height; } int pixStride() const { return _pixStride; } int rowStride() const { return _rowStride; } ImageFormat format() const { return _format; } const uint8_t* data() const { return _data; } const uint8_t* data(int x, int y) const { return _data + y * _rowStride + x * _pixStride; } ImageView cropped(int left, int top, int width, int height) const { left = std::clamp(left, 0, _width - 1); top = std::clamp(top, 0, _height - 1); width = width <= 0 ? (_width - left) : std::min(_width - left, width); height = height <= 0 ? (_height - top) : std::min(_height - top, height); return {data(left, top), width, height, _format, _rowStride, _pixStride}; } ImageView rotated(int degree) const { switch ((degree + 360) % 360) { case 90: return {data(0, _height - 1), _height, _width, _format, _pixStride, -_rowStride}; case 180: return {data(_width - 1, _height - 1), _width, _height, _format, -_rowStride, -_pixStride}; case 270: return {data(_width - 1, 0), _height, _width, _format, -_pixStride, _rowStride}; } return *this; } ImageView subsampled(int scale) const { return {_data, _width / scale, _height / scale, _format, _rowStride * scale, _pixStride * scale}; } }; class Image : public ImageView { std::unique_ptr<uint8_t[]> _memory; Image(std::unique_ptr<uint8_t[]>&& data, int w, int h, ImageFormat f) : ImageView(data.get(), w, h, f), _memory(std::move(data)) {} public: Image() = default; Image(int w, int h, ImageFormat f = ImageFormat::Lum) : Image(std::make_unique<uint8_t[]>(w * h * PixStride(f)), w, h, f) {} }; } // ZXing ```
/content/code_sandbox/core/src/ImageView.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,516
```objective-c /* */ #pragma once #include "BitMatrix.h" #include "Matrix.h" #include "Point.h" #include <cassert> #include <cstdint> #include <cstdio> #include <string> namespace ZXing { #ifdef PRINT_DEBUG class LogMatrix { using LogBuffer = Matrix<uint8_t>; LogBuffer _log; const BitMatrix* _image = nullptr; int _scale = 1; public: void init(const BitMatrix* image, int scale = 1) { _image = image; _scale = scale; _log = LogBuffer(_image->width() * _scale, _image->height() * _scale); } void write(const char* fn) { assert(_image); FILE* f = fopen(fn, "wb"); // Write PPM header, P5 == grey, P6 == rgb fprintf(f, "P6\n%d %d\n255\n", _log.width(), _log.height()); // Write pixels for (int y = 0; y < _log.height(); ++y) for (int x = 0; x < _log.width(); ++x) { unsigned char pix[3]; unsigned char &r = pix[0], &g = pix[1], &b = pix[2]; r = g = b = _image->get(x / _scale, y / _scale) ? 0 : 255; if (_scale > 1 && x % _scale == _scale / 2 && y % _scale == _scale / 2) r = g = b = r ? 230 : 50; switch (_log.get(x, y)) { case 1: r = g = b = _scale > 1 ? 128 : (r ? 230 : 50); break; case 2: r = b = 50, g = 220; break; case 3: g = r = 100, b = 250; break; case 4: g = b = 100, r = 250; break; } fwrite(&pix, 3, 1, f); } fclose(f); } template <typename T> void operator()(const PointT<T>& p, int color = 1) { if (_image && _image->isIn(p)) _log.set(static_cast<int>(p.x * _scale), static_cast<int>(p.y * _scale), color); } void operator()(const PointT<int>& p, int color) { operator()(centered(p), color); } template <typename T> void operator()(const std::vector<PointT<T>>& points, int color = 2) { for (auto p : points) operator()(p, color); } }; extern LogMatrix log; class LogMatrixWriter { LogMatrix &log; std::string fn; public: LogMatrixWriter(LogMatrix& log, const BitMatrix& image, int scale, std::string fn) : log(log), fn(fn) { log.init(&image, scale); } ~LogMatrixWriter() { log.write(fn.c_str()); } }; #else template<typename T> void log(PointT<T>, int = 0) {} #endif } // namespace ZXing ```
/content/code_sandbox/core/src/LogMatrix.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
711
```objective-c /* */ #pragma once #include "Barcode.h" #include <vector> #include <memory> namespace ZXing { class Reader; class BinaryBitmap; class ReaderOptions; class MultiFormatReader { public: explicit MultiFormatReader(const ReaderOptions& opts); explicit MultiFormatReader(ReaderOptions&& opts) = delete; ~MultiFormatReader(); Barcode read(const BinaryBitmap& image) const; // WARNING: this API is experimental and may change/disappear Barcodes readMultiple(const BinaryBitmap& image, int maxSymbols = 0xFF) const; private: std::vector<std::unique_ptr<Reader>> _readers; const ReaderOptions& _opts; }; } // ZXing ```
/content/code_sandbox/core/src/MultiFormatReader.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
146
```c++ /* */ #include "GlobalHistogramBinarizer.h" #include "BitMatrix.h" #include "Pattern.h" #include <algorithm> #include <array> #include <utility> namespace ZXing { static constexpr int LUMINANCE_BITS = 5; static constexpr int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; static constexpr int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; using Histogram = std::array<uint16_t, LUMINANCE_BUCKETS>; GlobalHistogramBinarizer::GlobalHistogramBinarizer(const ImageView& buffer) : BinaryBitmap(buffer) {} GlobalHistogramBinarizer::~GlobalHistogramBinarizer() = default; using ImageLineView = Range<StrideIter<const uint8_t*>>; inline ImageLineView RowView(const ImageView& iv, int row) { return {{iv.data(0, row), iv.pixStride()}, {iv.data(iv.width(), row), iv.pixStride()}}; } static void ThresholdSharpened(const ImageLineView in, int threshold, std::vector<uint8_t>& out) { out.resize(in.size()); auto i = in.begin(); auto o = out.begin(); *o++ = (*i++ <= threshold) * BitMatrix::SET_V; for (auto end = in.end() - 1; i != end; ++i) *o++ = ((-i[-1] + (int(i[0]) * 4) - i[1]) / 2 <= threshold) * BitMatrix::SET_V; *o++ = (*i++ <= threshold) * BitMatrix::SET_V; } static auto GenHistogram(const ImageLineView line) { // This code causes about 20% of the total runtime on an AVX2 system for a EAN13 search on Lum input data. // Trying to increase the performance by performing 2 or 4 "parallel" histograms helped nothing. Histogram res = {}; for (auto pix : line) res[pix >> LUMINANCE_SHIFT]++; return res; } // Return -1 on error static int EstimateBlackPoint(const Histogram& buckets) { // Find the tallest peak in the histogram. auto firstPeakPos = std::max_element(buckets.begin(), buckets.end()); int firstPeak = narrow_cast<int>(firstPeakPos - buckets.begin()); int firstPeakSize = *firstPeakPos; int maxBucketCount = firstPeakSize; // Find the second-tallest peak which is somewhat far from the tallest peak. int secondPeak = 0; int secondPeakScore = 0; for (int x = 0; x < Size(buckets); x++) { int distanceToBiggest = x - firstPeak; // Encourage more distant second peaks by multiplying by square of distance. int score = buckets[x] * distanceToBiggest * distanceToBiggest; if (score > secondPeakScore) { secondPeak = x; secondPeakScore = score; } } // Make sure firstPeak corresponds to the black peak. if (firstPeak > secondPeak) { std::swap(firstPeak, secondPeak); } // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if (secondPeak - firstPeak <= LUMINANCE_BUCKETS / 16) { return -1; } // Find a valley between them that is low and closer to the white peak. int bestValley = secondPeak - 1; int bestValleyScore = -1; for (int x = secondPeak - 1; x > firstPeak; x--) { int fromFirst = x - firstPeak; int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]); if (score > bestValleyScore) { bestValley = x; bestValleyScore = score; } } return bestValley << LUMINANCE_SHIFT; } bool GlobalHistogramBinarizer::getPatternRow(int row, int rotation, PatternRow& res) const { auto buffer = _buffer.rotated(rotation); auto lineView = RowView(buffer, row); if (buffer.width() < 3) return false; // special casing the code below for a width < 3 makes no sense #if defined(__AVX__) // or defined(__ARM_NEON) // If we are extracting a column (instead of a row), we run into cache misses on every pixel access both // during the histogram calculation and during the sharpen+threshold operation. Additionally, if we // perform the ThresholdSharpened function on pixStride==1 data, the auto-vectorizer makes that part // 8x faster on an AVX2 cpu which easily recovers the extra cost that we pay for the copying. thread_local std::vector<uint8_t> line; if (std::abs(buffer.pixStride()) > 4) { line.resize(lineView.size()); std::copy(lineView.begin(), lineView.end(), line.begin()); lineView = {{line.data(), 1}, {line.data() + line.size(), 1}}; } #endif auto threshold = EstimateBlackPoint(GenHistogram(lineView)) - 1; if (threshold <= 0) return false; thread_local std::vector<uint8_t> binarized; // the optimizer can generate a specialized version for pixStride==1 (non-rotated input) that is about 8x faster on AVX2 hardware if (lineView.begin().stride == 1) ThresholdSharpened(lineView, threshold, binarized); else ThresholdSharpened(lineView, threshold, binarized); GetPatternRow(Range(binarized), res); return true; } // Does not sharpen the data, as this call is intended to only be used by 2D Readers. std::shared_ptr<const BitMatrix> GlobalHistogramBinarizer::getBlackMatrix() const { // Quickly calculates the histogram by sampling four rows from the image. This proved to be // more robust on the blackbox tests than sampling a diagonal as we used to do. Histogram localBuckets = {}; { for (int y = 1; y < 5; y++) { int row = height() * y / 5; const uint8_t* luminances = _buffer.data(0, row); int right = (width() * 4) / 5; for (int x = width() / 5; x < right; x++) localBuckets[luminances[x] >> LUMINANCE_SHIFT]++; } } int blackPoint = EstimateBlackPoint(localBuckets); if (blackPoint <= 0) return {}; return std::make_shared<const BitMatrix>(binarize(blackPoint)); } } // ZXing ```
/content/code_sandbox/core/src/GlobalHistogramBinarizer.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,484
```c++ /* */ #include "MultiFormatReader.h" #include "BarcodeFormat.h" #include "BinaryBitmap.h" #include "ReaderOptions.h" #include "aztec/AZReader.h" #include "datamatrix/DMReader.h" #include "maxicode/MCReader.h" #include "oned/ODReader.h" #include "pdf417/PDFReader.h" #include "qrcode/QRReader.h" #include <memory> namespace ZXing { MultiFormatReader::MultiFormatReader(const ReaderOptions& opts) : _opts(opts) { auto formats = opts.formats().empty() ? BarcodeFormat::Any : opts.formats(); // Put linear readers upfront in "normal" mode if (formats.testFlags(BarcodeFormat::LinearCodes) && !opts.tryHarder()) _readers.emplace_back(new OneD::Reader(opts)); if (formats.testFlags(BarcodeFormat::QRCode | BarcodeFormat::MicroQRCode | BarcodeFormat::RMQRCode)) _readers.emplace_back(new QRCode::Reader(opts, true)); if (formats.testFlag(BarcodeFormat::DataMatrix)) _readers.emplace_back(new DataMatrix::Reader(opts, true)); if (formats.testFlag(BarcodeFormat::Aztec)) _readers.emplace_back(new Aztec::Reader(opts, true)); if (formats.testFlag(BarcodeFormat::PDF417)) _readers.emplace_back(new Pdf417::Reader(opts)); if (formats.testFlag(BarcodeFormat::MaxiCode)) _readers.emplace_back(new MaxiCode::Reader(opts)); // At end in "try harder" mode if (formats.testFlags(BarcodeFormat::LinearCodes) && opts.tryHarder()) _readers.emplace_back(new OneD::Reader(opts)); } MultiFormatReader::~MultiFormatReader() = default; Barcode MultiFormatReader::read(const BinaryBitmap& image) const { Barcode r; for (const auto& reader : _readers) { r = reader->decode(image); if (r.isValid()) return r; } return _opts.returnErrors() ? r : Barcode(); } Barcodes MultiFormatReader::readMultiple(const BinaryBitmap& image, int maxSymbols) const { Barcodes res; for (const auto& reader : _readers) { if (image.inverted() && !reader->supportsInversion) continue; auto r = reader->decode(image, maxSymbols); if (!_opts.returnErrors()) { //TODO: C++20 res.erase_if() auto it = std::remove_if(res.begin(), res.end(), [](auto&& r) { return !r.isValid(); }); res.erase(it, res.end()); } maxSymbols -= Size(r); res.insert(res.end(), std::move_iterator(r.begin()), std::move_iterator(r.end())); if (maxSymbols <= 0) break; } // sort barcodes based on their position on the image std::sort(res.begin(), res.end(), [](const Barcode& l, const Barcode& r) { auto lp = l.position().topLeft(); auto rp = r.position().topLeft(); return lp.y < rp.y || (lp.y == rp.y && lp.x < rp.x); }); return res; } } // ZXing ```
/content/code_sandbox/core/src/MultiFormatReader.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
688
```c++ /* */ #include "BitSource.h" #include "ByteArray.h" #include "ZXAlgorithms.h" #include <stdexcept> namespace ZXing { int BitSource::available() const { return 8 * (Size(_bytes) - _byteOffset) - _bitOffset; } static int ReadBitsImpl(int numBits, const ByteArray& _bytes, int available, int& _byteOffset, int& _bitOffset) { if (numBits < 1 || numBits > 32 || numBits > available) { throw std::out_of_range("BitSource::readBits: out of range"); } int result = 0; // First, read remainder from current byte if (_bitOffset > 0) { int bitsLeft = 8 - _bitOffset; int toRead = numBits < bitsLeft ? numBits : bitsLeft; int bitsToNotRead = bitsLeft - toRead; int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; result = (_bytes[_byteOffset] & mask) >> bitsToNotRead; numBits -= toRead; _bitOffset += toRead; if (_bitOffset == 8) { _bitOffset = 0; _byteOffset++; } } // Next read whole bytes if (numBits > 0) { while (numBits >= 8) { result = (result << 8) | _bytes[_byteOffset]; _byteOffset++; numBits -= 8; } // Finally read a partial byte if (numBits > 0) { int bitsToNotRead = 8 - numBits; int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; result = (result << numBits) | ((_bytes[_byteOffset] & mask) >> bitsToNotRead); _bitOffset += numBits; } } return result; } int BitSource::readBits(int numBits) { return ReadBitsImpl(numBits, _bytes, available(), _byteOffset, _bitOffset); } int BitSource::peakBits(int numBits) const { int bitOffset = _bitOffset; int byteOffset = _byteOffset; return ReadBitsImpl(numBits, _bytes, available(), byteOffset, bitOffset); } } // ZXing ```
/content/code_sandbox/core/src/BitSource.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
513
```objective-c /* */ #pragma once #include "GenericGFPoly.h" #include "ZXConfig.h" #include <stdexcept> #include <vector> namespace ZXing { /** * <p>This class contains utility methods for performing mathematical operations over * the Galois Fields. Operations use a given primitive polynomial in calculations.</p> * * <p>Throughout this package, elements of the GF are represented as an {@code int} * for convenience and speed (but at the cost of memory). * </p> * * @author Sean Owen * @author David Olivier */ class GenericGF { const int _size; int _generatorBase; std::vector<short> _expTable; std::vector<short> _logTable; /** * Create a representation of GF(size) using the given primitive polynomial. * * @param primitive irreducible polynomial whose coefficients are represented by * the bits of an int, where the least-significant bit represents the constant * coefficient * @param size the size of the field (m = log2(size) is called the word size of the encoding) * @param b the factor b in the generator polynomial can be 0- or 1-based * (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))). * In most cases it should be 1, but for QR code it is 0. */ GenericGF(int primitive, int size, int b); public: static const GenericGF& AztecData12(); static const GenericGF& AztecData10(); static const GenericGF& AztecData6(); static const GenericGF& AztecParam(); static const GenericGF& QRCodeField256(); static const GenericGF& DataMatrixField256(); static const GenericGF& AztecData8(); static const GenericGF& MaxiCodeField64(); // note: replaced addOrSubstract calls with '^' / '^='. everyone trying to understand this code needs to look into // Galois Fields with characteristic 2 and will then understand that XOR is addition/subtraction. And those // operators are way more readable than a noisy member function name /** * @return 2 to the power of a in GF(size) */ int exp(int a) const { return _expTable.at(a); } /** * @return base 2 log of a in GF(size) */ int log(int a) const { if (a == 0) { throw std::invalid_argument("a == 0"); } return _logTable.at(a); } /** * @return multiplicative inverse of a */ int inverse(int a) const { return _expTable[_size - log(a) - 1]; } /** * @return product of a and b in GF(size) */ int multiply(int a, int b) const noexcept { if (a == 0 || b == 0) return 0; #ifdef ZX_REED_SOLOMON_USE_MORE_MEMORY_FOR_SPEED return _expTable[_logTable[a] + _logTable[b]]; #else auto fast_mod = [](const int input, const int ceil) { // avoid using the '%' modulo operator => ReedSolomon computation is more than twice as fast // see also path_to_url return input < ceil ? input : input - ceil; }; return _expTable[fast_mod(_logTable[a] + _logTable[b], _size - 1)]; #endif } int size() const noexcept { return _size; } int generatorBase() const noexcept { return _generatorBase; } }; } // namespace ZXing ```
/content/code_sandbox/core/src/GenericGF.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
804
```objective-c /* */ #pragma once namespace ZXing { class BitMatrix; class ResultPoint; /** * <p> * Detects a candidate barcode-like rectangular region within an image. It * starts around the center of the image, increases the size of the candidate * region until it finds a white rectangular region. * </p> * * @param image barcode image to find a rectangle in * @param initSize initial size of search area around center * @param x x position of search center * @param y y position of search center * @return {@link ResultPoint}[] describing the corners of the rectangular * region. The first and last points are opposed on the diagonal, as * are the second and third. The first point will be the topmost * point and the last, the bottommost. The second point will be * leftmost and the third, the rightmost * @return true iff white rect was found */ bool DetectWhiteRect(const BitMatrix& image, int initSize, int x, int y, ResultPoint& p0, ResultPoint& p1, ResultPoint& p2, ResultPoint& p3); bool DetectWhiteRect(const BitMatrix& image, ResultPoint& p0, ResultPoint& p1, ResultPoint& p2, ResultPoint& p3); } // ZXing ```
/content/code_sandbox/core/src/WhiteRectDetector.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
288
```objective-c /* */ #pragma once #include <cassert> #include <cstdint> #include <cstring> #include <vector> #if __has_include(<bit>) && __cplusplus > 201703L // MSVC has the <bit> header but then warns about including it #include <bit> #if __cplusplus > 201703L && defined(__ANDROID__) // NDK 25.1.8937393 has the implementation but fails to advertise it #define __cpp_lib_bitops 201907L #endif #endif #if defined(__clang__) || defined(__GNUC__) #define ZX_HAS_GCC_BUILTINS #elif defined(_MSC_VER) && !defined(_M_ARM) && !defined(_M_ARM64) #include <intrin.h> #define ZX_HAS_MSC_BUILTINS #endif namespace ZXing::BitHacks { /** * The code below is taken from path_to_url~seander/bithacks.html * All credits go to Sean Eron Anderson and other authors mentioned in that page. */ /// <summary> /// Compute the number of zero bits on the left. /// </summary> template<typename T, typename = std::enable_if_t<std::is_integral_v<T>>> inline int NumberOfLeadingZeros(T x) { #ifdef __cpp_lib_bitops return std::countl_zero(static_cast<std::make_unsigned_t<T>>(x)); #else if constexpr (sizeof(x) <= 4) { static_assert(sizeof(x) == 4, "NumberOfLeadingZeros not implemented for 8 and 16 bit ints."); if (x == 0) return 32; #ifdef ZX_HAS_GCC_BUILTINS return __builtin_clz(x); #elif defined(ZX_HAS_MSC_BUILTINS) unsigned long where; if (_BitScanReverse(&where, x)) return 31 - static_cast<int>(where); return 32; #else int n = 0; if ((x & 0xFFFF0000) == 0) { n = n + 16; x = x << 16; } if ((x & 0xFF000000) == 0) { n = n + 8; x = x << 8; } if ((x & 0xF0000000) == 0) { n = n + 4; x = x << 4; } if ((x & 0xC0000000) == 0) { n = n + 2; x = x << 2; } if ((x & 0x80000000) == 0) { n = n + 1; } return n; #endif } else { if (x == 0) return 64; #ifdef ZX_HAS_GCC_BUILTINS return __builtin_clzll(x); #else // including ZX_HAS_MSC_BUILTINS int n = NumberOfLeadingZeros(static_cast<uint32_t>(x >> 32)); if (n == 32) n += NumberOfLeadingZeros(static_cast<uint32_t>(x)); return n; #endif } #endif } /// <summary> /// Compute the number of zero bits on the right. /// </summary> template<typename T, typename = std::enable_if_t<std::is_integral_v<T>>> inline int NumberOfTrailingZeros(T v) { #ifdef __cpp_lib_bitops return std::countr_zero(static_cast<std::make_unsigned_t<T>>(v)); #else if constexpr (sizeof(v) <= 4) { static_assert(sizeof(v) == 4, "NumberOfTrailingZeros not implemented for 8 and 16 bit ints."); #ifdef ZX_HAS_GCC_BUILTINS return v == 0 ? 32 : __builtin_ctz(v); #elif defined(ZX_HAS_MSC_BUILTINS) unsigned long where; if (_BitScanForward(&where, v)) return static_cast<int>(where); return 32; #else int c = 32; v &= -int32_t(v); if (v) c--; if (v & 0x0000FFFF) c -= 16; if (v & 0x00FF00FF) c -= 8; if (v & 0x0F0F0F0F) c -= 4; if (v & 0x33333333) c -= 2; if (v & 0x55555555) c -= 1; return c; #endif } else { #ifdef ZX_HAS_GCC_BUILTINS return v == 0 ? 64 : __builtin_ctzll(v); #else // including ZX_HAS_MSC_BUILTINS int n = NumberOfTrailingZeros(static_cast<uint32_t>(v)); if (n == 32) n += NumberOfTrailingZeros(static_cast<uint32_t>(v >> 32)); return n; #endif } #endif } inline uint32_t Reverse(uint32_t v) { #if 0 return __builtin_bitreverse32(v); #else v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1); // swap consecutive pairs v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2); // swap nibbles ... v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); // swap bytes v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8); // swap 2-byte long pairs v = (v >> 16) | (v << 16); return v; #endif } inline int CountBitsSet(uint32_t v) { #ifdef __cpp_lib_bitops return std::popcount(v); #elif defined(ZX_HAS_GCC_BUILTINS) return __builtin_popcount(v); #else v = v - ((v >> 1) & 0x55555555); // reuse input as temporary v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; // count #endif } // this is the same as log base 2 of v inline int HighestBitSet(uint32_t v) { return 31 - NumberOfLeadingZeros(v); } // shift a whole array of bits by offset bits to the right (thinking of the array as a contiguous stream of bits // starting with the LSB of the first int and ending with the MSB of the last int, this is actually a left shift) template <typename T> void ShiftRight(std::vector<T>& bits, std::size_t offset) { assert(offset < sizeof(T) * 8); if (offset == 0 || bits.empty()) return; std::size_t leftOffset = sizeof(T) * 8 - offset; for (std::size_t i = 0; i < bits.size() - 1; ++i) { bits[i] = (bits[i] >> offset) | (bits[i + 1] << leftOffset); } bits.back() >>= offset; } // reverse a whole array of bits. padding is the number of 'dummy' bits at the end of the array template <typename T> void Reverse(std::vector<T>& bits, std::size_t padding) { static_assert(sizeof(T) == sizeof(uint32_t), "Reverse only implemented for 32 bit types"); // reverse all int's first (reversing the ints in the array and the bits in the ints at the same time) auto first = bits.begin(), last = bits.end(); for (; first < --last; ++first) { auto t = *first; *first = BitHacks::Reverse(*last); *last = BitHacks::Reverse(t); } if (first == last) *last = BitHacks::Reverse(*last); // now correct the int's if the bit size isn't a multiple of 32 ShiftRight(bits, padding); } // use to avoid "load of misaligned address" when using a simple type cast template <typename T> T LoadU(const void* ptr) { static_assert(std::is_integral<T>::value, "T must be an integer"); T res; memcpy(&res, ptr, sizeof(T)); return res; } } // namespace ZXing::BitHacks ```
/content/code_sandbox/core/src/BitHacks.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,881
```objective-c /* */ #pragma once #include "BarcodeFormat.h" #include "ByteArray.h" #include "Content.h" #include "ReaderOptions.h" #include "Error.h" #include "ImageView.h" #include "Quadrilateral.h" #include "StructuredAppend.h" #ifdef ZXING_EXPERIMENTAL_API #include <memory> extern "C" struct zint_symbol; namespace ZXing { class BitMatrix; } struct zint_symbol_deleter { void operator()(zint_symbol* p) const noexcept; }; using unique_zint_symbol = std::unique_ptr<zint_symbol, zint_symbol_deleter>; #endif #include <string> #include <vector> namespace ZXing { class DecoderResult; class DetectorResult; class WriterOptions; class Result; // TODO: 3.0 replace deprected symbol name using Position = QuadrilateralI; using Barcode = Result; using Barcodes = std::vector<Barcode>; using Results = std::vector<Result>; /** * @brief The Barcode class encapsulates the result of decoding a barcode within an image. */ class Result { void setIsInverted(bool v) { _isInverted = v; } Result& setReaderOptions(const ReaderOptions& opts); friend Barcode MergeStructuredAppendSequence(const Barcodes&); friend Barcodes ReadBarcodes(const ImageView&, const ReaderOptions&); friend Image WriteBarcodeToImage(const Barcode&, const WriterOptions&); friend void IncrementLineCount(Barcode&); public: Result() = default; // linear symbology convenience constructor Result(const std::string& text, int y, int xStart, int xStop, BarcodeFormat format, SymbologyIdentifier si, Error error = {}, bool readerInit = false); Result(DecoderResult&& decodeResult, DetectorResult&& detectorResult, BarcodeFormat format); [[deprecated]] Result(DecoderResult&& decodeResult, Position&& position, BarcodeFormat format); bool isValid() const; const Error& error() const { return _error; } BarcodeFormat format() const { return _format; } /** * @brief bytes is the raw / standard content without any modifications like character set conversions */ const ByteArray& bytes() const; /** * @brief bytesECI is the raw / standard content following the ECI protocol */ ByteArray bytesECI() const; /** * @brief text returns the bytes() content rendered to unicode/utf8 text accoring to specified TextMode */ std::string text(TextMode mode) const; /** * @brief text returns the bytes() content rendered to unicode/utf8 text accoring to the TextMode set in the ReaderOptions */ std::string text() const; /** * @brief ecLevel returns the error correction level of the symbol (empty string if not applicable) */ std::string ecLevel() const; /** * @brief contentType gives a hint to the type of content found (Text/Binary/GS1/etc.) */ ContentType contentType() const; /** * @brief hasECI specifies wheter or not an ECI tag was found */ bool hasECI() const; const Position& position() const { return _position; } void setPosition(Position pos) { _position = pos; } /** * @brief orientation of barcode in degree, see also Position::orientation() */ int orientation() const; /** * @brief isMirrored is the symbol mirrored (currently only supported by QRCode and DataMatrix) */ bool isMirrored() const { return _isMirrored; } /** * @brief isInverted is the symbol inverted / has reveresed reflectance (see ReaderOptions::tryInvert) */ bool isInverted() const { return _isInverted; } /** * @brief symbologyIdentifier Symbology identifier "]cm" where "c" is symbology code character, "m" the modifier. */ std::string symbologyIdentifier() const; /** * @brief sequenceSize number of symbols in a structured append sequence. * * If this is not part of a structured append sequence, the returned value is -1. * If it is a structured append symbol but the total number of symbols is unknown, the * returned value is 0 (see PDF417 if optional "Segment Count" not given). */ int sequenceSize() const; /** * @brief sequenceIndex the 0-based index of this symbol in a structured append sequence. */ int sequenceIndex() const; /** * @brief sequenceId id to check if a set of symbols belongs to the same structured append sequence. * * If the symbology does not support this feature, the returned value is empty (see MaxiCode). * For QR Code, this is the parity integer converted to a string. * For PDF417 and DataMatrix, this is the "fileId". */ std::string sequenceId() const; bool isLastInSequence() const { return sequenceSize() == sequenceIndex() + 1; } bool isPartOfSequence() const { return sequenceSize() > -1 && sequenceIndex() > -1; } /** * @brief readerInit Set if Reader Initialisation/Programming symbol. */ bool readerInit() const { return _readerInit; } /** * @brief lineCount How many lines have been detected with this code (applies only to linear symbologies) */ int lineCount() const { return _lineCount; } /** * @brief version QRCode / DataMatrix / Aztec version or size. */ std::string version() const; #ifdef ZXING_EXPERIMENTAL_API void symbol(BitMatrix&& bits); ImageView symbol() const; void zint(unique_zint_symbol&& z); zint_symbol* zint() const { return _zint.get(); } #endif bool operator==(const Result& o) const; private: Content _content; Error _error; Position _position; ReaderOptions _readerOpts; // TODO: 3.0 switch order to prevent 4 padding bytes StructuredAppendInfo _sai; BarcodeFormat _format = BarcodeFormat::None; char _ecLevel[4] = {}; char _version[4] = {}; int _lineCount = 0; bool _isMirrored = false; bool _isInverted = false; bool _readerInit = false; #ifdef ZXING_EXPERIMENTAL_API std::shared_ptr<BitMatrix> _symbol; std::shared_ptr<zint_symbol> _zint; #endif }; /** * @brief Merge a list of Barcodes from one Structured Append sequence to a single barcode */ Barcode MergeStructuredAppendSequence(const Barcodes& results); /** * @brief Automatically merge all Structured Append sequences found in the given list of barcodes */ Barcodes MergeStructuredAppendSequences(const Barcodes& barcodes); } // ZXing ```
/content/code_sandbox/core/src/Barcode.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,454
```objective-c /* */ #pragma once #include "BinaryBitmap.h" namespace ZXing { /** * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding * algorithm. However, because it picks a global black point, it cannot handle difficult shadows * and gradients. * * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ class GlobalHistogramBinarizer : public BinaryBitmap { public: explicit GlobalHistogramBinarizer(const ImageView& buffer); ~GlobalHistogramBinarizer() override; bool getPatternRow(int row, int rotation, PatternRow &res) const override; std::shared_ptr<const BitMatrix> getBlackMatrix() const override; }; } // ZXing ```
/content/code_sandbox/core/src/GlobalHistogramBinarizer.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
196
```objective-c /* */ #pragma once #include "ByteArray.h" #include "CharacterSet.h" #include "ReaderOptions.h" #include <string> #include <vector> namespace ZXing { enum class ECI : int; enum class ContentType { Text, Binary, Mixed, GS1, ISO15434, UnknownECI }; enum class AIFlag : char { None, GS1, AIM }; std::string ToString(ContentType type); struct SymbologyIdentifier { char code = 0, modifier = 0, eciModifierOffset = 0; AIFlag aiFlag = AIFlag::None; std::string toString(bool hasECI = false) const { return code ? ']' + std::string(1, code) + static_cast<char>(modifier + eciModifierOffset * hasECI) : std::string(); } }; class Content { template <typename FUNC> void ForEachECIBlock(FUNC f) const; void switchEncoding(ECI eci, bool isECI); std::string render(bool withECI) const; public: struct Encoding { ECI eci; int pos; }; ByteArray bytes; std::vector<Encoding> encodings; SymbologyIdentifier symbology; CharacterSet defaultCharset = CharacterSet::Unknown; bool hasECI = false; Content(); Content(ByteArray&& bytes, SymbologyIdentifier si); void switchEncoding(ECI eci) { switchEncoding(eci, true); } void switchEncoding(CharacterSet cs); void reserve(int count) { bytes.reserve(bytes.size() + count); } void push_back(uint8_t val) { bytes.push_back(val); } void append(const std::string& str) { bytes.insert(bytes.end(), str.begin(), str.end()); } void append(const ByteArray& ba) { bytes.insert(bytes.end(), ba.begin(), ba.end()); } void append(const Content& other); void operator+=(char val) { push_back(val); } void operator+=(const std::string& str) { append(str); } void erase(int pos, int n); void insert(int pos, const std::string& str); bool empty() const { return bytes.empty(); } bool canProcess() const; std::string text(TextMode mode) const; std::wstring utfW() const; // utf16 or utf32 depending on the platform, i.e. on size_of(wchar_t) std::string utf8() const { return render(false); } ByteArray bytesECI() const; CharacterSet guessEncoding() const; ContentType type() const; }; } // ZXing ```
/content/code_sandbox/core/src/Content.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
540
```objective-c /* */ #pragma once #include "Version.h" #pragma message("Header `ZXVersion.h` is deprecated, please include `Version.h`.") ```
/content/code_sandbox/core/src/ZXVersion.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
30
```objective-c /* */ #pragma once #include <string> #include <string_view> namespace ZXing { std::string HRIFromGS1(std::string_view gs1); std::string HRIFromISO15434(std::string_view str); } // namespace ZXing ```
/content/code_sandbox/core/src/HRI.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
55
```c++ /* */ #include "GTIN.h" #include "Barcode.h" #include <algorithm> #include <iomanip> #include <iterator> #include <sstream> #include <string> namespace ZXing::GTIN { struct CountryId { uint16_t first; uint16_t last; const char id[3]; }; bool operator<(const CountryId& lhs, const CountryId& rhs) { return lhs.last < rhs.last; } // path_to_url (as of 7 Feb 2022) // and path_to_url static const CountryId COUNTRIES[] = { // clang-format off {1, 19, "US"}, {30, 39, "US"}, {60, 99, "US"}, // Note 99 coupon identification {100, 139, "US"}, {300, 379, "FR"}, // France (and Monaco according to Wikipedia) {380, 380, "BG"}, // Bulgaria {383, 383, "SI"}, // Slovenia {385, 385, "HR"}, // Croatia {387, 387, "BA"}, // Bosnia and Herzegovina {389, 389, "ME"}, // Montenegro //{390, 390, "XK"}, // (Kosovo according to Wikipedia, unsourced) {400, 440, "DE"}, // Germany {450, 459, "JP"}, // Japan {460, 469, "RU"}, // Russia {470, 470, "KG"}, // Kyrgyzstan {471, 471, "TW"}, // Taiwan {474, 474, "EE"}, // Estonia {475, 475, "LV"}, // Latvia {476, 476, "AZ"}, // Azerbaijan {477, 477, "LT"}, // Lithuania {478, 478, "UZ"}, // Uzbekistan {479, 479, "LK"}, // Sri Lanka {480, 480, "PH"}, // Philippines {481, 481, "BY"}, // Belarus {482, 482, "UA"}, // Ukraine {483, 483, "TM"}, // Turkmenistan {484, 484, "MD"}, // Moldova {485, 485, "AM"}, // Armenia {486, 486, "GE"}, // Georgia {487, 487, "KZ"}, // Kazakhstan {488, 488, "TJ"}, // Tajikistan {489, 489, "HK"}, // Hong Kong {490, 499, "JP"}, // Japan {500, 509, "GB"}, // UK {520, 521, "GR"}, // Greece {528, 528, "LB"}, // Lebanon {529, 529, "CY"}, // Cyprus {530, 530, "AL"}, // Albania {531, 531, "MK"}, // North Macedonia {535, 535, "MT"}, // Malta {539, 539, "IE"}, // Ireland {540, 549, "BE"}, // Belgium & Luxembourg {560, 560, "PT"}, // Portugal {569, 569, "IS"}, // Iceland {570, 579, "DK"}, // Denmark (and Faroe Islands and Greenland according to Wikipedia) {590, 590, "PL"}, // Poland {594, 594, "RO"}, // Romania {599, 599, "HU"}, // Hungary {600, 601, "ZA"}, // South Africa {603, 603, "GH"}, // Ghana {604, 604, "SN"}, // Senegal {608, 608, "BH"}, // Bahrain {609, 609, "MU"}, // Mauritius {611, 611, "MA"}, // Morocco {613, 613, "DZ"}, // Algeria {615, 615, "NG"}, // Nigeria {616, 616, "KE"}, // Kenya {617, 617, "CM"}, // Cameroon {618, 618, "CI"}, // Cte d'Ivoire {619, 619, "TN"}, // Tunisia {620, 620, "TZ"}, // Tanzania {621, 621, "SY"}, // Syria {622, 622, "EG"}, // Egypt {623, 623, "BN"}, // Brunei {624, 624, "LY"}, // Libya {625, 625, "JO"}, // Jordan {626, 626, "IR"}, // Iran {627, 627, "KW"}, // Kuwait {628, 628, "SA"}, // Saudi Arabia {629, 629, "AE"}, // United Arab Emirates {630, 630, "QA"}, // Qatar {631, 631, "NA"}, // Namibia {640, 649, "FI"}, // Finland {690, 699, "CN"}, // China {700, 709, "NO"}, // Norway {729, 729, "IL"}, // Israel {730, 739, "SE"}, // Sweden {740, 740, "GT"}, // Guatemala {741, 741, "SV"}, // El Salvador {742, 742, "HN"}, // Honduras {743, 743, "NI"}, // Nicaragua {744, 744, "CR"}, // Costa Rica {745, 745, "PA"}, // Panama {746, 746, "DO"}, // Dominican Republic {750, 750, "MX"}, // Mexico {754, 755, "CA"}, // Canada {759, 759, "VE"}, // Venezuela {760, 769, "CH"}, // Switzerland (and Liechtenstein according to Wikipedia) {770, 771, "CO"}, // Colombia {773, 773, "UY"}, // Uruguay {775, 775, "PE"}, // Peru {777, 777, "BO"}, // Bolivia {778, 779, "AR"}, // Argentina {780, 780, "CL"}, // Chile {784, 784, "PY"}, // Paraguay {786, 786, "EC"}, // Ecuador {789, 790, "BR"}, // Brazil {800, 839, "IT"}, // Italy (and San Marino and Vatican City according to Wikipedia) {840, 849, "ES"}, // Spain (and Andorra according to Wikipedia) {850, 850, "CU"}, // Cuba {858, 858, "SK"}, // Slovakia {859, 859, "CZ"}, // Czechia {860, 860, "RS"}, // Serbia {865, 865, "MN"}, // Mongolia {867, 867, "KP"}, // North Korea {868, 869, "TR"}, // Turkey {870, 879, "NL"}, // Netherlands {880, 880, "KR"}, // South Korea {883, 883, "MM"}, // Myanmar {884, 884, "KH"}, // Cambodia {885, 885, "TH"}, // Thailand {888, 888, "SG"}, // Singapore {890, 890, "IN"}, // India {893, 893, "VN"}, // Vietnam {896, 896, "PK"}, // Pakistan {899, 899, "ID"}, // Indonesia {900, 919, "AT"}, // Austria {930, 939, "AU"}, // Australia {940, 949, "NZ"}, // New Zealand {955, 955, "MY"}, // Malaysia {958, 958, "MO"}, // Macao //{960, 961, "GB"}, // Global Office - assigned to GS1 UK for GTIN-8 allocations (also 9620-9624999) // clang-format on }; std::string LookupCountryIdentifier(const std::string& GTIN, const BarcodeFormat format) { // Ignore add-on if any const auto space = GTIN.find(' '); const std::string::size_type size = space != std::string::npos ? space : GTIN.size(); if (size != 14 && size != 13 && size != 12 && size != 8) return {}; // GTIN-14 leading packaging level indicator const int first = size == 14 ? 1 : 0; // UPC-A/E implicit leading 0 const int implicitZero = size == 12 || (size == 8 && format != BarcodeFormat::EAN8) ? 1 : 0; if (size != 8 || format != BarcodeFormat::EAN8) { // Assuming following doesn't apply to EAN-8 // 0000000 Restricted Circulation Numbers; 0000001-0000099 unused to avoid collision with GTIN-8 int prefix = std::stoi(GTIN.substr(first, 7 - implicitZero)); if (prefix >= 0 && prefix <= 99) return {}; // 00001-00009 US prefix = std::stoi(GTIN.substr(first, 5 - implicitZero)); if (prefix >= 1 && prefix <= 9) return "US"; // 0001-0009 US prefix = std::stoi(GTIN.substr(first, 4 - implicitZero)); if (prefix >= 1 && prefix <= 9) return "US"; } const int prefix = std::stoi(GTIN.substr(first, 3 - implicitZero)); // Special case EAN-8 for prefix < 100 (GS1 General Specifications Figure 1.4.3-1) if (size == 8 && format == BarcodeFormat::EAN8 && prefix <= 99) // Restricted Circulation Numbers return {}; const auto it = std::lower_bound(std::begin(COUNTRIES), std::end(COUNTRIES), CountryId{0, narrow_cast<uint16_t>(prefix), ""}); return it != std::end(COUNTRIES) && prefix >= it->first && prefix <= it->last ? it->id : std::string(); } std::string EanAddOn(const Barcode& barcode) { if (!(BarcodeFormat::EAN13 | BarcodeFormat::UPCA | BarcodeFormat::UPCE | BarcodeFormat::EAN8).testFlag(barcode.format())) return {}; auto txt = barcode.bytes().asString(); auto pos = txt.find(' '); return pos != std::string::npos ? std::string(txt.substr(pos + 1)) : std::string(); } std::string IssueNr(const std::string& ean2AddOn) { if (ean2AddOn.size() != 2) return {}; return std::to_string(std::stoi(ean2AddOn)); } std::string Price(const std::string& ean5AddOn) { if (ean5AddOn.size() != 5) return {}; std::string currency; switch (ean5AddOn.front()) { case '0': [[fallthrough]]; case '1': currency = "GBP "; break; // UK case '3': currency = "AUD $"; break; // AUS case '4': currency = "NZD $"; break; // NZ case '5': currency = "USD $"; break; // US case '6': currency = "CAD $"; break; // CA case '9': // Reference: path_to_url if (ean5AddOn == "90000") // No suggested retail price return {}; if (ean5AddOn == "99991") // Complementary return "0.00"; if (ean5AddOn == "99990") return "Used"; // Otherwise... unknown currency? currency = ""; break; default: currency = ""; break; } int rawAmount = std::stoi(ean5AddOn.substr(1)); std::stringstream buf; buf << currency << std::fixed << std::setprecision(2) << (float(rawAmount) / 100); return buf.str(); } } // namespace ZXing::GTIN ```
/content/code_sandbox/core/src/GTIN.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,745
```c++ /* */ #include "HRI.h" #include "ZXAlgorithms.h" #include <cmath> #include <cstring> #include <string_view> namespace ZXing { struct AiInfo { const char aiPrefix[5]; int8_t _fieldSize; // if negative, the length is variable and abs(length) give the max size bool isVariableLength() const noexcept { return _fieldSize < 0; } int fieldSize() const noexcept { return std::abs(_fieldSize); } int aiSize() const { using namespace std::literals; if ((aiPrefix[0] == '3' && Contains("1234569", aiPrefix[1])) || aiPrefix == "703"sv || aiPrefix == "723"sv) return 4; else return strlen(aiPrefix); } }; // path_to_url 2023-09-22 static const AiInfo aiInfos[] = { //TWO_DIGIT_DATA_LENGTH { "00", 18 }, { "01", 14 }, { "02", 14 }, { "10", -20 }, { "11", 6 }, { "12", 6 }, { "13", 6 }, { "15", 6 }, { "16", 6 }, { "17", 6 }, { "20", 2 }, { "21", -20 }, { "22", -20 }, { "30", -8 }, { "37", -8 }, { "90", -30 }, { "91", -90 }, { "92", -90 }, { "93", -90 }, { "94", -90 }, { "95", -90 }, { "96", -90 }, { "97", -90 }, { "98", -90 }, { "99", -90 }, //THREE_DIGIT_DATA_LENGTH { "235", -28 }, { "240", -30 }, { "241", -30 }, { "242", -6 }, { "243", -20 }, { "250", -30 }, { "251", -30 }, { "253", -30 }, { "254", -20 }, { "255", -25 }, { "400", -30 }, { "401", -30 }, { "402", 17 }, { "403", -30 }, { "410", 13 }, { "411", 13 }, { "412", 13 }, { "413", 13 }, { "414", 13 }, { "415", 13 }, { "416", 13 }, { "417", 13 }, { "420", -20 }, { "421", -12 }, { "422", 3 }, { "423", -15 }, { "424", 3 }, { "425", -15 }, { "426", 3 }, { "427", -3 }, { "710", -20 }, { "711", -20 }, { "712", -20 }, { "713", -20 }, { "714", -20 }, { "715", -20 }, //THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH { "310", 6 }, { "311", 6 }, { "312", 6 }, { "313", 6 }, { "314", 6 }, { "315", 6 }, { "316", 6 }, { "320", 6 }, { "321", 6 }, { "322", 6 }, { "323", 6 }, { "324", 6 }, { "325", 6 }, { "326", 6 }, { "327", 6 }, { "328", 6 }, { "329", 6 }, { "330", 6 }, { "331", 6 }, { "332", 6 }, { "333", 6 }, { "334", 6 }, { "335", 6 }, { "336", 6 }, { "337", 6 }, { "340", 6 }, { "341", 6 }, { "342", 6 }, { "343", 6 }, { "344", 6 }, { "345", 6 }, { "346", 6 }, { "347", 6 }, { "348", 6 }, { "349", 6 }, { "350", 6 }, { "351", 6 }, { "352", 6 }, { "353", 6 }, { "354", 6 }, { "355", 6 }, { "356", 6 }, { "357", 6 }, { "360", 6 }, { "361", 6 }, { "362", 6 }, { "363", 6 }, { "364", 6 }, { "365", 6 }, { "366", 6 }, { "367", 6 }, { "368", 6 }, { "369", 6 }, { "390", -15 }, { "391", -18 }, { "392", -15 }, { "393", -18 }, { "394", 4 }, { "395", 6 }, { "703", -30 }, { "723", -30 }, //FOUR_DIGIT_DATA_LENGTH { "4300", -35 }, { "4301", -35 }, { "4302", -70 }, { "4303", -70 }, { "4304", -70 }, { "4305", -70 }, { "4306", -70 }, { "4307", 2 }, { "4308", -30 }, { "4309", 20 }, { "4310", -35 }, { "4311", -35 }, { "4312", -70 }, { "4313", -70 }, { "4314", -70 }, { "4315", -70 }, { "4316", -70 }, { "4317", 2 }, { "4318", -20 }, { "4319", -30 }, { "4320", -35 }, { "4321", 1 }, { "4322", 1 }, { "4323", 1 }, { "4324", 10 }, { "4325", 10 }, { "4326", 6 }, { "4330", -7 }, { "4331", -7 }, { "4332", -7 }, { "4333", -7 }, { "7001", 13 }, { "7002", -30 }, { "7003", 10 }, { "7004", -4 }, { "7005", -12 }, { "7006", 6 }, { "7007", -12 }, { "7008", -3 }, { "7009", -10 }, { "7010", -2 }, { "7011", -10 }, { "7020", -20 }, { "7021", -20 }, { "7022", -20 }, { "7023", -30 }, { "7040", 4 }, { "7240", -20 }, { "7241", 2 }, { "7242", -25 }, { "8001", 14 }, { "8002", -20 }, { "8003", -30 }, { "8004", -30 }, { "8005", 6 }, { "8006", 18 }, { "8007", -34 }, { "8008", -12 }, { "8009", -50 }, { "8010", -30 }, { "8011", -12 }, { "8012", -20 }, { "8013", -25 }, { "8017", 18 }, { "8018", 18 }, { "8019", -10 }, { "8020", -25 }, { "8026", 18 }, { "8030", -90 }, { "8110", -70 }, { "8111", 4 }, { "8112", -70 }, { "8200", -70 }, }; std::string HRIFromGS1(std::string_view gs1) { //TODO: c++20 auto starts_with = [](std::string_view str, std::string_view pre) { return str.substr(0, pre.size()) == pre; }; constexpr char GS = 29; // GS character (29 / 0x1D) std::string_view rem = gs1; std::string res; while (rem.size()) { const AiInfo* i = FindIf(aiInfos, [&](const AiInfo& i) { return starts_with(rem, i.aiPrefix); }); if (i == std::end(aiInfos)) return {}; int aiSize = i->aiSize(); if (Size(rem) < aiSize) return {}; res += '('; res += rem.substr(0, aiSize); res += ')'; rem.remove_prefix(aiSize); int fieldSize = i->fieldSize(); if (i->isVariableLength()) { auto gsPos = rem.find(GS); #if 1 fieldSize = std::min(gsPos == std::string_view::npos ? Size(rem) : narrow_cast<int>(gsPos), fieldSize); #else // TODO: ignore the 'max field size' part for now as it breaks rssexpanded-3/13.png? fieldSize = gsPos == std::string_view::npos ? Size(rem) : narrow_cast<int>(gsPos); #endif } if (fieldSize == 0 || Size(rem) < fieldSize) return {}; res += rem.substr(0, fieldSize); rem.remove_prefix(fieldSize); // See General Specification v22.0 Section 7.8.6.3: "...the processing routine SHALL tolerate a single separator character // immediately following any element string, whether necessary or not..." if (Size(rem) && rem.front() == GS) rem.remove_prefix(1); } return res; } std::string HRIFromISO15434(std::string_view str) { // Use available unicode symbols to simulate sub- and superscript letters as specified in // ISO/IEC 15434:2019(E) 6. Human readable representation std::string res; res.reserve(str.size()); for (char c : str) { #if 1 if (0 <= c && c <= 0x20) (res += "\xe2\x90") += char(0x80 + c); // Unicode Block Control Pictures: 0x2400 else res += c; #else switch (c) { case 4: oss << u8"\u1d31\u1d52\u209c"; break; // EOT case 28: oss << u8"\ua7f3\u209b"; break; // FS case 29: oss << u8"\u1d33\u209b"; break; // GS case 30: oss << u8"\u1d3f\u209b"; break; // RS case 31: oss << u8"\u1d41\u209b"; break; // US default: oss << c; } #endif } return res; } } // namespace ZXing ```
/content/code_sandbox/core/src/HRI.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
2,580
```objective-c /* */ #pragma once #include "GenericGFPoly.h" #include <list> #include <vector> namespace ZXing { // public only for testing purposes class ReedSolomonEncoder { public: explicit ReedSolomonEncoder(const GenericGF& field); void encode(std::vector<int>& message, int numECCodeWords); private: const GenericGF* _field; std::list<GenericGFPoly> _cachedGenerators; const GenericGFPoly& buildGenerator(int degree); }; /** * @brief ReedSolomonEncode replaces the last numECCodeWords code words in message with error correction code words */ inline void ReedSolomonEncode(const GenericGF& field, std::vector<int>& message, int numECCodeWords) { ReedSolomonEncoder(field).encode(message, numECCodeWords); } } // namespace ZXing ```
/content/code_sandbox/core/src/ReedSolomonEncoder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
178
```objective-c /* */ #pragma once #include "BinaryBitmap.h" #include "BitMatrix.h" #include <cstdint> namespace ZXing { class ThresholdBinarizer : public BinaryBitmap { const uint8_t _threshold = 0; public: ThresholdBinarizer(const ImageView& buffer, uint8_t threshold = 128) : BinaryBitmap(buffer), _threshold(threshold) {} bool getPatternRow(int row, int rotation, PatternRow& res) const override { auto buffer = _buffer.rotated(rotation); const int stride = buffer.pixStride(); const uint8_t* begin = buffer.data(0, row) + GreenIndex(buffer.format()); const uint8_t* end = begin + buffer.width() * stride; auto* lastPos = begin; bool lastVal = false; res.clear(); for (const uint8_t* p = begin; p != end; p += stride) { bool val = *p <= _threshold; if (val != lastVal) { res.push_back(narrow_cast<PatternRow::value_type>((p - lastPos) / stride)); lastVal = val; lastPos = p; } } res.push_back(narrow_cast<PatternRow::value_type>((end - lastPos) / stride)); if (*(end - stride) <= _threshold) res.push_back(0); // last value is number of white pixels, here 0 return true; } std::shared_ptr<const BitMatrix> getBlackMatrix() const override { return std::make_shared<const BitMatrix>(binarize(_threshold)); } }; } // ZXing ```
/content/code_sandbox/core/src/ThresholdBinarizer.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
353
```objective-c /* */ #pragma once #include <cstdint> #include <cstdio> #include <string> #include <string_view> #include <vector> namespace ZXing { /** ByteArray is an extension of std::vector<unsigned char>. */ class ByteArray : public std::vector<uint8_t> { public: ByteArray() = default; ByteArray(std::initializer_list<uint8_t> list) : std::vector<uint8_t>(list) {} explicit ByteArray(int len) : std::vector<uint8_t>(len, 0) {} explicit ByteArray(const std::string& str) : std::vector<uint8_t>(str.begin(), str.end()) {} void append(const ByteArray& other) { insert(end(), other.begin(), other.end()); } std::string_view asString(size_t pos = 0, size_t len = std::string_view::npos) const { return std::string_view(reinterpret_cast<const char*>(data()), size()).substr(pos, len); } }; inline std::string ToHex(const ByteArray& bytes) { std::string res(bytes.size() * 3, ' '); for (size_t i = 0; i < bytes.size(); ++i) { #ifdef _MSC_VER sprintf_s(&res[i * 3], 4, "%02X ", bytes[i]); #else snprintf(&res[i * 3], 4, "%02X ", bytes[i]); #endif } return res.substr(0, res.size()-1); } } // ZXing ```
/content/code_sandbox/core/src/ByteArray.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
311
```c++ /* */ #include "ReedSolomonDecoder.h" #include "GenericGF.h" #include "ZXConfig.h" #include <algorithm> #include <stdexcept> #include <utility> namespace ZXing { static bool RunEuclideanAlgorithm(const GenericGF& field, std::vector<int>&& rCoefs, GenericGFPoly& sigma, GenericGFPoly& omega) { int R = Size(rCoefs); // == numECCodeWords GenericGFPoly r(field, std::move(rCoefs)); GenericGFPoly& tLast = omega.setField(field); GenericGFPoly& t = sigma.setField(field); ZX_THREAD_LOCAL GenericGFPoly q, rLast; rLast.setField(field); q.setField(field); rLast.setMonomial(1, R); tLast.setMonomial(0); t.setMonomial(1); // Assume r's degree is < rLast's if (r.degree() >= rLast.degree()) swap(r, rLast); // Run Euclidean algorithm until r's degree is less than R/2 while (r.degree() >= R / 2) { swap(tLast, t); swap(rLast, r); // Divide rLastLast by rLast, with quotient in q and remainder in r if (rLast.isZero()) return false; // Oops, Euclidean algorithm already terminated? r.divide(rLast, q); q.multiply(tLast); q.addOrSubtract(t); swap(t, q); // t = q if (r.degree() >= rLast.degree()) throw std::runtime_error("Division algorithm failed to reduce polynomial?"); } int sigmaTildeAtZero = t.constant(); if (sigmaTildeAtZero == 0) return false; int inverse = field.inverse(sigmaTildeAtZero); t.multiplyByMonomial(inverse); r.multiplyByMonomial(inverse); // sigma is t omega = std::move(r); return true; } static std::vector<int> FindErrorLocations(const GenericGF& field, const GenericGFPoly& errorLocator) { // This is a direct application of Chien's search int numErrors = errorLocator.degree(); std::vector<int> res; res.reserve(numErrors); for (int i = 1; i < field.size() && Size(res) < numErrors; i++) if (errorLocator.evaluateAt(i) == 0) res.push_back(field.inverse(i)); if (Size(res) != numErrors) return {}; // Error locator degree does not match number of roots return res; } static std::vector<int> FindErrorMagnitudes(const GenericGF& field, const GenericGFPoly& errorEvaluator, const std::vector<int>& errorLocations) { // This is directly applying Forney's Formula int s = Size(errorLocations); std::vector<int> res(s); for (int i = 0; i < s; ++i) { int xiInverse = field.inverse(errorLocations[i]); int denom = 1; for (int j = 0; j < s; ++j) if (i != j) denom = field.multiply(denom, 1 ^ field.multiply(errorLocations[j], xiInverse)); res[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denom)); if (field.generatorBase() != 0) res[i] = field.multiply(res[i], xiInverse); } return res; } bool ReedSolomonDecode(const GenericGF& field, std::vector<int>& message, int numECCodeWords) { GenericGFPoly poly(field, message); std::vector<int> syndromes(numECCodeWords); for (int i = 0; i < numECCodeWords; i++) syndromes[numECCodeWords - 1 - i] = poly.evaluateAt(field.exp(i + field.generatorBase())); // if all syndromes are 0 there is no error to correct if (std::all_of(syndromes.begin(), syndromes.end(), [](int c) { return c == 0; })) return true; ZX_THREAD_LOCAL GenericGFPoly sigma, omega; if (!RunEuclideanAlgorithm(field, std::move(syndromes), sigma, omega)) return false; auto errorLocations = FindErrorLocations(field, sigma); if (errorLocations.empty()) return false; auto errorMagnitudes = FindErrorMagnitudes(field, omega, errorLocations); int msgLen = Size(message); for (int i = 0; i < Size(errorLocations); ++i) { int position = msgLen - 1 - field.log(errorLocations[i]); if (position < 0) return false; message[position] ^= errorMagnitudes[i]; } return true; } } // namespace ZXing ```
/content/code_sandbox/core/src/ReedSolomonDecoder.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,042
```objective-c /* */ #pragma once #include "Point.h" namespace ZXing { /** * <p>Encapsulates a point of interest in an image containing a barcode. Typically, this * would be the location of a finder pattern or the corner of the barcode, for example.</p> * * @author Sean Owen */ class ResultPoint : public PointF { public: ResultPoint() = default; ResultPoint(float x, float y) : PointF(x, y) {} ResultPoint(int x, int y) : PointF(x, y) {} template <typename T> ResultPoint(PointT<T> p) : PointF(p) {} float x() const { return static_cast<float>(PointF::x); } float y() const { return static_cast<float>(PointF::y); } void set(float x, float y) { *this = PointF(x, y); } static float Distance(int aX, int aY, int bX, int bY); }; } // ZXing ```
/content/code_sandbox/core/src/ResultPoint.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
204
```objective-c /* */ #pragma once #include "BitMatrixCursor.h" #include "Pattern.h" #include "Quadrilateral.h" #include "ZXAlgorithms.h" #include <optional> namespace ZXing { template <typename T, size_t N> static float CenterFromEnd(const std::array<T, N>& pattern, float end) { if (N == 5) { float a = pattern[4] + pattern[3] + pattern[2] / 2.f; float b = pattern[4] + (pattern[3] + pattern[2] + pattern[1]) / 2.f; float c = (pattern[4] + pattern[3] + pattern[2] + pattern[1] + pattern[0]) / 2.f; return end - (2 * a + b + c) / 4; } else if (N == 3) { float a = pattern[2] + pattern[1] / 2.f; float b = (pattern[2] + pattern[1] + pattern[0]) / 2.f; return end - (2 * a + b) / 3; } else { // aztec auto a = Reduce(pattern.begin() + (N/2 + 1), pattern.end(), pattern[N/2] / 2.f); return end - a; } } template<int N, typename Cursor> std::optional<Pattern<N>> ReadSymmetricPattern(Cursor& cur, int range) { static_assert(N % 2 == 1); assert(range > 0); Pattern<N> res = {}; auto constexpr s_2 = Size(res)/2; auto cuo = cur.turnedBack(); auto next = [&](auto& cur, int i) { auto v = cur.stepToEdge(1, range); res[s_2 + i] += v; if (range) range -= v; return v; }; for (int i = 0; i <= s_2; ++i) { if (!next(cur, i) || !next(cuo, -i)) return {}; } res[s_2]--; // the starting pixel has been counted twice, fix this return res; } template<bool RELAXED_THRESHOLD = false, typename PATTERN> int CheckSymmetricPattern(BitMatrixCursorI& cur, PATTERN pattern, int range, bool updatePosition) { FastEdgeToEdgeCounter curFwd(cur), curBwd(cur.turnedBack()); int centerFwd = curFwd.stepToNextEdge(range); if (!centerFwd) return 0; int centerBwd = curBwd.stepToNextEdge(range); if (!centerBwd) return 0; assert(range > 0); Pattern<pattern.size()> res = {}; auto constexpr s_2 = Size(res)/2; res[s_2] = centerFwd + centerBwd - 1; // -1 because the starting pixel is counted twice range -= res[s_2]; auto next = [&](auto& cur, int i) { auto v = cur.stepToNextEdge(range); res[s_2 + i] = v; range -= v; return v; }; for (int i = 1; i <= s_2; ++i) { if (!next(curFwd, i) || !next(curBwd, -i)) return 0; } if (!IsPattern<RELAXED_THRESHOLD>(res, pattern)) return 0; if (updatePosition) cur.step(res[s_2] / 2 - (centerBwd - 1)); return Reduce(res); } std::optional<PointF> CenterOfRing(const BitMatrix& image, PointI center, int range, int nth, bool requireCircle = true); std::optional<PointF> FinetuneConcentricPatternCenter(const BitMatrix& image, PointF center, int range, int finderPatternSize); std::optional<QuadrilateralF> FindConcentricPatternCorners(const BitMatrix& image, PointF center, int range, int ringIndex); struct ConcentricPattern : public PointF { int size = 0; }; template <bool E2E = false, typename PATTERN> std::optional<ConcentricPattern> LocateConcentricPattern(const BitMatrix& image, PATTERN pattern, PointF center, int range) { auto cur = BitMatrixCursor(image, PointI(center), {}); int minSpread = image.width(), maxSpread = 0; // TODO: setting maxError to 1 can subtantially help with detecting symbols with low print quality resulting in damaged // finder patterns, but it sutantially increases the runtime (approx. 20% slower for the falsepositive images). int maxError = 0; for (auto d : {PointI{0, 1}, {1, 0}}) { int spread = CheckSymmetricPattern<E2E>(cur.setDirection(d), pattern, range, true); if (spread) UpdateMinMax(minSpread, maxSpread, spread); else if (--maxError < 0) return {}; } #if 1 for (auto d : {PointI{1, 1}, {1, -1}}) { int spread = CheckSymmetricPattern<true>(cur.setDirection(d), pattern, range * 2, false); if (spread) UpdateMinMax(minSpread, maxSpread, spread); else if (--maxError < 0) return {}; } #endif if (maxSpread > 5 * minSpread) return {}; auto newCenter = FinetuneConcentricPatternCenter(image, PointF(cur.p), range, pattern.size()); if (!newCenter) return {}; return ConcentricPattern{*newCenter, (maxSpread + minSpread) / 2}; } } // ZXing ```
/content/code_sandbox/core/src/ConcentricFinder.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
1,253
```c++ /* */ #include "BinaryBitmap.h" #include "BitMatrix.h" #include <mutex> namespace ZXing { struct BinaryBitmap::Cache { std::once_flag once; std::shared_ptr<const BitMatrix> matrix; }; BitMatrix BinaryBitmap::binarize(const uint8_t threshold) const { BitMatrix res(width(), height()); if (_buffer.pixStride() == 1 && _buffer.rowStride() == _buffer.width()) { // Specialize for a packed buffer with pixStride 1 to support auto vectorization (16x speedup on AVX2) auto dst = res.row(0).begin(); for (auto src = _buffer.data(0, 0), end = _buffer.data(0, height()); src != end; ++src, ++dst) *dst = (*src <= threshold) * BitMatrix::SET_V; } else { auto processLine = [&res, threshold](int y, const auto* src, const int stride) { for (auto& dst : res.row(y)) { dst = (*src <= threshold) * BitMatrix::SET_V; src += stride; } }; for (int y = 0; y < res.height(); ++y) { auto src = _buffer.data(0, y) + GreenIndex(_buffer.format()); // Specialize the inner loop for strides 1 and 4 to support auto vectorization switch (_buffer.pixStride()) { case 1: processLine(y, src, 1); break; case 4: processLine(y, src, 4); break; default: processLine(y, src, _buffer.pixStride()); break; } } } return res; } BinaryBitmap::BinaryBitmap(const ImageView& buffer) : _cache(new Cache), _buffer(buffer) {} BinaryBitmap::~BinaryBitmap() = default; const BitMatrix* BinaryBitmap::getBitMatrix() const { std::call_once(_cache->once, [&](){_cache->matrix = getBlackMatrix();}); return _cache->matrix.get(); } void BinaryBitmap::invert() { if (_cache->matrix) { auto matrix = const_cast<BitMatrix*>(_cache->matrix.get()); matrix->flipAll(); } _inverted = true; } template <typename F> void SumFilter(const BitMatrix& in, BitMatrix& out, F func) { assert(in.height() >= 3); const auto* in0 = in.row(0).begin(); const auto* in1 = in.row(1).begin(); const auto* in2 = in.row(2).begin(); for (auto *out1 = out.row(1).begin() + 1, *end = out.row(out.height() - 1).begin() - 1; out1 != end; ++in0, ++in1, ++in2, ++out1) { int sum = 0; for (int j = 0; j < 3; ++j) sum += in0[j] + in1[j] + in2[j]; *out1 = func(sum); } } void BinaryBitmap::close() { if (_cache->matrix) { auto& matrix = *const_cast<BitMatrix*>(_cache->matrix.get()); BitMatrix tmp(matrix.width(), matrix.height()); // dilate SumFilter(matrix, tmp, [](int sum) { return (sum > 0 * BitMatrix::SET_V) * BitMatrix::SET_V; }); // erode SumFilter(tmp, matrix, [](int sum) { return (sum == 9 * BitMatrix::SET_V) * BitMatrix::SET_V; }); } _closed = true; } } // ZXing ```
/content/code_sandbox/core/src/BinaryBitmap.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
811
```objective-c /* */ #pragma once #include "Matrix.h" #include <cstdint> namespace ZXing { /** * @brief Represent a tri-state value false/true/empty */ class Trit { public: enum value_t : uint8_t {false_v, true_v, empty_v} value = empty_v; Trit() = default; Trit(bool v) : value(static_cast<value_t>(v)) {} operator bool() const { return value == true_v; } bool isEmpty() const { return value == empty_v; } }; using TritMatrix = Matrix<Trit>; } // ZXing ```
/content/code_sandbox/core/src/TritMatrix.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
123
```c++ /* */ #include "BarcodeFormat.h" #include "ZXAlgorithms.h" #include <algorithm> #include <cctype> #include <iterator> #include <sstream> #include <stdexcept> namespace ZXing { struct BarcodeFormatName { BarcodeFormat format; std::string_view name; }; static BarcodeFormatName NAMES[] = { {BarcodeFormat::None, "None"}, {BarcodeFormat::Aztec, "Aztec"}, {BarcodeFormat::Codabar, "Codabar"}, {BarcodeFormat::Code39, "Code39"}, {BarcodeFormat::Code93, "Code93"}, {BarcodeFormat::Code128, "Code128"}, {BarcodeFormat::DataBar, "DataBar"}, {BarcodeFormat::DataBarExpanded, "DataBarExpanded"}, {BarcodeFormat::DataMatrix, "DataMatrix"}, {BarcodeFormat::DXFilmEdge, "DXFilmEdge"}, {BarcodeFormat::EAN8, "EAN-8"}, {BarcodeFormat::EAN13, "EAN-13"}, {BarcodeFormat::ITF, "ITF"}, {BarcodeFormat::MaxiCode, "MaxiCode"}, {BarcodeFormat::MicroQRCode, "MicroQRCode"}, {BarcodeFormat::PDF417, "PDF417"}, {BarcodeFormat::QRCode, "QRCode"}, {BarcodeFormat::RMQRCode, "rMQRCode"}, {BarcodeFormat::UPCA, "UPC-A"}, {BarcodeFormat::UPCE, "UPC-E"}, {BarcodeFormat::LinearCodes, "Linear-Codes"}, {BarcodeFormat::MatrixCodes, "Matrix-Codes"}, }; std::string ToString(BarcodeFormat format) { auto i = FindIf(NAMES, [format](auto& v) { return v.format == format; }); return i == std::end(NAMES) ? std::string() : std::string(i->name); } std::string ToString(BarcodeFormats formats) { if (formats.empty()) return ToString(BarcodeFormat::None); std::string res; for (auto f : formats) res += ToString(f) + "|"; return res.substr(0, res.size() - 1); } static std::string NormalizeFormatString(std::string_view sv) { std::string str(sv); std::transform(str.begin(), str.end(), str.begin(), [](char c) { return (char)std::tolower(c); }); str.erase(std::remove_if(str.begin(), str.end(), [](char c) { return Contains("_-[]", c); }), str.end()); return str; } static BarcodeFormat ParseFormatString(const std::string& str) { auto i = FindIf(NAMES, [str](auto& v) { return NormalizeFormatString(v.name) == str; }); return i == std::end(NAMES) ? BarcodeFormat::None : i->format; } BarcodeFormat BarcodeFormatFromString(std::string_view str) { return ParseFormatString(NormalizeFormatString(str)); } BarcodeFormats BarcodeFormatsFromString(std::string_view str) { auto normalized = NormalizeFormatString(str); std::replace_if( normalized.begin(), normalized.end(), [](char c) { return Contains(" ,", c); }, '|'); std::istringstream input(normalized); BarcodeFormats res; for (std::string token; std::getline(input, token, '|');) { if(!token.empty()) { auto bc = ParseFormatString(token); if (bc == BarcodeFormat::None) throw std::invalid_argument("This is not a valid barcode format: " + token); res |= bc; } } return res; } } // ZXing ```
/content/code_sandbox/core/src/BarcodeFormat.cpp
c++
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
773
```objective-c /* */ #pragma once #ifdef __ANDROID__ #include <android/ndk-version.h> #endif #ifdef __cpp_impl_coroutine #if defined __ANDROID__ && __NDK_MAJOR__ < 26 // NDK 25.1.8937393 can compile this code with c++20 but needs a few tweaks: #include <experimental/coroutine> namespace std { using experimental::suspend_always; using experimental::coroutine_handle; struct default_sentinel_t {}; } #else #include <concepts> #include <coroutine> #endif #include <optional> #include <iterator> // this code is based on path_to_url#Example // but modified trying to prevent accidental copying of generated objects #if defined __ANDROID__ && __NDK_MAJOR__ < 26 template <class T> #else template <std::movable T> #endif class Generator { public: struct promise_type { Generator<T> get_return_object() { return Generator{Handle::from_promise(*this)}; } static std::suspend_always initial_suspend() noexcept { return {}; } static std::suspend_always final_suspend() noexcept { return {}; } std::suspend_always yield_value(T&& value) noexcept { current_value = std::move(value); return {}; } // void return_value(T&& value) noexcept { current_value = std::move(value); } static void return_void() {} // required to compile in VisualStudio, no idea why clang/gcc are happy without // Disallow co_await in generator coroutines. void await_transform() = delete; [[noreturn]] static void unhandled_exception() { throw; } std::optional<T> current_value; }; using Handle = std::coroutine_handle<promise_type>; explicit Generator(const Handle coroutine) : _coroutine{coroutine} {} Generator() = default; ~Generator() { if (_coroutine) _coroutine.destroy(); } Generator(const Generator&) = delete; Generator& operator=(const Generator&) = delete; Generator(Generator&& other) noexcept : _coroutine{other._coroutine} { other._coroutine = {}; } // Generator& operator=(Generator&& other) noexcept // { // if (this != &other) { // if (_coroutine) // _coroutine.destroy(); // _coroutine = other._coroutine; // other._coroutine = {}; // } // return *this; // } // Range-based for loop support. class Iter { public: void operator++() { _coroutine.resume(); } T&& operator*() const { return std::move(*_coroutine.promise().current_value); } bool operator==(std::default_sentinel_t) const { return !_coroutine || _coroutine.done(); } explicit Iter(const Handle coroutine) : _coroutine{coroutine} {} private: Handle _coroutine; }; Iter begin() { if (_coroutine) _coroutine.resume(); return Iter{_coroutine}; } std::default_sentinel_t end() { return {}; } private: Handle _coroutine; }; #endif /* usage example: template <std::integral T> Generator<T> range(T first, const T last) { while (first < last) co_yield first++; } int main() { for (const char i : range(65, 91)) std::cout << i << ' '; std::cout << '\n'; } */ ```
/content/code_sandbox/core/src/Generator.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
757
```objective-c /* */ #pragma once #include <string> #include <string_view> namespace ZXing { enum class CharacterSet : unsigned char { Unknown, ASCII, ISO8859_1, ISO8859_2, ISO8859_3, ISO8859_4, ISO8859_5, ISO8859_6, ISO8859_7, ISO8859_8, ISO8859_9, ISO8859_10, ISO8859_11, ISO8859_13, ISO8859_14, ISO8859_15, ISO8859_16, Cp437, Cp1250, Cp1251, Cp1252, Cp1256, Shift_JIS, Big5, GB2312, GB18030, EUC_JP, EUC_KR, UTF16BE, UnicodeBig [[deprecated]] = UTF16BE, UTF8, UTF16LE, UTF32BE, UTF32LE, BINARY, CharsetCount }; CharacterSet CharacterSetFromString(std::string_view name); std::string ToString(CharacterSet cs); } // ZXing ```
/content/code_sandbox/core/src/CharacterSet.h
objective-c
2016-04-12T22:33:06
2024-08-15T07:35:29
zxing-cpp
zxing-cpp/zxing-cpp
1,205
258