javax.imageio.ImageWriter Java Examples

The following examples show how to use javax.imageio.ImageWriter. 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: LUTCompareTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static Image createTestImage() throws IOException  {
    BufferedImage frame1 = createFrame(new int[] { 0xffff0000, 0xffff0000 });
    BufferedImage frame2 = createFrame(new int[] { 0xff0000ff, 0xffff0000 });

    ImageWriter writer = ImageIO.getImageWritersByFormatName("GIF").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new File("lut_test.gif"));
    ImageWriteParam param = writer.getDefaultWriteParam();
    writer.setOutput(ios);
    writer.prepareWriteSequence(null);
    writer.writeToSequence(new IIOImage(frame1, null, null), param);
    writer.writeToSequence(new IIOImage(frame2, null, null), param);
    writer.endWriteSequence();
    writer.reset();
    writer.dispose();

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

    return Toolkit.getDefaultToolkit().createImage("lut_test.gif");
}
 
Example #2
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 #3
Source File: CanWriteSequence.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(final ImageWriter writer) throws Exception {
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new FileOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    final IIOMetadata data = writer.getDefaultStreamMetadata(null);

    if (writer.canWriteSequence()) {
        writer.prepareWriteSequence(data);
    } else {
        try {
            writer.prepareWriteSequence(data);
            throw new RuntimeException(
                    "UnsupportedOperationException was not thrown");
        } catch (final UnsupportedOperationException ignored) {
            // expected
        }
    }
    writer.dispose();
    ios.close();
}
 
Example #4
Source File: SunJPEGEncoderAdapter.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Encodes an image in JPEG format and writes it to an output stream.
 *
 * @param bufferedImage  the image to be encoded (<code>null</code> not
 *     permitted).
 * @param outputStream  the OutputStream to write the encoded image to
 *     (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O problem.
 * @throws NullPointerException if <code>bufferedImage</code> is
 *     <code>null</code>.
 */
@Override
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
        throws IOException {
    ParamChecks.nullNotPermitted(bufferedImage, "bufferedImage");
    ParamChecks.nullNotPermitted(outputStream, "outputStream");
    Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iterator.next();
    ImageWriteParam p = writer.getDefaultWriteParam();
    p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    p.setCompressionQuality(this.quality);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(bufferedImage, null, null), p);
    ios.flush();
    writer.dispose();
    ios.close();
}
 
Example #5
Source File: PrepareWriteSequenceTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    String format = "GIF";
    ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();

    ImageWriteParam param = writer.getDefaultWriteParam();

    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(param);

    boolean gotException = false;
    try {
        writer.prepareWriteSequence(streamMetadata);
    } catch (IllegalStateException e) {
        gotException = true;
        System.out.println("Test passed.");
        e.printStackTrace(System.out);
    }

    if (!gotException) {
        throw new RuntimeException("Test failed.");
    }
}
 
Example #6
Source File: ImageConverter.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
private static void convertImages( final File file ) throws Exception {
	if ( file.isDirectory() ) {
		for ( final File childFile : file.listFiles() )
			convertImages( childFile );
	}
	else {
		final BufferedImage bi = ImageIO.read( file );
		
		// Default quality is not sufficient!
		// ImageIO.write( bi, "JPG", new File( file.getPath().replace( ".png", ".jpg" ) ) );
		
		final ImageWriter     iw  = ImageIO.getImageWritersByFormatName( "jpg" ).next();
		final ImageWriteParam iwp = iw.getDefaultWriteParam();
		
		iwp.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
		iwp.setCompressionQuality( 0.9f );
		
		iw.setOutput( new FileImageOutputStream( new File( file.getPath().replace( ".png", ".jpg" ) ) ) );
		iw.write( null, new IIOImage( bi , null, null ), iwp );
		iw.dispose();
	}
}
 
