Java Code Examples for javax.imageio.stream.ImageOutputStream#flush()

The following examples show how to use javax.imageio.stream.ImageOutputStream#flush() . 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: EmbeddedFormatTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void doTest(String compression, int bi_type) throws IOException {
    System.out.println("Test " + compression + " on " + getImageTypeName(bi_type));
    BufferedImage src = createTestImage(bi_type);
    writer.reset();

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

    ImageWriteParam wparam = prepareWriteParam(compression);
    writer.write(null, new IIOImage(src, null, null), wparam);
    ios.flush();
    ios.close();

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

    BufferedImage dst = reader.read(0);

    checkResult(dst);
}
 
Example 2
Source File: ShortHistogramTest.java    From openjdk-jdk8u 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: LUTCompareTest.java    From jdk8u60 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 4
Source File: ImageHelper.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Can change this to choose a better compression level as the default
 * 
 * @param image
 * @param scaledImage
 * @return
 */
private static boolean writeTo(BufferedImage image, OutputStream scaledImage, Size scaledSize, String outputFormat) {
    try {
        if (!StringHelper.containsNonWhitespace(outputFormat)) {
            outputFormat = OUTPUT_FORMAT;
        }

        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat);
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();
            ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize);
            IIOImage iiOImage = new IIOImage(image, null, null);
            ImageOutputStream iOut = new MemoryCacheImageOutputStream(scaledImage);
            writer.setOutput(iOut);
            writer.write(null, iiOImage, iwp);
            writer.dispose();
            iOut.flush();
            iOut.close();
            return true;
        } else {
            return ImageIO.write(image, outputFormat, scaledImage);
        }
    } catch (IOException e) {
        return false;
    }
}
 
Example 5
Source File: ShortHistogramTest.java    From jdk8u-dev-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 6
Source File: ScreenshotComponent.java    From netbeans with Apache License 2.0 6 votes vote down vote up
void save(File file) throws IOException {
    ImageWriter iw = null;
    String name = file.getName();
    int i = name.lastIndexOf('.');
    if (i >= 0) {
        String extension = name.substring(i + 1);
        Iterator<ImageWriter> imageWritersBySuffix = ImageIO.getImageWritersBySuffix(extension);
        if (imageWritersBySuffix.hasNext()) {
            iw = imageWritersBySuffix.next();
        }
    }
    if (iw != null) {
        file.delete();
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);
        try {
            iw.write((BufferedImage) image);
        } finally {
            iw.dispose();
            ios.flush();
            ios.close();
        }
    } else {
        ImageIO.write((BufferedImage) image, "PNG", file);
    }
}
 
Example 7
Source File: ImageIO.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}
 
Example 8
Source File: ImageIO.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}
 
Example 9
Source File: TopDownTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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 10
Source File: ImageIO.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}
 
Example 11
Source File: ImageIO.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}
 
Example 12
Source File: ImageDataContentHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void writeTo(Object obj, String mimeType, OutputStream os) throws IOException {
    if (obj instanceof Image) {
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mimeType);
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();

            BufferedImage bimg = convertToBufferedImage((Image)obj);
            ImageOutputStream out = ImageIO.createImageOutputStream(os);
            writer.setOutput(out);
            writer.write(bimg);
            writer.dispose();
            out.flush();
            out.close();
            return;
        }
    } else if (obj instanceof byte[]) {
        os.write((byte[])obj);
    } else if (obj instanceof InputStream) {
        IOUtils.copyAndCloseInput((InputStream)obj, os);
    } else if (obj instanceof File) {
        InputStream file = Files.newInputStream(((File)obj).toPath());
        IOUtils.copyAndCloseInput(file, os);
    } else {
        throw new IOException("Attachment type not spported " + obj.getClass());
    }

}
 
Example 13
Source File: ImageIO.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}
 
