Image物件轉Base64碼(java)
阿新 • • 發佈:2019-01-24
本文歡迎轉載,轉載請註明:/** * 直接輸出圖片為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 + "\"/>"); }