Example #7
Source File: GifTransparencyTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void doTest() {
    File pwd = new File(".");
    try {
        File f = File.createTempFile("transparency_test_", ".gif", pwd);
        System.out.println("file: " + f.getCanonicalPath());

        ImageWriter w = ImageIO.getImageWritersByFormatName("GIF").next();

        ImageWriterSpi spi = w.getOriginatingProvider();

        boolean succeed_write = ImageIO.write(src, "gif", f);

        if (!succeed_write) {
            throw new RuntimeException("Test failed: failed to write src.");
        }

        dst = ImageIO.read(f);

        checkResult(src, dst);

    } catch (IOException e) {
        throw new RuntimeException("Test failed.", e);
    }
}
 
Example #8
Source File: ImageUtil.java    From minifierbeans with Apache License 2.0 5 votes vote down vote up
public void compressJPG(String inputFilePath, String outputFilePath, String fileType) {
    InputOutput io = IOProvider.getDefault().getIO(Bundle.CTL_Base64Encode(), false);
    try {
        File imageFile = new File(inputFilePath);
        File compressedImageFile = new File(outputFilePath);

        InputStream is = new FileInputStream(imageFile);
        OutputStream os = new FileOutputStream(compressedImageFile);
        float quality = 0.5f;
        
        // create a BufferedImage as the result of decoding the supplied InputStream
        BufferedImage image = ImageIO.read(is);
        
        // get all image writers for JPG format
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(fileType);

        if (!writers.hasNext()) {
            throw new IllegalStateException("No writers found");
        }
        
        ImageWriter writer = writers.next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        writer.setOutput(ios);
        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        
        // appends a complete image stream containing a single image and
        //associated stream and image metadata and thumbnails to the output
        writer.write(null, new IIOImage(image, null, null), param);

        is.close();
        os.close();
        ios.close();
        writer.dispose();
    } catch (IOException ex) {
        io.getOut().println("Exception: " + ex.toString());
    }
}
 
Example #9
Source File: WriteProgressListenerTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void imageComplete(ImageWriter source) {
    print("imageComplete");

    if (state != IMAGE_STARTED) {
        error("imageComplete called without imageStarted!");
    }
    if (prevPercentageDone == 0.0F) {
        error("percentageDone was never updated!");
    }
    state = IMAGE_COMPLETE;
}
 