Example 14
Source File: ImageScalarImpl.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeJPG(BufferedImage bufferedImage, OutputStream outputStream, double quality) throws IOException {
    Iterator<ImageWriter> iterator =
        ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter imageWriter = iterator.next();
    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    imageWriteParam.setCompressionQuality((float) quality);
    ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(outputStream);
    imageWriter.setOutput(imageOutputStream);
    IIOImage iioimage = new IIOImage(bufferedImage, null, null);
    imageWriter.write(null, iioimage, imageWriteParam);
    imageOutputStream.flush();
}
 
Example 15
Source File: ImageIO.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Writes image to output stream  using given image writer.
 */
private static boolean doWrite(RenderedImage im, ImageWriter writer,
                             ImageOutputStream output) throws IOException {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    try {
        writer.write(im);
    } finally {
        writer.dispose();
        output.flush();
    }
    return true;
}
 
Example 16
Source File: BMPSubsamplingTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public BMPSubsamplingTest() throws IOException {
    ImageWriter writer =
        ImageIO.getImageWritersByFormatName(format).next();

    ImageWriteParam wparam = writer.getDefaultWriteParam();
    wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    String[] types = wparam.getCompressionTypes();
    for (int t = 0; t < img_types.length; t++) {
        int img_type = img_types[t];
        System.out.println("Test for " + getImageTypeName(img_type));
        BufferedImage image = getTestImage(img_type);

        ImageTypeSpecifier specifier = new ImageTypeSpecifier(image);

        if (!writer.getOriginatingProvider().canEncodeImage(specifier)) {
            System.out.println("Writer does not support encoding this buffered image type.");
            continue;
        }

        for(int i=0; i<types.length; i++) {
            if ("BI_JPEG".equals(types[i])) {
                // exclude BI_JPEG from automatic test
                // due to color diffusion effect on the borders.
                continue;
            }

            if (canEncodeImage(types[i], specifier, img_type)) {
                System.out.println("compression type: " + types[i] +
                    " Supported for " + getImageTypeName(img_type));
            } else {
                System.out.println("compression type: " + types[i] +
                    " NOT Supported for " + getImageTypeName(img_type));
                continue;
            }
            ImageWriteParam imageWriteParam = getImageWriteParam(writer, types[i]);

            imageWriteParam.setSourceSubsampling(srcXSubsampling,
                                                 srcYSubsampling,
                                                 0, 0);
            File outputFile = new File("subsampling_test_" +
                getImageTypeName(img_type) + "__" +
                types[i] + ".bmp");
            ImageOutputStream ios =
                ImageIO.createImageOutputStream(outputFile);
            writer.setOutput(ios);

            IIOImage iioImg = new IIOImage(image, null, null);

            writer.write(null, iioImg, imageWriteParam);

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

            BufferedImage outputImage = ImageIO.read(outputFile);
            checkTestImage(outputImage);
        }
    }
}
 
Example 17
Source File: WriteAfterAbort.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private void test(final ImageWriter writer) throws IOException {
    // 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
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream 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");
    }
    writer.dispose();
    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.");
            }
        }
    }
}
 
Example 18
Source File: RGBAnimationTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void doTest() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writer.reset();
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    ImageWriteParam wparam = prepareWriteParam();

    IIOMetadata streamMetadata = prepareStreamMetadata(wparam);

    writer.prepareWriteSequence(streamMetadata);

    for (int i = 0; i < frames.length; i++) {
        BufferedImage src = frames[i].getImage();
        IIOMetadata imageMetadata = prepareImageMetadata(i, src, wparam);
        IIOImage img = new IIOImage(src,  null, imageMetadata);

        writer.writeToSequence(img, wparam);
    }
    writer.endWriteSequence();
    ios.flush();
    ios.close();

    if (doSave) {
        File f = File.createTempFile("wr_test_", "." + format, new File("."));
        System.out.println("Save to file: " + f.getCanonicalPath());
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(baos.toByteArray());
        fos.flush();
        fos.close();
    }
    // read result
    reader.reset();
    ByteArrayInputStream bais =
            new ByteArrayInputStream(baos.toByteArray());
    reader.setInput(ImageIO.createImageInputStream(bais));

    int minIndex = reader.getMinIndex();
    int numImages = reader.getNumImages(true);

    for (int i = 0; i < numImages; i++) {
        BufferedImage dst = reader.read(i + minIndex);
        frames[i].checkResult(dst);
    }
}
 
