how to convert a BufferedImage object to a byte []?

0

I have an object of type BufferedImage that I am filled with a screenshot using AWT

BufferedImage imagexd = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

I get the image correctly in the object but now I want to store it in the machine. I already knew how to store this type of data with OutputStream.write asi

( OutputStream out = new FileOutputStream("ruta"); out.write(bytes); )

The problem is that it receives a byte array (byte []) and buffered image does not have any method to obtain this (at least for what it investigates), so my question is how can I get the byte [] of that BufferedImage ?

    
asked by JHon Dickertson 04.10.2017 в 21:21
source

1 answer

1

While I also have no idea how to get the bytes[] of a BufferedImage directly, there is another way you could use

1- First you create an object of type ByteArrayOutputStream by which we will obtain the array later on

ByteArrayOutputStream byteConte= new ByteArrayOutputStream();

2-Using ImageIO.write you will write the image about ByteArrayOutputStream

ImageIO.write(imagexd, "jpg" byteConte);

Here you are passing the BufferedImage ( imagexd ), the type or format of this ( jpg ), and where we will write our image ( byteConte )

3-Then just get the fix directly from ByteArrayOutputStream with toByteArray() in this way:

byte[] bytes = byteConte.toByteArray();
    
answered by 04.10.2017 / 21:29
source