• Java--二维码生成&图片和流转化


     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 }

  • 相关阅读:
    TCP的发送系列 — 发送缓存的管理(二)
    TCP的发送系列 — 发送缓存的管理(一)
    TCP的发送系列 — tcp_sendmsg()的实现(二)
    TCP的发送系列 — tcp_sendmsg()的实现(一)
    YTU 2618: B 求类中数据成员的最大值-类模板
    YTU 2617: B C++时间类的运算符重载
    YTU 2616: A代码完善--简易二元运算
    YTU 2615: AB编程题--世界杯小组赛
    YTU 2614: A代码完善--系统日期
    YTU 2611: A代码完善--向量的运算
  • 原文地址:https://www.cnblogs.com/microcat/p/6398185.html
Copyright © 2020-2023  润新知