Java Code Examples for javax.imageio.ImageIO.createImageOutputStream()

The following are Jave code examples for showing how to use createImageOutputStream() of the javax.imageio.ImageIO class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: shareMySheet   File: ImageTransformation.java   View Source Code Vote up 10 votes
public static byte[] compress(BufferedImage image, float scale) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = writers.next();
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(scale);
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), param);
    byte[] data = baos.toByteArray();
    writer.dispose();
    return data;
}
 
Example 2
Project: omero-ms-pixel-buffer   File: TileRequestHandler.java   View Source Code Vote up 7 votes
/**
 * Writes a buffered image to a TIFF output stream.
 * @param image buffered image to write out as a TIFF
 * @param output output stream to write to
 * @throws IOException If there is an error writing to
 * <code>output</code>.
 */
private void writeTiff(BufferedImage image, OutputStream output)
        throws IOException {
    try (ImageOutputStream ios =
            ImageIO.createImageOutputStream(output)) {
        IIORegistry registry = IIORegistry.getDefaultInstance();
        registry.registerServiceProviders(
                ServiceRegistry.lookupProviders(
                        TIFFImageWriterSpi.class));
        TIFFImageWriterSpi spi = registry.getServiceProviderByClass(
                TIFFImageWriterSpi.class);
        TIFFImageWriter writer = new TIFFImageWriter(spi);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(image, null, null), null);
    }
}
 
Example 3
Project: openjdk-jdk10   File: ImageWriterCompressionTest.java   View Source Code Vote up 6 votes
private static long saveImage(final BufferedImage image,
                              final ImageWriter writer,
                              final ImageWriteParam writerParams,
                              final String mode,
                              final String suffix) throws IOException
{
    final File imgFile = new File("WriterCompressionTest-"
                                  + mode + '.' + suffix);
    System.out.println("Writing file: " + imgFile.getAbsolutePath());

    final ImageOutputStream imgOutStream
        = ImageIO.createImageOutputStream(new FileOutputStream(imgFile));
    try {
        writer.setOutput(imgOutStream);
        writer.write(null, new IIOImage(image, null, null), writerParams);
    } finally {
        imgOutStream.close();
    }
    return imgFile.length();
}
 
Example 4
Project: openjdk-jdk10   File: RGBImageTest.java   View Source Code Vote up 5 votes
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 5
Project: GlitchKernel   File: ImageUtil.java   View Source Code Vote up 5 votes
public static byte[] setGlitchQuality(byte[] inputImageBytes, int quality) throws Exception
{
	Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png");
	ImageWriter writer = (ImageWriter)iter.next();  
	ImageWriteParam iwp = writer.getDefaultWriteParam(); 
    BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(inputImageBytes)); 
    IIOImage image = new IIOImage(originalImage, null, null);
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    ImageOutputStream imageOut=ImageIO.createImageOutputStream(out);
    writer.setOutput(imageOut);  
    writer.write(null, image, iwp);  
    byte[] qualityImageBytes = out.toByteArray();
    return qualityImageBytes;
}
 
Example 6
Project: SpotSpotter   File: ImageReader2File.java   View Source Code Vote up 5 votes
public static void IR2F(ImageReader input, String formatname, String output) throws IOException {
	final Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatname);
	final ImageWriter writer = writers.next();
	final File f = new File(output);
	final ImageOutputStream ios = ImageIO.createImageOutputStream(f);
	writer.setOutput(ios);
}
 
Example 7
Project: openjdk-jdk10   File: CompressionModeTest.java   View Source Code Vote up 5 votes
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 8
Project: openjdk-jdk10   File: PngForceStopWritingTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws IOException {

        OutputStream outputStream = new NullOutputStream();
        ImageOutputStream imageOutputStream =
            ImageIO.createImageOutputStream(outputStream);
        try {
            ImageIO.write(createImage(2048),"PNG", imageOutputStream);
        } catch (IOException e) {
            imageOutputStream.close();
        }
    }
 
