Meta data is missing after creating BufferedImage

时间:2016-03-02 10:59:00

标签: java metadata inputstream bufferedimage javax.imageio

I am writing meta data inside PNG image using below code:

public synchronized static byte[] writeMetaDataInPNGImage(BufferedImage buffImg,
                                                                      String key, String value)

{
    byte[][] image = null;
    try
    {


        ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();

        ImageWriteParam writeParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
            .createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);

        // adding metadata
        IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);

        IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry");
        textEntry.setAttribute("keyword", key);
        textEntry.setAttribute("value", value);
        IIOMetadataNode text = new IIOMetadataNode("tEXt");
        text.appendChild(textEntry);

        IIOMetadataNode root = new IIOMetadataNode("javax_imageio_png_1.0");
        root.appendChild(text);
        int width = buffImg.getWidth();
        int height = buffImg.getHeight();
        metadata.mergeTree("javax_imageio_png_1.0", root);



        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageOutputStream stream = ImageIO.createImageOutputStream(baos);
        writer.setOutput(stream);
        writer.write(metadata, new IIOImage(buffImg, null, metadata), writeParam);
        stream.close();

        return baos.toByteArray();
        // return ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));

    }
    catch (Exception e)
    {
        System.out.println("Exception while writing \t " + e.getMessage() + "  :: "
                           + e.getStackTrace());
        e.printStackTrace();
    }
    return null;
}

After writing meta data I am returning byte array with meta data and image data.

byte[] pngjdata = writeMetaDataInPNGImage(img.getAsBufferedImage(),"key", "hello");

If I save the image with pngjdata[] I am able to see the meta data inside image, but if I create BufferedImage from this byte array and save it I am not seeing written meta data.

InputStream in1 = new ByteArrayInputStream(pngjdata);
BufferedImage brImage = ImageIO.read(in1);

Why is brImage not having the meta data written by me?

1 个答案:

答案 0 :(得分:4)

  

为什么brImage没有我写的元数据?

BufferedImage不包含您要查找的元数据。 BufferedImage实例仅表示像素值,颜色模型,样本模型等,或者换句话说,显示图像所需的数据。还没有用于设置/获取元数据的API(但您可能会对getProperty(name)以及从旧版AWT Image API继承的相关方法感到困惑。

ImageIO API中的元数据表示为IIOMetadata的实例,以及您可以通过getAsTree(..)方法获得的各种类似DOM的表单(例如{{1}对于PNG,或者"标准" "javax_imageio_png_1.0"格式)。

要在应用程序中将像素数据和元数据组织在一起,您可以使用"javax_imageio_1.0"类。

您可以使用ImageReader.readAll(index, param)方法同时读取像素数据和元数据。您可以使用ImageWriter.write(null, iioImage, param)同时编写两者,就像上面已经做过的那样(只需注意IIOImage方法的第一个参数是 stream 元数据,与图像元数据不同,对于PNG只传递write)。