Java : BufferedImage to Bitmap format
Asked Answered
R

4

11

I have a program in which i capture the screen using the code :

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

Now i want to convert this BufferedImage into Bitmap format and return it through a function for some other need, Not save it in a file. Any help please??

Ranchero answered 13/6, 2011 at 13:26 Comment(1)
#3962187Zebulon
H
7

You need to have a look at ImageIO.write.

If you want the result in the form of a byte[] array, you should use a ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(yourImage, "bmp", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
Haircut answered 13/6, 2011 at 13:28 Comment(2)
Well I had already viewed that class but it writes into a file Stream but i dont want to write it into a file i want to convert it into bitmap format in the memory itself and return it through a funtion.Ranchero
Thank you i think that may help!!Ranchero
D
2

When you say "into Bitmap format" you then mean the data (as in a byte array)? If that's the case, then you can use ImageIO.write (like suggested above).
If you don't want to save it to a file, but just want to get the data, can you use a ByteArrayOutputStream like this:

ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(img, "BMP", out);
byte[] result = out.toByteArray();
Derr answered 13/6, 2011 at 13:42 Comment(0)
H
1

To see the image types available for write in the J2SE (ex. JAI), see ImageIO.getWriterFileSuffixes():

E.G.

class ShowJavaImageTypes {

    public static void main(String[] args) {
        String[] imageTypes =
            javax.imageio.ImageIO.getWriterFileSuffixes();
        for (String imageType : imageTypes) {
            System.out.println(imageType);
        }
    }
}

Output

For this Sun Java 6 JRE on Windows 7.

bmp
jpg
wbmp
jpeg
png
gif
Press any key to continue . . .

See similar ImageIO methods for MIME types, formats, and the corresponding readers.

Horacehoracio answered 13/6, 2011 at 14:51 Comment(0)
I
-1

You can simply do this:

public Bitmap getBitmapFromBufferedImage(BufferedImage image)
{
     return redResult.getBitmap();
}
Insuppressible answered 12/1, 2020 at 23:2 Comment(2)
no such BufferedImage::getBitmap() in my IDE hereMascagni
Oh... yeah, that's right. Can you tell me your use case?Insuppressible

© 2022 - 2024 — McMap. All rights reserved.