Example 9
Project: OpenJSharp   File: RuntimeBuiltinLeafInfoImpl.java   View Source Code Vote up 5 votes
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 10
Project: openjdk-jdk10   File: BitDepth.java   View Source Code Vote up 5 votes
private File testWriteRGB(String format, int type) throws IOException {

        BufferedImage bi = new BufferedImage(width, height, type);
        Graphics2D g = bi.createGraphics();

        Color white = new Color(255, 255, 255);
        Color red = new Color(255, 0, 0);
        Color green = new Color(0, 255, 0);
        Color blue = new Color(0, 0, 255);

        g.setColor(white);
        g.fillRect(0, 0, width, height);
        g.setColor(red);
        g.fillRect(10, 10, 20, 20);
        g.setColor(green);
        g.fillRect(30, 30, 20, 20);
        g.setColor(blue);
        g.fillRect(50, 50, 20, 20);

        ImageTypeSpecifier spec = new ImageTypeSpecifier(bi);
        Iterator<ImageWriter> writers = ImageIO.getImageWriters(spec, format);
        File file = new File("BitDepth_" + biTypeNames[type] + "." + format);
        if (!writers.hasNext()) {
            System.out.println("\tNo writers available for type " + biTypeNames[type]
                               + " BufferedImage!");
        } else {
            ImageWriter writer = writers.next();
            try (ImageOutputStream out = ImageIO.createImageOutputStream(file)) {
                writer.setOutput(out);
                writer.write(bi);
            } catch (Exception e) {
                System.out.println("\tCan't write a type " +  biTypeNames[type]
                           + " BufferedImage!");
                return null;
            }
        }

        return file;
    }
 
Example 11
Project: openjdk-jdk10   File: MergeTreeTest.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws IOException {
    ImageWriter iw =
        (ImageWriter)ImageIO.getImageWritersByFormatName("jpeg").next();

    ImageTypeSpecifier type =
        ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);

    ImageOutputStream ios =
        ImageIO.createImageOutputStream(new File("MergeTreeTest.jpeg"));
    iw.setOutput(ios);

    IIOMetadata meta = iw.getDefaultImageMetadata(type, null);

    boolean isFailed = false;

    String[] fmts = meta.getMetadataFormatNames();
    for (int i=0; i<fmts.length; i++) {
        System.out.print("Format: " + fmts[i] + " ... ");
        Node root = meta.getAsTree(fmts[i]);
        try {
            meta.mergeTree(fmts[i], root);
        } catch (NullPointerException e) {
            throw new RuntimeException("Test failed for format " + fmts[i], e);
        }
        System.out.println("PASSED");
    }
}
 
Example 12
Project: imageio-jnr   File: OpenJp2ImageWriterTest.java   View Source Code Vote up 5 votes
private void compressAndCompare(String fixtureName, ImageWriteParam param) throws Exception {
  File expected = new File(ClassLoader.getSystemResource("expected/" + fixtureName).getFile());
  BufferedImage in = ImageIO.read(ClassLoader.getSystemResource("lenna.png"));
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try (ImageOutputStream ios = ImageIO.createImageOutputStream(os)) {
    writer.setOutput(ios);
    writer.write(null, new IIOImage(in, null, null), param);
  }
  os.flush();
  assertThat(sha1digest(new ByteArrayInputStream(os.toByteArray()))).isEqualTo(sha1digest(expected));
}
 
Example 13
Project: openjdk-jdk10   File: AnimationTest.java   View Source Code Vote up 5 votes
private ImageWriter initWriter() throws IOException {
    ImageOutputStream ios =
        ImageIO.createImageOutputStream(new File(fname));
    writer = ImageIO.getImageWritersByFormatName("GIF").next();

    writer.setOutput(ios);

    return writer;
}
 
Example 14
Project: openjdk-jdk10   File: EncodeSubImageTest.java   View Source Code Vote up 5 votes
private void write(File f, boolean subsample) throws IOException {
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);

    writer.setOutput(ios);
    ImageWriteParam p = writer.getDefaultWriteParam();
    if (subsample) {
        p.setSourceSubsampling(subSampleX, subSampleY, 0, 0);
    }
    writer.write(null, new IIOImage(img, null, null), p);
    ios.close();
    writer.reset();
}
 
Example 15
Project: openjdk-jdk10   File: CanWriteSequence.java   View Source Code Vote up 5 votes
private static void test(final ImageWriter writer) throws Exception {
    try {
        file = File.createTempFile("temp", ".img");
        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
            }
        }
    } finally {
        writer.dispose();
        if (file != null) {
            if (fos != null) {
                fos.close();
            }
            Files.delete(file.toPath());
        }
    }
}
 
Example 16
Project: openjdk-jdk10   File: TopDownTest.java   View Source Code Vote up 5 votes
private static void writeWithCompression(BufferedImage src,
                                         String compression) throws IOException
{
    System.out.println("Compression: " + compression);
    ImageWriter writer = ImageIO.getImageWritersByFormatName("BMP").next();
    if (writer == null) {
        throw new RuntimeException("Test failed: no bmp writer available");
    }
    File fout = File.createTempFile(compression + "_", ".bmp",
                                    new File("."));

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

    BMPImageWriteParam param = (BMPImageWriteParam)
            writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compression);
    param.setTopDown(true);
    writer.write(null, new IIOImage(src, null, null), param);
    writer.dispose();
    ios.flush();
    ios.close();

    BufferedImage dst = ImageIO.read(fout);

    verify(dst);
}
 
