Skip to content

Instantly share code, notes, and snippets.

@scottdw
Last active July 14, 2016 14:50
Show Gist options
  • Save scottdw/420377 to your computer and use it in GitHub Desktop.
Save scottdw/420377 to your computer and use it in GitHub Desktop.
A java class that reads text from stdin and outputs a pbm (Portable Bit Map) encoded QR Code on stdout.
/*
* Copyright 2010 Scott Douglas-Watson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Description: A java class that reads text from stdin and outputs a pbm (Portable
* Bit Map) encoded QR Code on stdout.
*
* URL: http://gist.github.com/420377
*
* Requires:
* core.jar from http://code.google.com/p/zxing/
*
* See also:
* Emacs region to QR code function http://gist.github.com/420386
*/
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InToQrPbm {
private static String readInput() throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
for (String s = in.readLine(); s != null; s = in.readLine()) {
sb.append(s).append('\n');
}
return sb.toString().trim();
}
private static String toPBM(BitMatrix bytes, boolean invert) {
String black = "1 ";
String white = "0 ";
if (invert) {
black = "0 ";
white = "1 ";
}
StringBuilder sb = new StringBuilder("P1\n");
sb.append(bytes.getWidth()).append(" ").append(bytes.getHeight());
sb.append("\n");
for (int y = 0; y < bytes.getHeight(); y++) {
for (int x = 0; x < bytes.getWidth(); x++) {
sb.append(bytes.get(x, y) ? black : white);
}
sb.deleteCharAt(sb.length() - 1);
sb.append("\n");
}
return sb.toString();
}
private static BitMatrix generateQRCode(String s) throws WriterException {
return new MultiFormatWriter().encode(s, BarcodeFormat.QR_CODE,
300, 300);
}
public static void main(String[] args) throws IOException, WriterException {
boolean invert = false;
for (String a : args) {
if ("-i".equals(a)) {
invert = true;
break;
}
}
String input = readInput();
if (!"".equals(input)) {
System.out.println(toPBM(generateQRCode(input), invert));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment