Java Code Examples for javax.imageio.ImageWriter#getDefaultImageMetadata()

The following examples show how to use javax.imageio.ImageWriter#getDefaultImageMetadata() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MergeStdCommentTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example 2
Source File: ShortHistogramTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
protected File writeImageWithHist(BufferedImage bi) throws IOException {
    File f = File.createTempFile("hist_", ".png", new File("."));

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

    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);

    ImageWriteParam param = writer.getDefaultWriteParam();
    ImageTypeSpecifier type = new ImageTypeSpecifier(bi);

    IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param);

    /* add hIST node to image metadata */
    imgMetadata = upgradeMetadata(imgMetadata, bi);

    IIOImage iio_img = new IIOImage(bi,
                                    null, // no thumbnails
                                    imgMetadata);

    writer.write(iio_img);
    ios.flush();
    ios.close();
    return f;
}
 
Example 3
Source File: MergeStdCommentTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example 4
Source File: MergeStdCommentTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example 5
Source File: ImageTools.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
public static void saveImageInPng(BufferedImage img, File f) throws IOException {
	Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName("png");
	
	if(!iw.hasNext())
		throw new IOException("PNG Writer not found");
	
	
	ImageWriter writer = iw.next();

	ImageWriteParam writeParam = writer.getDefaultWriteParam();
	ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
	IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
	setDPI(metadata);

	ImageOutputStream stream = ImageIO.createImageOutputStream(f);
	try {
		writer.setOutput(stream);
		writer.write(metadata, new IIOImage(img, null, metadata), writeParam);
	} finally {
		stream.close();
	}

}
 
Example 6
Source File: ShortHistogramTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
protected File writeImageWithHist(BufferedImage bi) throws IOException {
    File f = File.createTempFile("hist_", ".png", new File("."));

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

    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);

    ImageWriteParam param = writer.getDefaultWriteParam();
    ImageTypeSpecifier type = new ImageTypeSpecifier(bi);

    IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param);

    /* add hIST node to image metadata */
    imgMetadata = upgradeMetadata(imgMetadata, bi);

    IIOImage iio_img = new IIOImage(bi,
                                    null, // no thumbnails
                                    imgMetadata);

    writer.write(iio_img);
    ios.flush();
    ios.close();
    return f;
}
 
Example 7
Source File: MergeStdCommentTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example 8
Source File: MergeStdCommentTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example 9
Source File: ShortHistogramTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
protected File writeImageWithHist(BufferedImage bi) throws IOException {
    File f = File.createTempFile("hist_", ".png", new File("."));

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

    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);

    ImageWriteParam param = writer.getDefaultWriteParam();
    ImageTypeSpecifier type = new ImageTypeSpecifier(bi);

    IIOMetadata imgMetadata = writer.getDefaultImageMetadata(type, param);

    /* add hIST node to image metadata */
    imgMetadata = upgradeMetadata(imgMetadata, bi);

    IIOImage iio_img = new IIOImage(bi,
                                    null, // no thumbnails
                                    imgMetadata);

    writer.write(iio_img);
    ios.flush();
    ios.close();
    return f;
}
 
Example 10
Source File: SinglePageDocument.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeDocument(OutputStream outputStream, Format format, int dpi) throws IOException,
		DocumentException, PrintingException {
	if (format == Format.PDF) {
		baos.writeTo(outputStream);
	} else {
		PDDocument pdf = PDDocument.load(new ByteArrayInputStream(baos.toByteArray()), true);
		PDFRenderer renderer = new PDFRenderer(pdf);
		BufferedImage bufferedImage = renderer.renderImageWithDPI(0, dpi);
		pdf.close();
		if (format == Format.PNG) {
			final String formatName = format.getExtension();
			for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
				ImageWriter writer1 = iw.next();
				ImageWriteParam writeParam = writer1.getDefaultWriteParam();
				ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
						.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
				IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam);
				if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
					continue;
				}

				setDPI(metadata);
				// Write bufferedImage to outputStream
				final ImageOutputStream stream = ImageIO.createImageOutputStream(outputStream);
				try {
					writer1.setOutput(stream);
					writer1.write(metadata, new IIOImage(bufferedImage, null, metadata), writeParam);
				} finally {
					stream.flush();
					stream.close();
				}
				break;
			}
		} else {
			ImageIO.write(bufferedImage, format.getExtension(), outputStream);
		}

	}
}
 
