bufferedimage null pointer exception

37 Views Asked by At

I have an image in a string form returned from soap. I need to decode this image and use it as bufferedimage. But when I do the conversions bufferedimage appears as null. How can I fix this? Where am I making a mistake?

 String content=getContent(soapResponse);
 byte[] inputStreamResponse=content.getBytes(StandardCharsets.UTF_8);

 BufferedImage image = null;

 try {
     image = ImageIO.read(new ByteArrayInputStream(inputStreamResponse));
 } catch (IOException e) {
     e.printStackTrace();
 }
 BufferedImage scaledImg = Scalr.resize(image, 300); //300dpi


 private String getContent(SOAPMessage soapResponse)  {
    String content=null;
    if (labelelement.getLocalName().equals("content")) {
            String ss= labelelement.getLastChild().getNodeValue();
            content=   new String(Base64.getDecoder().decode(ss),StandardCharsets.UTF_8);
    }
    return content;
 }
1

There are 1 best solutions below

0
Harald K On

ImageIO comes with support for a limited set of formats built in (BMP, GIF, JPEG, PNG and TIFF since Java 9). More formats may be added by installing third-party plugins. ImageIO.read(...) will return null if there is no plugin available for the format you are trying to read. This is not a bug, but intended, documented behavior. You probably want to add a test for that in your code, unless you know for sure that the SOAP service only provides valid images in a supported format.

That said, the problem in your code is likely the getContent method which decodes the base64 data into a String... This is probably corrupting the image data. Instead, decode to a byte array, a buffer or a ByteInputStream. Then read from this array/buffer/stream in your main method.

Something like:

byte[] content = getContent(soapResponse);

BufferedImage image = null;

try (InputStream stream = new ByteArrayInputStream(content)) {
    image = ImageIO.read(stream);
} catch (IOException e) {
    e.printStackTrace();
}

if (image == null) {
    // TODO: Handle image could not be decoded situation
}

BufferedImage scaledImg = Scalr.resize(image, 300); //300dpi


/// ...

private byte[] getContent(SOAPMessage soapResponse)  {
    if (labelelement.getLocalName().equals("content")) {
        String ss = labelelement.getLastChild().getNodeValue();
        return Base64.getDecoder().decode(ss);
    }

    return null;
 }