简体   繁体   English

如何使用Java将图像转换为base64字符串?

[英]How can I convert an image to a base64 string using Java?

As the title indicates, I want to know how to convert an image to a base64 string in Java. 正如标题所示,我想知道如何在Java中将图像转换为base64字符串。 How can I do this? 我怎样才能做到这一点?

Use the Base64 class. 使用Base64类。

If you're on pre-Java 8, have a look at one of the following resources: 如果您使用的是Java 8之前的版本,请查看以下资源之一:

java code to convert image to string 用于将图像转换为字符串的java代码

package com.test;

import java.io.IOException;

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Test{
public static void main (String args[]) throws IOException {
 BufferedImage img = ImageIO.read(new File("C:/Test/logo.png"));
        BufferedImage newImg;
        String imgstr;
 imgstr = encodeToString(img, "png");
        System.out.println(imgstr);
}
public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

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

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

and can embed it in XSL as below 并可以将其嵌入XSL中,如下所示

<img src="data:image/png;base64,iVBORw0......."/>

Apache Commons Base64用于编码和解码

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

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