Example 11
Source File: CompressionModeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void doTest(int mode) {
    String fileFormat = "bmp";
    try {
        ImageWriter iw = (ImageWriter)ImageIO.getImageWritersBySuffix(fileFormat).next();
        if(iw == null) {
            throw new RuntimeException("No available image writer for "
                                       + fileFormat
                                       + " Test failed.");
        }

        File file = new File("image." + fileFormat);
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);

        BufferedImage bimg = new BufferedImage(100,
                                               100, BufferedImage.TYPE_INT_RGB);
        Graphics g = bimg.getGraphics();
        g.setColor(Color.green);
        g.fillRect(0,0,100,100);

        ImageWriteParam param = iw.getDefaultWriteParam();

        param.setCompressionMode(mode);

        IIOMetadata meta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(bimg),
                                                      param);

        IIOImage iioImg = new IIOImage(bimg, null, meta);
        iw.write(null, iioImg, param);
    } catch(Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Test failed.");
    }
}
 
Example 12
Source File: RGBImageTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void doTest() throws IOException {
    BufferedImage biSrc = getSrc();

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    ImageWriteParam writeParam = writer.getDefaultWriteParam();
    IIOMetadata imageMetadata =
        writer.getDefaultImageMetadata(new ImageTypeSpecifier(biSrc), writeParam);

    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(writeParam);

    IIOImage iioImg = new IIOImage(biSrc, null, imageMetadata);
    writer.write(streamMetadata, iioImg, writeParam);
    ios.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);
    ImageReader reader = ImageIO.getImageReader(writer);
    reader.setInput(iis);
    BufferedImage dst = reader.read(0);

    // do test
    int x = dx / 2;
    int y = height / 2;

    for (int i = 0; i < usedColors.length; i++) {
        int dstRgb = dst.getRGB(x, y);
        System.out.println("dstColor: " + Integer.toHexString(dstRgb));
        int srcRgb = usedColors[i].getRGB();
        System.out.println("srcColor: " + Integer.toHexString(srcRgb));
        if (dstRgb != srcRgb) {
            throw new RuntimeException("wrong color " + i + ": " + Integer.toHexString(dstRgb));
        }
        x += dx;
    }

}
 
Example 13
Source File: ToolImageResize.java    From protools with Apache License 2.0 4 votes vote down vote up
/**
 * 缩放gif图片
 *
 * @param originalFile
 *         原图片
 * @param resizedFile
 *         缩放后的图片
 * @param newWidth
 *         宽度
 * @param quality
 *         缩放比例 (等比例)
 *
 * @throws IOException
 */
private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
    if (quality < 0 || quality > 1) {
        throw new IllegalArgumentException("Quality has to be between 0 and 1");
    }
    ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());

    Image i = ii.getImage();
    Image resizedImage = null;
    int iWidth = i.getWidth(null);
    int iHeight = i.getHeight(null);
    if (iWidth > iHeight) {
        resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
    } else {
        resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
    }
    // This code ensures that all the pixels in the image are loaded.
    Image temp = new ImageIcon(resizedImage).getImage();
    // Create the buffered image.
    BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
    // Copy image to buffered image.
    Graphics g = bufferedImage.createGraphics();
    // Clear background and paint the image.
    g.setColor(Color.white);
    g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
    g.drawImage(temp, 0, 0, null);
    g.dispose();
    // Soften.
    float softenFactor = 0.05f;
    float[] softenArray = {0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0};
    Kernel kernel = new Kernel(3, 3, softenArray);
    ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    bufferedImage = cOp.filter(bufferedImage, null);
    // Write the jpeg to a file.
    try (
            FileOutputStream out = new FileOutputStream(resizedFile)) {

        ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(out);
        imageWriter.setOutput(ios);
        //and metadata
        IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), null);

        JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(quality);
        imageWriter.write(imageMetaData, new IIOImage(bufferedImage, null, null), jpegParams);
    }
}
 
Example 14
Source File: BooleanAttributes.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void test(String mimeType, boolean useStreamMeta,
                        String metaXml, String... boolXpaths)
    throws Exception
{
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document)dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();

    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);

    meta.mergeTree(metaFormat, node);

    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);

    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta) meta = ir.getStreamMetadata();
    else meta = ir.getImageMetadata(0);

    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
 
