1/*
2 * Fast QR Code generator demo
3 *
4 * Run this command-line program with no arguments. The program creates/overwrites a bunch of
5 * PNG and SVG files in the current working directory to demonstrate the creation of QR Codes.
6 *
7 * Copyright (c) Project Nayuki. (MIT License)
8 * https://www.nayuki.io/page/fast-qr-code-generator-library
9 *
10 * Permission is hereby granted, free of charge, to any person obtaining a copy of
11 * this software and associated documentation files (the "Software"), to deal in
12 * the Software without restriction, including without limitation the rights to
13 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
14 * the Software, and to permit persons to whom the Software is furnished to do so,
15 * subject to the following conditions:
16 * - The above copyright notice and this permission notice shall be included in
17 *   all copies or substantial portions of the Software.
18 * - The Software is provided "as is", without warranty of any kind, express or
19 *   implied, including but not limited to the warranties of merchantability,
20 *   fitness for a particular purpose and noninfringement. In no event shall the
21 *   authors or copyright holders be liable for any claim, damages or other
22 *   liability, whether in an action of contract, tort or otherwise, arising from,
23 *   out of or in connection with the Software or the use or other dealings in the
24 *   Software.
25 */
26
27package io.nayuki.fastqrcodegen;
28
29import java.awt.image.BufferedImage;
30import java.io.File;
31import java.io.IOException;
32import java.nio.charset.StandardCharsets;
33import java.nio.file.Files;
34import java.util.Arrays;
35import java.util.List;
36import java.util.Objects;
37import javax.imageio.ImageIO;
38
39
40public final class QrCodeGeneratorDemo {
41
42	// The main application program.
43	public static void main(String[] args) throws IOException {
44		doBasicDemo();
45		doVarietyDemo();
46		doSegmentDemo();
47		doMaskDemo();
48	}
49
50
51
52	/*---- Demo suite ----*/
53
54	// Creates a single QR Code, then writes it to a PNG file and an SVG file.
55	private static void doBasicDemo() throws IOException {
56		String text = "Hello, world!";          // User-supplied Unicode text
57		QrCode.Ecc errCorLvl = QrCode.Ecc.LOW;  // Error correction level
58
59		QrCode qr = QrCode.encodeText(text, errCorLvl);  // Make the QR Code symbol
60
61		BufferedImage img = toImage(qr, 10, 4);          // Convert to bitmap image
62		File imgFile = new File("hello-world-QR.png");   // File path for output
63		ImageIO.write(img, "png", imgFile);              // Write image to file
64
65		String svg = toSvgString(qr, 4, "#FFFFFF", "#000000");  // Convert to SVG XML code
66		File svgFile = new File("hello-world-QR.svg");          // File path for output
67		Files.write(svgFile.toPath(),                           // Write image to file
68			svg.getBytes(StandardCharsets.UTF_8));
69	}
70
71
72	// Creates a variety of QR Codes that exercise different features of the library, and writes each one to file.
73	private static void doVarietyDemo() throws IOException {
74		QrCode qr;
75
76		// Numeric mode encoding (3.33 bits per digit)
77		qr = QrCode.encodeText("314159265358979323846264338327950288419716939937510", QrCode.Ecc.MEDIUM);
78		writePng(toImage(qr, 13, 1), "pi-digits-QR.png");
79
80		// Alphanumeric mode encoding (5.5 bits per character)
81		qr = QrCode.encodeText("DOLLAR-AMOUNT:$39.87 PERCENTAGE:100.00% OPERATIONS:+-*/", QrCode.Ecc.HIGH);
82		writePng(toImage(qr, 10, 2), "alphanumeric-QR.png");
83
84		// Unicode text as UTF-8
85		qr = QrCode.encodeText("こんにちwa、世界! αβγδ", QrCode.Ecc.QUARTILE);
86		writePng(toImage(qr, 10, 3), "unicode-QR.png");
87
88		// Moderately large QR Code using longer text (from Lewis Carroll's Alice in Wonderland)
89		qr = QrCode.encodeText(
90			"Alice was beginning to get very tired of sitting by her sister on the bank, "
91			+ "and of having nothing to do: once or twice she had peeped into the book her sister was reading, "
92			+ "but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice "
93			+ "'without pictures or conversations?' So she was considering in her own mind (as well as she could, "
94			+ "for the hot day made her feel very sleepy and stupid), whether the pleasure of making a "
95			+ "daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly "
96			+ "a White Rabbit with pink eyes ran close by her.", QrCode.Ecc.HIGH);
97		writePng(toImage(qr, 6, 10), "alice-wonderland-QR.png");
98	}
99
100
101	// Creates QR Codes with manually specified segments for better compactness.
102	private static void doSegmentDemo() throws IOException {
103		QrCode qr;
104		List<QrSegment> segs;
105
106		// Illustration "silver"
107		String silver0 = "THE SQUARE ROOT OF 2 IS 1.";
108		String silver1 = "41421356237309504880168872420969807856967187537694807317667973799";
109		qr = QrCode.encodeText(silver0 + silver1, QrCode.Ecc.LOW);
110		writePng(toImage(qr, 10, 3), "sqrt2-monolithic-QR.png");
111
112		segs = Arrays.asList(
113			QrSegment.makeAlphanumeric(silver0),
114			QrSegment.makeNumeric(silver1));
115		qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);
116		writePng(toImage(qr, 10, 3), "sqrt2-segmented-QR.png");
117
118		// Illustration "golden"
119		String golden0 = "Golden ratio φ = 1.";
120		String golden1 = "6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374";
121		String golden2 = "......";
122		qr = QrCode.encodeText(golden0 + golden1 + golden2, QrCode.Ecc.LOW);
123		writePng(toImage(qr, 8, 5), "phi-monolithic-QR.png");
124
125		segs = Arrays.asList(
126			QrSegment.makeBytes(golden0.getBytes(StandardCharsets.UTF_8)),
127			QrSegment.makeNumeric(golden1),
128			QrSegment.makeAlphanumeric(golden2));
129		qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);
130		writePng(toImage(qr, 8, 5), "phi-segmented-QR.png");
131
132		// Illustration "Madoka": kanji, kana, Cyrillic, full-width Latin, Greek characters
133		String madoka = "「魔法少女まどか☆マギカ」って、 ИАИ desu κα?";
134		qr = QrCode.encodeText(madoka, QrCode.Ecc.LOW);
135		writePng(toImage(qr, 9, 4, 0xFFFFE0, 0x303080), "madoka-utf8-QR.png");
136
137		segs = Arrays.asList(QrSegmentAdvanced.makeKanji(madoka));
138		qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);
139		writePng(toImage(qr, 9, 4, 0xE0F0FF, 0x404040), "madoka-kanji-QR.png");
140	}
141
142
143	// Creates QR Codes with the same size and contents but different mask patterns.
144	private static void doMaskDemo() throws IOException {
145		QrCode qr;
146		List<QrSegment> segs;
147
148		// Project Nayuki URL
149		segs = QrSegment.makeSegments("https://www.nayuki.io/");
150		qr = QrCode.encodeSegments(segs, QrCode.Ecc.HIGH, QrCode.MIN_VERSION, QrCode.MAX_VERSION, -1, true);  // Automatic mask
151		writePng(toImage(qr, 8, 6, 0xE0FFE0, 0x206020), "project-nayuki-automask-QR.png");
152		qr = QrCode.encodeSegments(segs, QrCode.Ecc.HIGH, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 3, true);  // Force mask 3
153		writePng(toImage(qr, 8, 6, 0xFFE0E0, 0x602020), "project-nayuki-mask3-QR.png");
154
155		// Chinese text as UTF-8
156		segs = QrSegment.makeSegments("維基百科(Wikipedia,聆聽i/ˌwɪkᵻˈpiːdi.ə/)是一個自由內容、公開編輯且多語言的網路百科全書協作計畫");
157		qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 0, true);  // Force mask 0
158		writePng(toImage(qr, 10, 3), "unicode-mask0-QR.png");
159		qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 1, true);  // Force mask 1
160		writePng(toImage(qr, 10, 3), "unicode-mask1-QR.png");
161		qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 5, true);  // Force mask 5
162		writePng(toImage(qr, 10, 3), "unicode-mask5-QR.png");
163		qr = QrCode.encodeSegments(segs, QrCode.Ecc.MEDIUM, QrCode.MIN_VERSION, QrCode.MAX_VERSION, 7, true);  // Force mask 7
164		writePng(toImage(qr, 10, 3), "unicode-mask7-QR.png");
165	}
166
167
168
169	/*---- Utilities ----*/
170
171	private static BufferedImage toImage(QrCode qr, int scale, int border) {
172		return toImage(qr, scale, border, 0xFFFFFF, 0x000000);
173	}
174
175
176	/**
177	 * Returns a raster image depicting the specified QR Code, with
178	 * the specified module scale, border modules, and module colors.
179	 * <p>For example, scale=10 and border=4 means to pad the QR Code with 4 light border
180	 * modules on all four sides, and use 10&#xD7;10 pixels to represent each module.
181	 * @param qr the QR Code to render (not {@code null})
182	 * @param scale the side length (measured in pixels, must be positive) of each module
183	 * @param border the number of border modules to add, which must be non-negative
184	 * @param lightColor the color to use for light modules, in 0xRRGGBB format
185	 * @param darkColor the color to use for dark modules, in 0xRRGGBB format
186	 * @return a new image representing the QR Code, with padding and scaling
187	 * @throws NullPointerException if the QR Code is {@code null}
188	 * @throws IllegalArgumentException if the scale or border is out of range, or if
189	 * {scale, border, size} cause the image dimensions to exceed Integer.MAX_VALUE
190	 */
191	private static BufferedImage toImage(QrCode qr, int scale, int border, int lightColor, int darkColor) {
192		Objects.requireNonNull(qr);
193		if (scale <= 0 || border < 0)
194			throw new IllegalArgumentException("Value out of range");
195		if (border > Integer.MAX_VALUE / 2 || qr.size + border * 2L > Integer.MAX_VALUE / scale)
196			throw new IllegalArgumentException("Scale or border too large");
197
198		BufferedImage result = new BufferedImage((qr.size + border * 2) * scale, (qr.size + border * 2) * scale, BufferedImage.TYPE_INT_RGB);
199		for (int y = 0; y < result.getHeight(); y++) {
200			for (int x = 0; x < result.getWidth(); x++) {
201				boolean color = qr.getModule(x / scale - border, y / scale - border);
202				result.setRGB(x, y, color ? darkColor : lightColor);
203			}
204		}
205		return result;
206	}
207
208
209	// Helper function to reduce code duplication.
210	private static void writePng(BufferedImage img, String filepath) throws IOException {
211		ImageIO.write(img, "png", new File(filepath));
212	}
213
214
215	/**
216	 * Returns a string of SVG code for an image depicting the specified QR Code, with the specified
217	 * number of border modules. The string always uses Unix newlines (\n), regardless of the platform.
218	 * @param qr the QR Code to render (not {@code null})
219	 * @param border the number of border modules to add, which must be non-negative
220	 * @param lightColor the color to use for light modules, in any format supported by CSS, not {@code null}
221	 * @param darkColor the color to use for dark modules, in any format supported by CSS, not {@code null}
222	 * @return a string representing the QR Code as an SVG XML document
223	 * @throws NullPointerException if any object is {@code null}
224	 * @throws IllegalArgumentException if the border is negative
225	 */
226	private static String toSvgString(QrCode qr, int border, String lightColor, String darkColor) {
227		Objects.requireNonNull(qr);
228		Objects.requireNonNull(lightColor);
229		Objects.requireNonNull(darkColor);
230		if (border < 0)
231			throw new IllegalArgumentException("Border must be non-negative");
232		long brd = border;
233		StringBuilder sb = new StringBuilder()
234			.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
235			.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n")
236			.append(String.format("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 %1$d %1$d\" stroke=\"none\">\n",
237				qr.size + brd * 2))
238			.append("\t<rect width=\"100%\" height=\"100%\" fill=\"" + lightColor + "\"/>\n")
239			.append("\t<path d=\"");
240		for (int y = 0; y < qr.size; y++) {
241			for (int x = 0; x < qr.size; x++) {
242				if (qr.getModule(x, y)) {
243					if (x != 0 || y != 0)
244						sb.append(" ");
245					sb.append(String.format("M%d,%dh1v1h-1z", x + brd, y + brd));
246				}
247			}
248		}
249		return sb
250			.append("\" fill=\"" + darkColor + "\"/>\n")
251			.append("</svg>\n")
252			.toString();
253	}
254
255}
256