Example #10
Source File: ImageFileWriters.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static IIOMetadata getWriterMetaData(String targetFormat,
        ImageAttributes attributes, BufferedImage image, ImageWriter writer,
        ImageWriteParam param) {
    try {
        IIOMetadata metaData;
        switch (targetFormat) {
            case "png":
                metaData = ImagePngFile.getWriterMeta(attributes, image, writer, param);
                break;
            case "jpg":
            case "jpeg":
                metaData = ImageJpgFile.getWriterMeta(attributes, image, writer, param);
                break;
            case "tif":
            case "tiff":
                metaData = ImageTiffFile.getWriterMeta(attributes, image, writer, param);
                break;
            case "bmp":
                metaData = ImageBmpFile.getWriterMeta(attributes, image, writer, param);
                break;
            default:
                metaData = getWriterMetaData(attributes, image, writer, param);
        }
        return metaData;
    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example #11
Source File: ITXtTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void writeTo(File f, ITXtTest t) {
    BufferedImage src = createBufferedImage();
    try {
        ImageOutputStream imageOutputStream =
            ImageIO.createImageOutputStream(f);

        ImageTypeSpecifier imageTypeSpecifier =
            new ImageTypeSpecifier(src);
        ImageWriter imageWriter =
            ImageIO.getImageWritersByFormatName("PNG").next();

        imageWriter.setOutput(imageOutputStream);

        IIOMetadata m =
            imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);

        String format = m.getNativeMetadataFormatName();
        Node root = m.getAsTree(format);

        IIOMetadataNode iTXt = t.getNode();
        root.appendChild(iTXt);
        m.setFromTree(format, root);

        imageWriter.write(new IIOImage(src, null, m));
        imageOutputStream.close();
        System.out.println("Writing done.");
    } catch (Throwable e) {
        throw new RuntimeException("Writing test failed.", e);
    }
}
 
Example #12
Source File: RuntimeBuiltinLeafInfoImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public Base64Data print(Image v) {
    ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx();
    XMLSerializer xs = XMLSerializer.getInstance();

    String mimeType = xs.getXMIMEContentType();
    if(mimeType==null || mimeType.startsWith("image/*"))
        // because PNG is lossless, it's a good default
        //
        // mime type can be a range, in which case we can't just pass that
        // to ImageIO.getImageWritersByMIMEType, so here I'm just assuming
        // the default of PNG. Not sure if this is complete.
        mimeType = "image/png";

    try {
        Iterator<ImageWriter> itr = ImageIO.getImageWritersByMIMEType(mimeType);
        if(itr.hasNext()) {
            ImageWriter w = itr.next();
            ImageOutputStream os = ImageIO.createImageOutputStream(imageData);
            w.setOutput(os);
            w.write(convertToBufferedImage(v));
            os.close();
            w.dispose();
        } else {
            // no encoder
            xs.handleEvent(new ValidationEventImpl(
                ValidationEvent.ERROR,
                Messages.NO_IMAGE_WRITER.format(mimeType),
                xs.getCurrentLocation(null) ));
            // TODO: proper error reporting
            throw new RuntimeException("no encoder for MIME type "+mimeType);
        }
    } catch (IOException e) {
        xs.handleError(e);
        // TODO: proper error reporting
        throw new RuntimeException(e);
    }
    Base64Data bd = new Base64Data();
    imageData.set(bd,mimeType);
    return bd;
}
 
Example #13
Source File: AnimationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        AnimationTest t = new AnimationTest();
        t.initFrame();

        ImageWriter w = t.initWriter();

        ImageWriteParam p = w.getDefaultWriteParam();

        IIOMetadata streamMetadata = w.getDefaultStreamMetadata(p);

        w.prepareWriteSequence(streamMetadata);

        for (int i = 0; i < 50; i++) {
            BufferedImage f = t.createNextFrame();

            ImageTypeSpecifier type = new ImageTypeSpecifier(f);

            IIOMetadata m = w.getDefaultImageMetadata(type, p);

            w.writeToSequence(new IIOImage(f, null, m), p);
        }
        w.endWriteSequence();

        t.checkAnimation();
    } catch (Exception e) {
        throw new RuntimeException("Test failed.", e);
    }
}
 
Example #14
Source File: WriteAfterAbort.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException {
    final IIORegistry registry = IIORegistry.getDefaultInstance();
    final Iterator<ImageWriterSpi> iter = registry.getServiceProviders(
            ImageWriterSpi.class, provider -> true, true);

    // Validates all supported ImageWriters
    while (iter.hasNext()) {
        final WriteAfterAbort writeAfterAbort = new WriteAfterAbort();
        final ImageWriter writer = iter.next().createWriterInstance();
        System.out.println("ImageWriter = " + writer);
        writeAfterAbort.test(writer);
    }
    System.out.println("Test passed");
}
 
Example #15
Source File: ResetOutOfMemory.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) {
    ImageWriter writer = new JPEGImageWriter(null);
    try {
        writer.reset();
    } catch (OutOfMemoryError e) {
        throw new RuntimeException("Got OutOfMemoryError!");
    }
}
 