Example 15
Source File: JPEGFactory.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi,
                                            OutputStream out) throws IOException
{
    // encode to JPEG
    ImageOutputStream ios = null;
    ImageWriter imageWriter = null;
    try
    {
        // find JAI writer
        imageWriter = getJPEGImageWriter();
        ios = ImageIO.createImageOutputStream(out);
        imageWriter.setOutput(ios);

        // add compression
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam)imageWriter.getDefaultWriteParam();
        jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(quality);

        // add metadata
        ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
        IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam);
        Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(dpi));
        jfif.setAttribute("Ydensity", Integer.toString(dpi));
        jfif.setAttribute("resUnits", "1"); // 1 = dots/inch

        // write
        imageWriter.write(data, new IIOImage(image, null, null), jpegParam);
    }
    finally
    {
        // clean up
        IOUtils.closeQuietly(out);
        if (ios != null)
        {
            ios.close();
        }
        if (imageWriter != null)
        {
            imageWriter.dispose();
        }
    }
}
 
Example 16
Source File: Utils.java    From lizzie with GNU General Public License v3.0 4 votes vote down vote up
public static void toGif(
    String path, List<BufferedImage> frames, int delayTime, boolean override) {
  if (Utils.isBlank(path) || frames == null || frames.size() == 0) return;
  Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("gif");
  try {
    File file = new File(path);
    if (override) {
      file.deleteOnExit();
    }

    ImageWriter writer = it.hasNext() ? it.next() : null;
    ImageOutputStream stream = ImageIO.createImageOutputStream(file);
    if (Objects.isNull(writer)) {
      throw new IOException();
    }
    writer.setOutput(stream);
    writer.prepareWriteSequence(null);

    IIOMetadataNode gce = new IIOMetadataNode("GraphicControlExtension");
    gce.setAttribute("disposalMethod", "none");
    gce.setAttribute("userInputFlag", "FALSE");
    gce.setAttribute("transparentColorFlag", "FALSE");
    gce.setAttribute("transparentColorIndex", "0");
    gce.setAttribute("delayTime", Objects.toString(delayTime));

    IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension");
    ae.setAttribute("applicationID", "NETSCAPE");
    ae.setAttribute("authenticationCode", "2.0");
    ae.setUserObject(new byte[] {0x1, 0x0, 0x0});

    IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions");
    aes.appendChild(ae);

    for (BufferedImage image : frames) {
      ImageWriteParam iwp = writer.getDefaultWriteParam();
      IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), iwp);
      String metaFormat = metadata.getNativeMetadataFormatName();
      Node root = metadata.getAsTree(metaFormat);
      root.appendChild(gce);
      root.appendChild(aes);
      metadata.setFromTree(metaFormat, root);
      writer.writeToSequence(new IIOImage(image, null, metadata), null);
      metadata = null;
    }
    writer.endWriteSequence();
    stream.close();
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}
 
Example 17
Source File: LogicalScreenDimensionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    String format = "GIF";
    ImageWriter writer =
            ImageIO.getImageWritersByFormatName(format).next();
    if (writer == null) {
        throw new RuntimeException("No available writers for " + format);
    }

    BufferedImage img = createTestImage(100, 100, BufferedImage.TYPE_BYTE_GRAY);

    ImageWriteParam p = writer.getDefaultWriteParam();
    ImageTypeSpecifier type =
        ImageTypeSpecifier.createFromRenderedImage(img);
    IIOMetadata inImageMetadata =
        writer.getDefaultImageMetadata(type, p);

    IIOMetadata inStreamMetadata = writer.getDefaultStreamMetadata(p);

    // write and read image
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    writer.write(inStreamMetadata, new IIOImage(img, null, inImageMetadata), p);

    ios.flush();
    ios.close();

    // read result
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);
    ImageReader reader = ImageIO.getImageReader(writer);
    reader.setInput(iis);

    IIOMetadata outStreamMetadata = reader.getStreamMetadata();

    GIFStreamMetadata gifStreamMetadata = (GIFStreamMetadata)outStreamMetadata;

    if (gifStreamMetadata.logicalScreenWidth != img.getWidth() ||
            gifStreamMetadata.logicalScreenHeight != img.getHeight()) {
        throw new RuntimeException("Test failed due to wrong logical screen dimension.");
    }
}
 
