java String内容变成二维码并转成base64返回

其他导包略……
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

 

/**
     * 把string变成二维码然后转成Base64导出
     * @param string
     * @return
     */
    private String methods(String str) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置字符集编码类型
        hints.put(EncodeHintType.MARGIN, 1);  //设置白边
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 300, 300,hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            //输出二维码图片流
            try {
                ImageIO.write(image, "png",outputStream);
                return Base64.encodeBase64String(outputStream.toByteArray());
            } catch (IOException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (WriterException e1) {
        // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return null;
    }
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);//0xFF000000黑;0xFFFFFFFF白
            }
        }
        return image;
    }

你可能感兴趣的:(Java,IO)