Java BufferedImage Encode encodeToImgElement(BufferedImage image, String formatName)

Here you can find the source of encodeToImgElement(BufferedImage image, String formatName)

Description

encode To Img Element

License

Open Source License

Declaration

public static String encodeToImgElement(BufferedImage image, String formatName) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.BufferedOutputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;

public class Main {
    public static String encodeToImgElement(BufferedImage image, String formatName) {
        return encodedImageToImgElement(encode(image, formatName), formatName);
    }//from  w  w w. j  a  v a 2  s .  com

    public static String encodedImageToImgElement(String encodedImage, String formatName) {
        return String.format("<img src='%s'/>", encodedImage);
    }

    public static String encode(RenderedImage image, String formatName) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedOutputStream bos = new BufferedOutputStream(baos);) {
            ImageIO.write(image, formatName, bos);
            bos.flush();
            return Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. encodeImage(BufferedImage image)
  2. encodeImageToBase64(BufferedImage image)
  3. encodeImageToPNGByteArray(BufferedImage image)
  4. encodeJPEG(BufferedImage image)
  5. encodePNG(BufferedImage image, String pathAndFileName)