简体   繁体   English

从图像格式8BPP创建BufferedImage

[英]Create BufferedImage from image format 8BPP

In my project I receive an Base64-encoded image that is in a greyscale 8BPP format. 在我的项目中,我收到了灰度8BPP格式的Base64编码图像。 I am having trouble converting this into a BufferedImage. 我在将其转换为BufferedImage时遇到麻烦。 I have some code that works when I read an image (f.ex png) from disk, base64-encode it and the reverse the process. 当我从磁盘读取图像(f.ex png),对它进行base64编码并逆转该过程时,我有一些可以工作的代码。

Anyway, when I try to convert my received String, everything seems to work, but null is returned. 无论如何,当我尝试转换接收到的String时,一切似乎正常,但是返回null。 It is not the catch that is invoked, but rather ImageIO.read that returns null. 不是调用catch而是返回空值的ImageIO.read。

Any suggestions? 有什么建议么? I know that the base64 string is valid, because I have tried to save it as a raw file and open it in an editor, which shows the image properly. 我知道base64字符串是有效的,因为我尝试将其保存为原始文件并在编辑器中将其打开,这样可以正确显示图像。

This is my code: 这是我的代码:

public static BufferedImage convertBase64StringToBufferedImage(String base64String){
    byte[] pictureBytes = Base64Coder.decode(base64String);

    InputStream is = new ByteArrayInputStream(pictureBytes);

    BufferedImage image;
    try {
        image = ImageIO.read(new ByteArrayInputStream(pictureBytes));
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
    return image;
}

From the documentation : 文档中

Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. 返回一个BufferedImage,作为使用ImageReader解码提供的InputStream的结果,该ImageReader是从当前注册的ImageReader中自动选择的。 The InputStream is wrapped in an ImageInputStream. InputStream包装在ImageInputStream中。 If no registered ImageReader claims to be able to read the resulting stream, null is returned. 如果没有注册的ImageReader声称能够读取结果流,则返回null。

Here's the code that gets executed: 这是要执行的代码:

public static BufferedImage read(ImageInputStream stream)
    throws IOException {
    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }

    Iterator iter = getImageReaders(stream);
    if (!iter.hasNext()) {
        return null;                  // <~~~~~ here's your null
    }

    ImageReader reader = (ImageReader)iter.next();
    ImageReadParam param = reader.getDefaultReadParam();
    reader.setInput(stream, true, true);
    BufferedImage bi;
    try {
        bi = reader.read(0, param);
    } finally {
        reader.dispose();
        stream.close();
    }
    return bi;
}

Perhaps you can try explicitly getting an ImageReader based on the appropriate mime-type, and do the read code (as seen above) with that reader. 也许您可以尝试根据适当的mime类型显式地获取ImageReader ,然后对该阅读器进行读取代码(如上所示)。

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

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