1. 程式人生 > >Image物件轉Base64碼(java)

Image物件轉Base64碼(java)

/**
 * 直接輸出圖片為base64碼
 *
 * @param key
 * @param imageurl
 * @param width
 * @param height
 * @throws IOException
 * @演算法:
 * @日期:2015年1月28日
 */
public void putImage(String key, Image image) throws IOException {
    // Image->bufferreImage
    BufferedImage bimg = new BufferedImage(image.getWidth(null),
            image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bimg.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
 
    // bufferImage->base64
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(bimg, "jpg", outputStream);
    BASE64Encoder encoder = new BASE64Encoder();
    String base64Img = encoder.encode(outputStream.toByteArray());
 
    // 輸出
    this.content = this.content.replace("@{" + key + "}",
            "<img src= \"data:image/png;base64," + base64Img + "\"/>");
}
 
/**
 * 直接輸出圖片為base64碼
 *
 * @param key
 * @param imageurl
 * @param width
 * @param height
 * @演算法:
 * @日期:2015年1月28日
 */
public void putImage(String key, Image image, int width, int height)
        throws IOException {
    // Image->bufferreImage
    BufferedImage bimg = new BufferedImage(image.getWidth(null),
            image.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bimg.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
 
    // bufferImage->base64
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(bimg, "jpg", outputStream);
    BASE64Encoder encoder = new BASE64Encoder();
    String base64Img = encoder.encode(outputStream.toByteArray());
 
    this.content = this.content.replace("@{" + key + "}",
            "<img src= \"data:image/png;base64," + base64Img
                    + "\" width=\"" + width + "\" height=\"" + height
                    + "\"/>");
}
本文歡迎轉載,轉載請註明: