Java BufferedImage to Byte Array toByteArray(BufferedImage image, String extension)

Here you can find the source of toByteArray(BufferedImage image, String extension)

Description

Saves image into byte array.

License

Open Source License

Parameter

Parameter Description
image image to be saved
extension the image extension (png)

Return

Image in byte array.

Declaration

public static byte[] toByteArray(BufferedImage image, String extension) 

Method Source Code

//package com.java2s;
/*//w w  w  .j a  v a2  s.c  om
 * Copyright (c) 2008 Golden T Studios.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import javax.imageio.ImageIO;

public class Main {
    /**
     * Saves image into byte array.
     * 
     * @param image image to be saved
     * @param extension the image extension (png)
     * @return Image in byte array.
     * @see #fromByteArray(byte[])
     */
    public static byte[] toByteArray(BufferedImage image, String extension) {
        if (image != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            try {
                ImageIO.write(image, extension, baos);
            } catch (IOException e) {
                throw new IllegalStateException(e.toString());
            }
            byte[] b = baos.toByteArray();

            return b;
        }

        return new byte[0];
    }
}

Related

  1. imageToBytes(BufferedImage image, String imageFormat)
  2. imageToBytes(BufferedImage img, String formatName)
  3. toArrayByte(BufferedImage image)
  4. toByteArray(BufferedImage image)
  5. toByteArray(BufferedImage image, float quality)
  6. toByteArray(BufferedImage image, String formatName)
  7. toByteArray(BufferedImage img, String imageFileType)
  8. toByteArray(BufferedImage org)
  9. toByteArray(final BufferedImage image, final String format)