生成二维码

package org.kanpiaoxue.barcode;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class Create2DBarcode {

	public static void main(String[] args) throws Exception {
		long before = System.currentTimeMillis();
		String repeat = Strings.repeat("*", 120);
		String msg = repeat
				+ "\n\tjava [-Dtext=hello | -Dfile=c:\\hello.txt [-Dedge=200]] -DoutputFile=c:\\world.png -jar create2DBarcode.jar\n"
				+ repeat;
		System.out.println(msg);
		String text = System.getProperty("text");
		String fileName = System.getProperty("file");
		String outputFileName = System.getProperty("outputFile");
		Preconditions.checkArgument(!(Strings.isNullOrEmpty(text) && Strings
				.isNullOrEmpty(fileName)),
				"Enter args like : -Dtext=hello or -Dfile=c:\\hello.txt");

		Preconditions
				.checkNotNull(outputFileName,
						"outputFile is null. Please enter args like : -DoutputFile=c:\\world.png");

		if (Strings.isNullOrEmpty(text)) {
			StringBuilder builder = new StringBuilder();
			for (String line : Files.readLines(new File(fileName),
					Charset.forName("UTF8"))) {
				builder.append(line).append("\n");
			}
			text = builder.toString();
		} else {
			text = text.trim();
		}

		int width = 300;
		int height = width;
		String w = System.getProperty("edge");
		if (!Strings.isNullOrEmpty(w)) {
			height = width = Integer.valueOf(w).intValue();
		}

		String format = "png";
		Map<EncodeHintType, String> map = Maps.newHashMap();
		map.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
				BarcodeFormat.QR_CODE, width, height, map);
		File outputFile = new File(outputFileName);
		outputFile.delete();
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		System.out.println("output file is : " + outputFile + " . It consumes "
				+ (System.currentTimeMillis() - before) + " ms.");
	}

}

 

你可能感兴趣的:(二维码)