Example 19
Source File: BMPSubsamplingTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public BMPSubsamplingTest() throws IOException {
    ImageWriter writer =
        ImageIO.getImageWritersByFormatName(format).next();

    ImageWriteParam wparam = writer.getDefaultWriteParam();
    wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    String[] types = wparam.getCompressionTypes();
    for (int t = 0; t < img_types.length; t++) {
        int img_type = img_types[t];
        System.out.println("Test for " + getImageTypeName(img_type));
        BufferedImage image = getTestImage(img_type);

        ImageTypeSpecifier specifier = new ImageTypeSpecifier(image);

        if (!writer.getOriginatingProvider().canEncodeImage(specifier)) {
            System.out.println("Writer does not support encoding this buffered image type.");
            continue;
        }

        for(int i=0; i<types.length; i++) {
            if ("BI_JPEG".equals(types[i])) {
                // exclude BI_JPEG from automatic test
                // due to color diffusion effect on the borders.
                continue;
            }

            if (canEncodeImage(types[i], specifier, img_type)) {
                System.out.println("compression type: " + types[i] +
                    " Supported for " + getImageTypeName(img_type));
            } else {
                System.out.println("compression type: " + types[i] +
                    " NOT Supported for " + getImageTypeName(img_type));
                continue;
            }
            ImageWriteParam imageWriteParam = getImageWriteParam(writer, types[i]);

            imageWriteParam.setSourceSubsampling(srcXSubsampling,
                                                 srcYSubsampling,
                                                 0, 0);
            File outputFile = new File("subsampling_test_" +
                getImageTypeName(img_type) + "__" +
                types[i] + ".bmp");
            ImageOutputStream ios =
                ImageIO.createImageOutputStream(outputFile);
            writer.setOutput(ios);

            IIOImage iioImg = new IIOImage(image, null, null);

            writer.write(null, iioImg, imageWriteParam);

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

            BufferedImage outputImage = ImageIO.read(outputFile);
            checkTestImage(outputImage);
        }
    }
}
 
Example 20
Source File: BMPCompressionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void doTest() {
    try {
        System.out.println(this.getDescription());
        if (param.getCompressionMode() != ImageWriteParam.MODE_EXPLICIT) {
            System.out.println("Warning: compression mode is not MODE_EXPLICIT");
        }
        // change metadata according to ImageWriteParam
        IIOMetadata new_meta = iw.convertImageMetadata(meta, new ImageTypeSpecifier(img), param);

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

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
        iw.setOutput(ios);
        System.out.print("write image...");
        System.out.println("Current compression Type is \""+param.getCompressionType()+"\"");
        iw.write(new_meta, iio_img, param);
        //iw.write(iio_img);
        System.out.println("OK");
        System.out.print("read image ... ");
        ios.flush();

        byte[] ba_image = baos.toByteArray();

        System.out.println("Array length=" + ba_image.length);
        FileOutputStream fos = new FileOutputStream(new File(param.getCompressionType()+".bmp"));
        fos.write(ba_image);
        fos.flush();
        fos = null;
        ByteArrayInputStream bais = new ByteArrayInputStream(ba_image);

        ImageReader ir = ImageIO.getImageReader(iw);
        ir.setInput(ImageIO.createImageInputStream(bais));

        BufferedImage res = ir.read(0);
        System.out.println("OK");

        if (!param.getCompressionType().equals("BI_JPEG")) {
            System.out.print("compare images ... ");
            boolean r = compare(img,res);
            System.out.println(r?"OK":"FAILED");
            if (!r) {
                throw new RuntimeException("Compared images are not equals. Test failed.");
            }
        }


        BMPMetadata mdata = (BMPMetadata)ir.getImageMetadata(0);

        if (!param.getCompressionType().equals(param.getCompressionTypes()[mdata.compression])) {
            throw new RuntimeException("Different compression value");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException("Unexpected exception: " + ex);
    }

}