user3598272
user3598272

Reputation: 145

Java - GIF to base64 string

how to convert gif to base64?

here's what i try so far

public static String convertImageToBase64(String urlString, String type ){

    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        URL url = new URL(urlString);
        BufferedImage img = ImageIO.read( url );

        ImageIO.write(img, type, bos);
        byte[] imageBytes = bos.toByteArray();

        BASE64Encoder encoder = new BASE64Encoder();
        imageString = encoder.encode(imageBytes);

        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}

code above is working, but it lost the animation

Upvotes: 0

Views: 2379

Answers (3)

user1886876
user1886876

Reputation:

I'm assuming what you want is a Base64 representation of the GIF file itself, not the ImageIO representation. If you have an older version of Java without built-in Base64 support, Apache Commons Codec will do the job. Read the file into a byte array using URL.openStream(), not with ImageIO, then call Base64.encodeBase64String. If you want the result URL encoded, call Base64.encodeBase64URLSafe instead.

If you actually want the ImageIO representation, then you're stuck with losing the animation.

Upvotes: 1

dimm
dimm

Reputation: 1798

Most likely the class BufferedImage does not support images with animation. So the code opens and parses the image only to the first frame.

Instead try directly getting the bytes with URL.openStream and then just convert the downloaded bytes to base64.

Notice that this way you can't be sure that the downloaded file is actually an image since you are not opening it at all. This may or may not be needed.

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You have to use

public String encodeToString(byte[] src)

of class BASE64.Encoder (from java 8)

Upvotes: 1

Related Questions