Converter um objeto Image em array de bytes!

Ola pessoal!

Já dei uma boa pesquisada no guj e em outros cantos da rede, mas até agora não encontrei nada que pudesse me ajudar.

A única coisa que encontrei até agora foi esse código aqui mesmo no guj

    public byte[] ReadImageAsByteArray (String filename) throws IOException{
        byte []buffer = new byte[1024];
        
        InputStream is = this.getClass().getResourceAsStream( filename ); // nessa linda ta dando NullPointerException
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        
        while (is.read( buffer ) != -1)  {
            out.write( buffer );
        }
        return out.toByteArray();
    }    

O primeiro problema é que ele da NullPointerException e eu nao tenho nem como testar :frowning:
e o segundo problema é que eu preciso converter uma imgagem do tipo Image e não um arquivo

alguem poderia me passar um código, ou algum link que me leve a solução deste problema? mesmo que seja um código que converta arquivos em bytes para que eu possa fazer testes!

muito obrigado!

:stuck_out_tongue:

bom andei dando uma olhada no google e achei este código ve se te ajuda.

public static byte[] getByteArray(Image image) {
        int raw[] = new int[image.getWidth() * image.getHeight()];
        image.getRGB(raw, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
        byte rawByte[] = new byte[image.getWidth() * image.getHeight() * 4];
        int n = 0;
        for(int i = 0; i < raw.length; i++) {
            int ARGB = raw[i];
            int a = (ARGB & 0xff000000) >> 24;
            int r = (ARGB & 0xff0000) >> 16;
            int g = (ARGB & 0xff00) >> 8;
            int b = ARGB & 0xff;
            rawByte[n] = (byte)b;
            rawByte[n + 1] = (byte)g;
            rawByte[n + 2] = (byte)r;
            rawByte[n + 3] = (byte)a;
            n += 4;
        }
       
        raw = null;
        return rawByte;
    }

Testa ai e diz se funciona, n testei:

// img é o seu objeto image
BufferedImage bi = new BufferedImage( img.width, img.height,BufferedImage.TYPE_INT_RGB );
Graphics2D g2 = bi.createGraphics();
g2.drawImage( img, 0, 0, null ); 

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( img, "jpg", baos );
byte[] data = baos.toByteArray();

[quote=jingle] bom andei dando uma olhada no google e achei este código ve se te ajuda.

[code]
public static byte[] getByteArray(Image image) {
int raw[] = new int[image.getWidth() * image.getHeight()];
image.getRGB(raw, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
byte rawByte[] = new byte[image.getWidth() * image.getHeight() * 4];
int n = 0;
for(int i = 0; i < raw.length; i++) {
int ARGB = raw[i];
int a = (ARGB & 0xff000000) >> 24;
int r = (ARGB & 0xff0000) >> 16;
int g = (ARGB & 0xff00) >> 8;
int b = ARGB & 0xff;
rawByte[n] = (byte)b;
rawByte[n + 1] = (byte)g;
rawByte[n + 2] = (byte)r;
rawByte[n + 3] = (byte)a;
n += 4;
}

    raw = null;
    return rawByte;
}

[/code][/quote]

jingle

na linha três está errado

o objeto image não possui o metodo getRGB(parametros)

poderia me dar uma dica de como resolver!

valeu

[quote=fabiocsi]Testa ai e diz se funciona, n testei:

[code]
// img é o seu objeto image
BufferedImage bi = new BufferedImage( img.width, img.height,BufferedImage.TYPE_INT_RGB );
Graphics2D g2 = bi.createGraphics();
g2.drawImage( img, 0, 0, null );

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( img, “jpg”, baos );
byte[] data = baos.toByteArray();
[/code][/quote]

na linha numero 7 o método statico ImageIO.write(paremetros) nao procede.

estou tentando algumas mudanças pra ver no que da…

Eu aqui estou tentando fazer a mesma coisa. E pelo jeito é o cão chupando manga achar uma forma de fazer isso.

Se eu achar a solução eu posto aqui o/

Tinha colocado uma mensagem, mas decidi mudar.
É o seguinte:

BufferedImage imagem = ImageIO.read(new File("PathDaImagem.jpg"));   // crio a imagem
ByteArrayOutputStream baos = new ByteArrayOutputStream();   // crio um OS de array de bytes
ImageIO.write(imagem, "jpg", baos);   // Uso o write pra escrever os dados da imagem no OS do array de bytes
baos.toByteArray();    // pego o array de bytes

Legal Brito =)
Só que ainda assim no meu caso isso não funcionaria. Porque eu não tenho a imagem em disco. A minha imagem vem de uma requisição http onde eu recebo a imagem em uma stream que converto para um Image.

Mas de qualquer forma agora eu já consegui uma solução perfeita! Consegui fazer um método onde eu passo um Image e ele me devolve o array de bytes do Image =D

Como existem vários tópicos sobre esse assunto no GUJ eu estou centralizando o assunto no seguinte tópico: http://www.guj.com.br/posts/list/0/58204.java#1169911

A eu postei lá o método, deem uma olhada =)

Abração!