1. 程式人生 > >BufferedImage緩存圖片(data:image/jpg;base64,)轉換base64輸出與解析

BufferedImage緩存圖片(data:image/jpg;base64,)轉換base64輸出與解析

phi split stream null java request dispose decode gray

1、比如說二維碼圖片數據data,不想落地生成jpg文件,通過java緩存文件轉換base64輸出到頁面展示,那麽java後端處理寫法參考如下:

          InputStream is = new ByteArrayInputStream(data);
                BufferedImage img = ImageIO.read(is);
                BufferedImage bi = new BufferedImage(IMG_WIDTH, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
                Graphics g 
= bi.getGraphics(); g.drawImage(img, 0, 0, IMG_WIDTH, IMG_WIDTH, Color.LIGHT_GRAY, null); g.dispose(); is.close(); // bufferImage->base64 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img,
"jpg", outputStream); String base64Img = Base64Util.encode2Str(outputStream.toByteArray()); res = "data:image/jpg;base64," + base64Img.toString(); outputStream.close();

2、反過來,把頁面上base64展示的圖片,傳遞到java端解析出來的寫法如下:

       request.setCharacterEncoding("utf-8");  //
設置編碼    String s[] = src.split(","); byte[] src1 = Base64.decodeBase64(s[1]); ByteArrayInputStream inputStream = new ByteArrayInputStream(src1); BufferedImage bi = ImageIO.read(inputStream); String str = MatrixUtils.decode(bi);

BufferedImage緩存圖片(data:image/jpg;base64,)轉換base64輸出與解析