Example #16
Source File: ImageIOHelper.java    From tess4j with Apache License 2.0 5 votes vote down vote up
public static List<File> createTiffFiles(List<IIOImage> imageList, int index, int dpiX, int dpiY) throws IOException {
    List<File> tiffFiles = new ArrayList<File>();

    //Set up the writeParam
    TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    //Get tiff writer and set output to file
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT);
    if (!writers.hasNext()) {
        throw new RuntimeException(JAI_IMAGE_WRITER_MESSAGE);
    }
    ImageWriter writer = writers.next();

    //Get the stream metadata
    IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam);

    // all if index == -1; otherwise, only index-th
    for (IIOImage oimage : (index == -1 ? imageList : imageList.subList(index, index + 1))) {
        if (dpiX != 0 && dpiY != 0) {
            // Get the default image metadata.
            ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(oimage.getRenderedImage());
            ImageWriteParam param = writer.getDefaultWriteParam();
            IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, param);
            imageMetadata = setDPIViaAPI(imageMetadata, dpiX, dpiY);
            oimage.setMetadata(imageMetadata);
        }

        File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT);
        try (ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile)) {
            writer.setOutput(ios);
            writer.write(streamMetadata, oimage, tiffWriteParam);
            tiffFiles.add(tiffFile);
        }
    }
    writer.dispose();

    return tiffFiles;
}
 
Example #17
Source File: TrackerWriteProgressListener.java    From Pixelitor with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void imageProgress(ImageWriter source, float percentageDone) {
    int progress = (int) percentageDone;
    if (progress > workDone) {
        tracker.unitsDone(progress - workDone);
        workDone = progress;
    }
}
 
Example #18
Source File: RuntimeBuiltinLeafInfoImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Base64Data print(Image v) {
    ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx();
    XMLSerializer xs = XMLSerializer.getInstance();

    String mimeType = xs.getXMIMEContentType();
    if(mimeType==null || mimeType.startsWith("image/*"))
        // because PNG is lossless, it's a good default
        //
        // mime type can be a range, in which case we can't just pass that
        // to ImageIO.getImageWritersByMIMEType, so here I'm just assuming
        // the default of PNG. Not sure if this is complete.
        mimeType = "image/png";

    try {
        Iterator<ImageWriter> itr = ImageIO.getImageWritersByMIMEType(mimeType);
        if(itr.hasNext()) {
            ImageWriter w = itr.next();
            ImageOutputStream os = ImageIO.createImageOutputStream(imageData);
            w.setOutput(os);
            w.write(convertToBufferedImage(v));
            os.close();
            w.dispose();
        } else {
            // no encoder
            xs.handleEvent(new ValidationEventImpl(
                ValidationEvent.ERROR,
                Messages.NO_IMAGE_WRITER.format(mimeType),
                xs.getCurrentLocation(null) ));
            // TODO: proper error reporting
            throw new RuntimeException("no encoder for MIME type "+mimeType);
        }
    } catch (IOException e) {
        xs.handleError(e);
        // TODO: proper error reporting
        throw new RuntimeException(e);
    }
    Base64Data bd = new Base64Data();
    imageData.set(bd,mimeType);
    return bd;
}
 
Example #19
Source File: WriteProgressListenerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void imageComplete(ImageWriter source) {
    System.out.println("Image Completed");
    if (!isImageComplete) {
        isImageComplete = true;
    } else {
        throw new RuntimeException("The imageComplete() was called twice."
                                   + " Test failed.");
    }

    checkProgress();
}
 
Example #20
Source File: JPEGMovWriter.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
protected void writeFrame(OutputStream out, BufferedImage image,
		Map<String, Object> settings) throws IOException {
	if (image.getType() == BufferedImage.TYPE_INT_ARGB
			|| image.getType() == BufferedImage.TYPE_INT_ARGB_PRE) {
		if (printWarning == false) {
			printWarning = true;
			System.err
					.println("JPEGMovWriter Warning: a BufferedImage of type TYPE_INT_ARGB may produce unexpected results. The recommended type is TYPE_INT_RGB.");
		}
	}
	float quality;
	if (settings != null
			&& settings.get(PROPERTY_QUALITY) instanceof Number) {
		quality = ((Number) settings.get(PROPERTY_QUALITY)).floatValue();
	} else if (settings != null
			&& settings.get(PROPERTY_QUALITY) instanceof String) {
		quality = Float.parseFloat((String) settings.get(PROPERTY_QUALITY));
	} else {
		quality = defaultQuality;
	}

	MemoryCacheImageOutputStream iOut = new MemoryCacheImageOutputStream(
			out);
	ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/jpeg").next();
	ImageWriteParam iwParam = iw.getDefaultWriteParam();
	iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
	iwParam.setCompressionQuality(quality);
	iw.setOutput(iOut);
	IIOImage img = new IIOImage(image, null, null);
	iw.write(null, img, iwParam);
}
 
