Java的BufferedImage中PNG格式的Base64字符串 [英] Java BufferedImage to PNG format Base64 String

查看:2948
本文介绍了Java的BufferedImage中PNG格式的Base64字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得的截图输出为Base64 EN codeD字符串,但没有得到很远。在code我到目前为止使用一个Base64库(<一个href=\"http://iharder.sourceforge.net/current/java/base64/\">http://iharder.sourceforge.net/current/java/base64/ ):

I'm trying to get a screenshot output as a base64 encoded string but not getting very far. The code I have so far uses a Base64 library ( http://iharder.sourceforge.net/current/java/base64/ ):

    Robot robot = new Robot();
    Rectangle r = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() );
    BufferedImage bi = robot.createScreenCapture(r);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStream b64 = new Base64.OutputStream(os);
    ImageIO.write(bi, "png", os);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.writeTo(b64);
    String result = out.toString("UTF-8");

我每次运行此,结果始终是一个空字符串,但我不明白为什么。任何想法?

Each time I run this, "result" is always an empty string but I don't understand why. Any ideas?

请注意:我不希望有巴新写入磁盘上的文件

Note: I don't want to have to write the png to a file on disk.

推荐答案

下面的语句工作在错误的方向:

The following statement works in the wrong direction:

out.writeTo(b64);

它覆盖基地64个数据与的空字节数组出

什么是的目的了呢?我不认为你需要它。

What's the purpose of out anyway? I don't think you need it.

更新:

和你直接写图像操作系统,而不是通过基地64 EN codeR写作。

And you write the image directly to os instead of writing through the Base 64 encoder.

以下code应该工作:

The following code should work:

...
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputStream b64 = new Base64.OutputStream(os);
ImageIO.write(bi, "png", b64);
String result = os.toString("UTF-8");

这篇关于Java的BufferedImage中PNG格式的Base64字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