Flex Texmex
Flex Texmex

Reputation: 1084

How to convert a BufferedImage to gif in java

I want to convert a BufferedImage to gif. I already converted BufferedImage to jpeg with a function and the output was Byte[] so I could send it over the inet with a socket connection.

I need a gif encode function similiar to this jpeg encode function:

public static byte[] getImageAsJPEG(BufferedImage image) throws ImageFormatException, IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
    param.setQuality(0.9f, false);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(image);

    return output.toByteArray();
}

Upvotes: 0

Views: 2130

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

Use:

ImageIO.write(image, "GIF", output);

As in:

public static byte[] getImageAsGIF(BufferedImage image) throws ImageFormatException, IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    ImageIO.write(image, "GIF", output);

    return output.toByteArray();
}

Upvotes: 2

Related Questions