Example #21
Source File: GetReaderWriterInfo.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testGetWriterFormatNames() {
    String[] names = ImageIO.getWriterFormatNames();
    for (String n : names) {
        Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(n);
        if (!it.hasNext()) {
            throw new RuntimeException("getWriterFormatNames returned " +
                                       "an unknown name: " + n);
        }
    }
}
 
Example #22
Source File: WritingInterruptionTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void imageProgress(ImageWriter source,
                          float percentageDone)
{
    if (20f < percentageDone && percentageDone < 80f ) {
        Thread t = new Thread(action);
        t.start();
    }
}
 
Example #23
Source File: AnnotateScreenCapture.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public File saveToFile(File captureFile) throws FileNotFoundException, IOException {
    writePNG(captureFile);

    ImageReader reader = getPNGImageReader();
    ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(captureFile));
    reader.setInput(iis);
    BufferedImage pngImage = reader.read(0);
    IIOMetadata imageMetadata = reader.getImageMetadata(0);

    Node root = imageMetadata.getAsTree(imageMetadata.getNativeMetadataFormatName());
    IIOMetadataNode textNode = new IIOMetadataNode("tEXt");
    ArrayList<Annotation> annotations = imagePanel.getAnnotations();
    for (int i = 0; i < annotations.size(); i++) {
        textNode.appendChild(getAnnotationNode((Annotation) annotations.get(i), i));
    }
    root.appendChild(textNode);

    imageMetadata.mergeTree(imageMetadata.getNativeMetadataFormatName(), root);

    IIOImage imageWrite = new IIOImage(pngImage, new ArrayList<BufferedImage>(), imageMetadata);

    ImageWriter writer = getPNGImageWriter();
    ImageOutputStream ios = ImageIO.createImageOutputStream(new FileOutputStream(captureFile));
    writer.setOutput(ios);
    writer.write(imageWrite);
    writer.dispose();

    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    ImagePanel finalImage = new ImagePanel(new FileInputStream(captureFile), false);
    frame.add(finalImage, BorderLayout.CENTER);
    frame.pack();
    File savedFile = new File(captureFile.getParentFile(), "ext-" + captureFile.getName());
    getScreenShot(frame.getContentPane(), savedFile);
    frame.dispose();

    return savedFile;
}
 
Example #24
Source File: BufferedImageHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isWritable(MediaType mediaType) {
	if (mediaType == null || MediaType.ALL.equals(mediaType)) {
		return true;
	}
	Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(mediaType.toString());
	return imageWriters.hasNext();
}
 
Example #25
Source File: DefaultDrawerImageUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ImageAndResolution getImageAndResolution(BufferedImage buffImage, int dpi, ImageWriter writer, ImageWriteParam imageWriterParams,
		IIOMetadata metadata) throws IOException {
	try (ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageOutputStream imageOs = ImageIO.createImageOutputStream(os)) {
		writer.setOutput(imageOs);
		writer.write(metadata, new IIOImage(buffImage, null, metadata), imageWriterParams);
		return new ImageAndResolution(new InMemoryDocument(os.toByteArray()), dpi, dpi);
	}
}
 
