Java Image to Byte Array toByteArray(Image img)

Here you can find the source of toByteArray(Image img)

Description

to Byte Array

License

LGPL

Declaration

public static byte[] toByteArray(Image img) throws IOException 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import javax.swing.ImageIcon;

public class Main {
    public static byte[] toByteArray(Image img) throws IOException {

        ImageIcon ii = new ImageIcon(img);
        img = ii.getImage();/* w w w  .ja  v  a 2  s  .c  om*/

        // img eh o seu objeto image
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, 0, 0, null);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MemoryCacheImageOutputStream mos = new MemoryCacheImageOutputStream(baos);

        Object[] obj = getWriter(1);

        if (obj == null)
            return null;

        ImageWriter writer = (ImageWriter) obj[0];
        ImageWriteParam iwp = (ImageWriteParam) obj[1];

        writer.setOutput(mos);

        IIOImage image = new IIOImage(toBufferedImage(img), null, null);
        writer.write(null, image, iwp);

        return baos.toByteArray();

    }

    private static Object[] getWriter(float quality) {

        Object[] obj = new Object[2];

        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");

        if (iter.hasNext()) {

            ImageWriter writer = iter.next();

            ImageWriteParam iwp = writer.getDefaultWriteParam();

            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

            iwp.setCompressionQuality(quality);

            obj[0] = writer;
            obj[1] = iwp;

            return obj;
        }

        return null;

    }

    public static BufferedImage toBufferedImage(Image img) {

        ImageIcon ii = new ImageIcon(img);
        img = ii.getImage();

        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();

        return bi;
    }
}

Related

  1. bufferedImageToByteArray(BufferedImage bufferedImage)
  2. bufferedImageToByteArray(BufferedImage image)
  3. bufferedImageToByteArray(BufferedImage img)
  4. bufferedImageToBytes(final BufferedImage bufferedImage, final ImageWriter imageWriter, final ImageWriteParam imageWriteParameter)
  5. toByteArray(Image image)