jimSampica
jimSampica

Reputation: 12410

Getting metadata from JPEG in byte array form

I have a jpeg image in the form of a byte array. How can I get the byte array in a form where I can strip the comments node of the metadata?

byte[] myimagedata = ...

ImageWriter writer = ImageIO.getImageWritersBySuffix("jpeg").next();
ImageReader reader = ImageIO.getImageReader(writer);

//Looking for file here but have byte array
reader.setInput(new FileImageInputStream(new File(Byte array cant go here)));

IIOMetadata imageMetadata = reader.getImageMetadata(0);
Element tree = (Element)   imageMetadata.getAsTree("javax_imageio_jpeg_image_1.0");
NodeList comNL = tree.getElementsByTagName("com");
IIOMetadataNode comNode;
if (comNL.getLength() == 0) {
    comNode = new IIOMetadataNode("com");
    Node markerSequenceNode = tree.getElementsByTagName("markerSequence").item(0);
    markerSequenceNode.insertBefore(comNode,markerSequenceNode.getFirstChild());
} else {
    comNode = (IIOMetadataNode) comNL.item(0);          
}

Upvotes: 1

Views: 2452

Answers (1)

Stephen C
Stephen C

Reputation: 718798

You seem you be (just) asking how to create an ImageInputStream that reads from a byte array. From reading the javadocs, I think this should work:

new MemoryCacheImageInputStream(new ByteArrayInputStream(myimagedata))

The FileImageInputStream class doesn't have a constructor that allows you to read from anything but a file in the file system.

The FileCacheImageInputStream would also be an option, but it involves providing a directory in the file system for temporary caching ... and that seems undesirable in this context.

Upvotes: 4

Related Questions