Example 17
Project: openjdk-jdk10   File: WriteProgressListenerTest.java   View Source Code Vote up 5 votes
public void doTest() {
    try {
        System.out.println("Progress test for " + compression_type);
        BufferedImage bi = new BufferedImage(20, 300, BufferedImage.TYPE_INT_RGB);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

        Iterator iter = ImageIO.getImageWritersByFormatName(format);
        if (!iter.hasNext()) {
            throw new RuntimeException("No available writer for " + format);
        }
        ImageWriter writer = (ImageWriter)iter.next();

        writer.setOutput(ios);
        writer.addIIOWriteProgressListener(listener);

        IIOImage iio_img = new IIOImage(bi, null, null);

        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionType(compression_type);


        writer.write(null, iio_img, param);

        if (!listener.isTestPassed) {
            throw new RuntimeException("Test for " + compression_type + " does not finish correctly!");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Project: openjdk-jdk10   File: LogicalScreenDimensionTest.java   View Source Code Vote up 4 votes
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 19
Project: openjdk-jdk10   File: WriteAfterAbort.java   View Source Code Vote up 4 votes
private void test(final ImageWriter writer) throws IOException {
    try {
        // Image initialization
        final BufferedImage imageWrite =
                new BufferedImage(WIDTH, HEIGHT, TYPE_BYTE_BINARY);
        final Graphics2D g = imageWrite.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.dispose();

        // File initialization
        file = File.createTempFile("temp", ".img");
        fos = new SkipWriteOnAbortOutputStream(file);
        final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
        writer.setOutput(ios);
        writer.addIIOWriteProgressListener(this);

        // This write will be aborted, and file will not be touched
        writer.write(imageWrite);
        if (!isStartedCalled) {
            throw new RuntimeException("Started should be called");
        }
        if (!isProgressCalled) {
            throw new RuntimeException("Progress should be called");
        }
        if (!isAbortCalled) {
            throw new RuntimeException("Abort should be called");
        }
        if (isCompleteCalled) {
            throw new RuntimeException("Complete should not be called");
        }
        // Flush aborted data
        ios.flush();

        /*
         * This write should be completed successfully and the file should
         * contain correct image data.
         */
        abortFlag = false;
        isAbortCalled = false;
        isCompleteCalled = false;
        isProgressCalled = false;
        isStartedCalled = false;
        writer.write(imageWrite);

        if (!isStartedCalled) {
            throw new RuntimeException("Started should be called");
        }
        if (!isProgressCalled) {
            throw new RuntimeException("Progress should be called");
        }
        if (isAbortCalled) {
            throw new RuntimeException("Abort should not be called");
        }
        if (!isCompleteCalled) {
            throw new RuntimeException("Complete should be called");
        }
        ios.close();

        // Validates content of the file.
        final BufferedImage imageRead = ImageIO.read(file);
        for (int x = 0; x < WIDTH; ++x) {
            for (int y = 0; y < HEIGHT; ++y) {
                if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
                    throw new RuntimeException("Test failed.");
                }
            }
        }
    } finally {
        writer.dispose();
        if (file != null) {
            if (fos != null) {
                fos.close();
            }
            Files.delete(file.toPath());
        }
    }
}
 
Example 20
Project: openjdk-jdk10   File: ReadMalformedPngTest.java   View Source Code Vote up 2 votes
private static byte[] createTestPng() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    BufferedImage img = createTestImage();

    try {
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

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

        w.setOutput(ios);

        ImageWriteParam p = w.getDefaultWriteParam();

        ImageTypeSpecifier t = ImageTypeSpecifier.createFromRenderedImage(img);

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

        String nativeMetadataFormat = m.getNativeMetadataFormatName();

        Node root = m.getAsTree(nativeMetadataFormat);

        IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry");
        textEntry.setAttribute("keyword", "comment");
        textEntry.setAttribute("value", "This is a test image for JDK-6945174");

        IIOMetadataNode text = new IIOMetadataNode("tEXt");
        text.appendChild(textEntry);

        root.appendChild(text);

        m.mergeTree(nativeMetadataFormat, root);

        IIOImage iio_img = new IIOImage(img, null, m);

        w.write(iio_img);

        w.dispose();
        ios.flush();
        ios.close();
    } catch (IOException e) {
        throw new RuntimeException("Test failed.", e);
    }

    baos.flush();

    byte[] data = baos.toByteArray();

    adjustCommentLength(Integer.MAX_VALUE + 0x1000, data);

    return data;
}