1 package test;
2
3 import java.awt.image.BufferedImage;
4 import java.io.ByteArrayInputStream;
5 import java.io.ByteArrayOutputStream;
6 import java.io.File;
7 import java.util.Hashtable;
8
9 import javax.imageio.ImageIO;
10
11 import com.google.zxing.BarcodeFormat;
12 import com.google.zxing.EncodeHintType;
13 import com.google.zxing.MultiFormatWriter;
14 import com.google.zxing.client.j2se.MatrixToImageWriter;
15 import com.google.zxing.common.BitMatrix;
16 import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
17
18 public class Test {
19
20 public static void main(String[] args) throws Exception {
21 String text = "你好";
22
23 int width = 100;
24 int height = 100;
25 String format = "png";
26 Hashtable hints = new Hashtable();
27 hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
28 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
29 File outputFile = new File("new.png");
30 MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
31
32 byte[] b = toByteArray(new File("new.png"));
33 new Base64();
34 String s = Base64.encode(b);
35 // String s = new String(b, "utf-8");
36 System.out.println(s);
37 // new Base64();
38 ByteArrayInputStream in = new ByteArrayInputStream(Base64.decode(s));
39 BufferedImage image = ImageIO.read(in);
40 File newFile = new File("new2.png");
41 ImageIO.write(image, "png", newFile);
42
43 }
44
45 public static byte[] toByteArray(File imageFile) throws Exception {
46 BufferedImage img = ImageIO.read(imageFile);
47 ByteArrayOutputStream buf = new ByteArrayOutputStream((int) imageFile.length());
48 try {
49 ImageIO.write(img, "jpg", buf);
50 } catch (Exception e) {
51 e.printStackTrace();
52 return null;
53 }
54 return buf.toByteArray();
55 }
56
57 }