Example 18
Source File: ImageTiffFile.java    From MyBox with Apache License 2.0 4 votes vote down vote up
public static IIOMetadata getWriterMeta(ImageAttributes attributes, BufferedImage image,
        ImageWriter writer, ImageWriteParam param) {
    try {
        IIOMetadata metaData;
        if (attributes != null && attributes.getColorType() != null) {
            ImageTypeSpecifier imageTypeSpecifier;
            switch (attributes.getColorType()) {
                case ARGB:
                    imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
                    break;
                case RGB:
                    imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
                    break;
                case BINARY:
                    imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY);
                    break;
                case GRAY:
                    imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_GRAY);
                    break;
                default:
                    imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
                    break;
            }
            metaData = writer.getDefaultImageMetadata(imageTypeSpecifier, param);
        } else if (image != null) {
            metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
        } else {
            metaData = writer.getDefaultImageMetadata(
                    ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB), param);
        }

        if (metaData == null || metaData.isReadOnly() || attributes == null) {
            return metaData;
        }
        if (attributes.getDensity() > 0) {
            String nativeName = metaData.getNativeMetadataFormatName();  // javax_imageio_tiff_image_1.0
            Node nativeTree = metaData.getAsTree(nativeName);
            long[] xRes = new long[]{attributes.getDensity(), 1};
            long[] yRes = new long[]{attributes.getDensity(), 1};
            TIFFField fieldXRes = new TIFFField(
                    BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION),
                    TIFFTag.TIFF_RATIONAL, 1, new long[][]{xRes});
            TIFFField fieldYRes = new TIFFField(
                    BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION),
                    TIFFTag.TIFF_RATIONAL, 1, new long[][]{yRes});
            nativeTree.getFirstChild().appendChild(fieldXRes.getAsNativeNode());
            nativeTree.getFirstChild().appendChild(fieldYRes.getAsNativeNode());
            char[] fieldUnit = new char[]{BaselineTIFFTagSet.RESOLUTION_UNIT_INCH};
            TIFFField fieldResUnit = new TIFFField(
                    BaselineTIFFTagSet.getInstance().getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT),
                    TIFFTag.TIFF_SHORT, 1, fieldUnit);
            nativeTree.getFirstChild().appendChild(fieldResUnit.getAsNativeNode());
            metaData.mergeTree(nativeName, nativeTree);
        }

        return metaData;

    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example 19
Source File: JRImageBase64Exporter.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void exportReport() throws JRException {
	byte[] bytes;
	List bufferedImages;
	try {
		bytes = new byte[0];
		String message = "<IMAGES>";
		JasperReport report = (JasperReport) getParameter(JRImageExporterParameter.JASPER_REPORT);
		JasperPrint jasperPrint = (JasperPrint) getParameter(JRExporterParameter.JASPER_PRINT);

		bufferedImages = generateReportImages(report, jasperPrint);
		Iterator iterImgs = bufferedImages.iterator();
		int count = 1;
		while (iterImgs.hasNext()) {
			message += "<IMAGE page=\"" + count + "\">";
			BufferedImage image = (BufferedImage) iterImgs.next();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
			ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
			imageWriter.setOutput(ios);
			IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), null);
			ImageWriteParam par = imageWriter.getDefaultWriteParam();
			par.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
			par.setCompressionQuality(1.0f);
			imageWriter.write(imageMetaData, new IIOImage(image, null, null), par);

			// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
			// JPEGEncodeParam encodeParam = encoder.getDefaultJPEGEncodeParam(image);
			// encodeParam.setQuality(1.0f, true);
			// encoder.setJPEGEncodeParam(encodeParam);
			// encoder.encode(image);

			byte[] byteImg = baos.toByteArray();

			baos.close();
			BASE64Encoder encoder64 = new BASE64Encoder();
			String encodedImage = encoder64.encode(byteImg);

			message += encodedImage;
			message += "</IMAGE>";
			count++;

			imageWriter.dispose();
		}
		message += "</IMAGES>";
		bytes = message.getBytes();

		OutputStream out = (OutputStream) getParameter(JRExporterParameter.OUTPUT_STREAM);
		out.write(bytes);
	} catch (Throwable t) {
		throw new RuntimeException("Error while producing byte64 encoding of the report images", t);
	}
}
 
Example 20
Source File: BooleanAttributes.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void test(String mimeType, boolean useStreamMeta,
                        String metaXml, String... boolXpaths)
    throws Exception
{
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document)dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();

    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);

    meta.mergeTree(metaFormat, node);

    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);

    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta) meta = ir.getStreamMetadata();
    else meta = ir.getImageMetadata(0);

    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}