Java BufferedImage to Byte Array imageToBytes(BufferedImage img, String formatName)

Here you can find the source of imageToBytes(BufferedImage img, String formatName)

Description

Returns the image into an array of bytes.

License

Open Source License

Parameter

Parameter Description
img - a RenderedImage to be written.
formatName - a String containing the informal name of the format.

Declaration

public static byte[] imageToBytes(BufferedImage img, String formatName) 

Method Source Code

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

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import java.io.IOException;

import javax.imageio.ImageIO;

public class Main {
    /**//www.jav  a  2 s  .c om
     * Returns the image into an array of bytes.
     *
     * @param img - a RenderedImage to be written.
     * @param formatName - a String containing the informal name of the format.
     * @return
     */
    public static byte[] imageToBytes(BufferedImage img, String formatName) {
        byte[] imgBytes = null;
        ByteArrayOutputStream stream = null;

        try {
            stream = new ByteArrayOutputStream();
            ImageIO.write(img, formatName, stream);
            stream.flush();
            imgBytes = stream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return imgBytes;
    }
}

Related

  1. imageToByte(BufferedImage image)
  2. imageToByte(BufferedImage img)
  3. imageToByteArray(BufferedImage o)
  4. imageToBytes(BufferedImage image, String encoding)
  5. imageToBytes(BufferedImage image, String imageFormat)
  6. toArrayByte(BufferedImage image)
  7. toByteArray(BufferedImage image)
  8. toByteArray(BufferedImage image, float quality)
  9. toByteArray(BufferedImage image, String extension)