Example #26
Source File: ITXtTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void writeTo(File f, ITXtTest t) {
    BufferedImage src = createBufferedImage();
    try {
        ImageOutputStream imageOutputStream =
            ImageIO.createImageOutputStream(f);

        ImageTypeSpecifier imageTypeSpecifier =
            new ImageTypeSpecifier(src);
        ImageWriter imageWriter =
            ImageIO.getImageWritersByFormatName("PNG").next();

        imageWriter.setOutput(imageOutputStream);

        IIOMetadata m =
            imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);

        String format = m.getNativeMetadataFormatName();
        Node root = m.getAsTree(format);

        IIOMetadataNode iTXt = t.getNode();
        root.appendChild(iTXt);
        m.setFromTree(format, root);

        imageWriter.write(new IIOImage(src, null, m));
        imageOutputStream.close();
        System.out.println("Writing done.");
    } catch (Throwable e) {
        throw new RuntimeException("Writing test failed.", e);
    }
}
 
Example #27
Source File: ImageUtil.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/** Checks that the provided <code>ImageWriter</code> can encode
 * the provided <code>ImageTypeSpecifier</code> or not.  If not, an
 * <code>IIOException</code> will be thrown.
 * @param writer The provided <code>ImageWriter</code>.
 * @param type The image to be tested.
 * @throws IIOException If the writer cannot encoded the provided image.
 */
public static final void canEncodeImage(ImageWriter writer,
                                        ImageTypeSpecifier type)
    throws IIOException {
    ImageWriterSpi spi = writer.getOriginatingProvider();

    if(type != null && spi != null && !spi.canEncodeImage(type))  {
        throw new IIOException(I18N.getString("ImageUtil2")+" "+
                               writer.getClass().getName());
    }
}
 
Example #28
Source File: BMPImageWriter.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
public void writeAborted(ImageWriter source) {
}
 
Example #29
Source File: BMPImageWriter.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public void thumbnailComplete(ImageWriter source) {
}
 
Example #30
Source File: XDataTransferer.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public LinkedHashSet<String> getPlatformMappingsForFlavor(DataFlavor df) {
    LinkedHashSet<String> natives = new LinkedHashSet<>(1);

    if (df == null) {
        return natives;
    }

    String charset = df.getParameter("charset");
    String baseType = df.getPrimaryType() + "/" + df.getSubType();
    String mimeType = baseType;

    if (charset != null && DataTransferer.isFlavorCharsetTextType(df)) {
        mimeType += ";charset=" + charset;
    }

    // Add a mapping to the MIME native whenever the representation class
    // doesn't require translation.
    if (df.getRepresentationClass() != null &&
        (df.isRepresentationClassInputStream() ||
         df.isRepresentationClassByteBuffer() ||
         byte[].class.equals(df.getRepresentationClass()))) {
        natives.add(mimeType);
    }

    if (DataFlavor.imageFlavor.equals(df)) {
        String[] mimeTypes = ImageIO.getWriterMIMETypes();
        if (mimeTypes != null) {
            for (int i = 0; i < mimeTypes.length; i++) {
                Iterator writers =
                    ImageIO.getImageWritersByMIMEType(mimeTypes[i]);

                while (writers.hasNext()) {
                    ImageWriter imageWriter = (ImageWriter)writers.next();
                    ImageWriterSpi writerSpi =
                        imageWriter.getOriginatingProvider();

                    if (writerSpi != null &&
                        writerSpi.canEncodeImage(getDefaultImageTypeSpecifier())) {
                        natives.add(mimeTypes[i]);
                        break;
                    }
                }
            }
        }
    } else if (DataTransferer.isFlavorCharsetTextType(df)) {
        // stringFlavor is semantically equivalent to the standard
        // "text/plain" MIME type.
        if (DataFlavor.stringFlavor.equals(df)) {
            baseType = "text/plain";
        }

        for (String encoding : DataTransferer.standardEncodings()) {
            if (!encoding.equals(charset)) {
                natives.add(baseType + ";charset=" + encoding);
            }
        }

        // Add a MIME format without specified charset.
        if (!natives.contains(baseType)) {
            natives.add(baseType);
        }
    }

    return natives;
}