简体   繁体   English

Java-GIF到base64字符串

[英]Java - GIF to base64 string

how to convert gif to base64? 怎么把gif转换成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 上面的代码可以正常工作,但是它丢失了动画

You have to use 你必须用

public String encodeToString(byte[] src)

of class BASE64.Encoder (from java 8) BASE64.Encoder的类(来自java 8)

Most likely the class BufferedImage does not support images with animation. BufferedImage类很可能不支持带有动画的图像。 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. 而是尝试直接使用URL.openStream获取字节,然后将下载的字节转换为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. 可能需要也可能不需要。

I'm assuming what you want is a Base64 representation of the GIF file itself, not the ImageIO representation. 我假设您想要的是GIF文件本身的Base64表示形式,而不是ImageIO表示形式。 If you have an older version of Java without built-in Base64 support, Apache Commons Codec will do the job. 如果您有不带内置Base64支持的Java的较早版本,则Apache Commons Codec将完成此工作。 Read the file into a byte array using URL.openStream() , not with ImageIO, then call Base64.encodeBase64String . 使用URL.openStream()而不是ImageIO将文件读入字节数组,然后调用Base64.encodeBase64String If you want the result URL encoded, call Base64.encodeBase64URLSafe instead. 如果要对结果URL进行编码,请改为调用Base64.encodeBase64URLSafe

If you actually want the ImageIO representation, then you're stuck with losing the animation. 如果您确实需要ImageIO表示形式,那么您就迷失了动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM