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

The following examples show how to use javax.imageio.ImageWriter#setOutput() . 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: ShortHistogramTest.java    From openjdk-jdk9 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 2
Source File: SunJPEGEncoderAdapter.java    From buffer_bci with GNU General Public License v3.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 3
Source File: GImage.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private Icon getIcon(ImageWriter imageWriter) throws IOException {
	GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
	GraphicsDevice gDev = gEnv.getDefaultScreenDevice();
	GraphicsConfiguration gConfig = gDev.getDefaultConfiguration();

	BufferedImage bufferedImage = gConfig.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
	bufferedImage.setRGB(0, 0, width, height, array, 0, width);

	OutputStream out = new ByteArrayOutputStream();
	ImageOutputStream imageOut = new MemoryCacheImageOutputStream(out);

	imageWriter.setOutput(imageOut);

	try {
		imageWriter.write(bufferedImage);
	}
	finally {
		imageOut.close();
	}

	Icon icon = new ImageIcon(bufferedImage);
	return icon;
}
 
Example 4
Source File: JmeDesktopSystem.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void writeImageFile(OutputStream outStream, String format, ByteBuffer imageData, int width, int height) throws IOException {
    BufferedImage awtImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Screenshots.convertScreenShot2(imageData.asIntBuffer(), awtImage);

    ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
    ImageWriteParam writeParam = writer.getDefaultWriteParam();

    if (format.equals("jpg")) {
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) writeParam;
        jpegParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(0.95f);
    }

    awtImage = verticalFlip(awtImage);
    
    ImageOutputStream imgOut = new MemoryCacheImageOutputStream(outStream);
    writer.setOutput(imgOut);
    IIOImage outputImage = new IIOImage(awtImage, null, null);
    try {
        writer.write(null, outputImage, writeParam);
    } finally {
        imgOut.close();
        writer.dispose();
    }
}
 
Example 5
Source File: Server.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ImageTranslator(float cq) {
    compressionQuality = cq;

    try {
        baos =  new ByteArrayOutputStream();
        ios = ImageIO.createImageOutputStream(baos);

        writers = ImageIO.getImageWritersByFormatName("jpeg");
        writer = (ImageWriter)writers.next();
        writer.setOutput(ios);

        param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(compressionQuality);

    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(0);
    }
}
 
Example 6
Source File: LUTCompareTest.java    From dragonwell8_jdk 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 7
Source File: OCRUtil.java    From JewelCrawler with GNU General Public License v3.0 5 votes vote down vote up
public static File createImage(File imageFile, String imageFormat) {
	File tempFile = null;
	try {
		Iterator<ImageReader> readers = ImageIO
				.getImageReadersByFormatName(imageFormat);
		ImageReader reader = readers.next();

		ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
		reader.setInput(iis);
		// Read the stream metadata
		IIOMetadata streamMetadata = reader.getStreamMetadata();

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

		// Get tif writer and set output to file
		Iterator<ImageWriter> writers = ImageIO
				.getImageWritersByFormatName("tiff");
		ImageWriter writer = writers.next();

		BufferedImage bi = reader.read(0);
		// bi = new ImageFilter(bi).changeGrey();
		IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
		tempFile = tempImageFile(imageFile);
		ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
		writer.setOutput(ios);
		writer.write(streamMetadata, image, tiffWriteParam);
		ios.close();

		writer.dispose();
		reader.dispose();
	} catch (Exception exc) {
		exc.printStackTrace();
	}
	return tempFile;
}
 
Example 8
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 9
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 10
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 11
Source File: RuntimeBuiltinLeafInfoImpl.java    From jdk8u60 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 12
Source File: ChartPanel.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean saveImage_Jpeg(String file, int width, int height, int dpi) {
    double scaleFactor = dpi / 72.0;
    BufferedImage bufferedImage = new BufferedImage((int)(width * scaleFactor), (int)(height * scaleFactor), BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bufferedImage.createGraphics();
    AffineTransform at = g.getTransform();
    at.scale(scaleFactor, scaleFactor);
    g.setTransform(at);
    paintGraphics(g, width, height);

    try {
        // Image writer 
        ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file));
        imageWriter.setOutput(ios);

        // Compression
        JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(0.85f);

        // Metadata (dpi)
        IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams);
        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"); // density is dots per inch	
        data.setFromTree("javax_imageio_jpeg_image_1.0", tree);

        // Write and clean up
        imageWriter.write(null, new IIOImage(bufferedImage, null, data), jpegParams);
        ios.close();
        imageWriter.dispose();
    } catch (Exception e) {
        return false;
    }
    g.dispose();

    return true;
}
 
Example 13
Source File: ITXtTest.java    From openjdk-jdk9 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));
        System.out.println("Writing done.");
    } catch (Throwable e) {
        throw new RuntimeException("Writing test failed.", e);
    }
}
 
Example 14
Source File: BMPSubsamplingTest.java    From openjdk-jdk9 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 15
Source File: Images.java    From restcommander with Apache License 2.0 4 votes vote down vote up
/**
 * Resize an image
 * @param originalImage The image file
 * @param to The destination file
 * @param w The new width (or -1 to proportionally resize) or the maxWidth if keepRatio is true
 * @param h The new height (or -1 to proportionally resize) or the maxHeight if keepRatio is true
 * @param keepRatio : if true, resize will keep the original image ratio and use w and h as max dimensions
 */
public static void resize(File originalImage, File to, int w, int h, boolean keepRatio) {
    try {
        BufferedImage source = ImageIO.read(originalImage);
        int owidth = source.getWidth();
        int oheight = source.getHeight();
        double ratio = (double) owidth / oheight;
        
        int maxWidth = w;
        int maxHeight = h;
        
        if (w < 0 && h < 0) {
            w = owidth;
            h = oheight;
        }
        if (w < 0 && h > 0) {
            w = (int) (h * ratio);
        }
        if (w > 0 && h < 0) {
            h = (int) (w / ratio);
        }
        
        if(keepRatio) {
            h = (int) (w / ratio);
            if(h > maxHeight) {
                h = maxHeight;
                w = (int) (h * ratio);
            }
            if(w > maxWidth) {
                w = maxWidth;
                h = (int) (w / ratio);
            }
        }

        String mimeType = "image/jpeg";
        if (to.getName().endsWith(".png")) {
            mimeType = "image/png";
        }
        if (to.getName().endsWith(".gif")) {
            mimeType = "image/gif";
        }

        // out
        BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Image srcSized = source.getScaledInstance(w, h, Image.SCALE_SMOOTH);
        Graphics graphics = dest.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, w, h);
        graphics.drawImage(srcSized, 0, 0, null);
        ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
        ImageWriteParam params = writer.getDefaultWriteParam();
        FileImageOutputStream toFs = new FileImageOutputStream(to);
        writer.setOutput(toFs);
        IIOImage image = new IIOImage(dest, null, null);
        writer.write(null, image, params);
        toFs.flush();
        toFs.close();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 16
Source File: WriteAfterAbort.java    From openjdk-jdk8u-backup 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 17
Source File: ReaderListenersTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void doTest(String compression) {
    try {
        BufferedImage img = createTestImage();

        ImageWriter iw = (ImageWriter)
            ImageIO.getImageWritersByFormatName("bmp").next();
        if (iw == null) {
            throw new RuntimeException("No writers for bmp format."
                                       + " Test failed.");
        }


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        iw.setOutput(ImageIO.createImageOutputStream(baos));
        ImageWriteParam param = iw.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionType(compression);

        iw.write(null, new IIOImage(img, null, null), param);
        baos.close();

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

        ImageReader ir = (ImageReader)
            ImageIO.getImageReadersByFormatName("bmp").next();
        if (ir == null) {
            throw new RuntimeException("No readers for bmp format."
                                       + " Test failed.");
        }

        IIOReadUpdateAdapter updateAdapter = new IIOReadUpdateAdapter();
        IIOReadProgressAdapter progressAdapter = new IIOReadProgressAdapter();
        ir.addIIOReadProgressListener(progressAdapter);
        ir.addIIOReadUpdateListener(updateAdapter);
        ir.setInput(ImageIO.createImageInputStream(bais));
        BufferedImage dst = ir.read(0);

        progressAdapter.checkResults();

        if (!updateAdapter.isImageUpdateUsed) {
            throw new RuntimeException("imageUpdate was not used."
                                       + " Test failed.");
        }
    } catch(IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Test failed");
    }
}
 
Example 18
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 19
Source File: BooleanAttributes.java    From openjdk-8-source 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 20
Source File: ImageShrinker.java    From triplea with GNU General Public License v3.0 4 votes vote down vote up
private void runInternal(final String[] args) throws IOException {
  handleCommandLineArgs(args);
  JOptionPane.showMessageDialog(
      null,
      new JLabel(
          "<html>"
              + "This is the ImageShrinker, it will create a smallMap.jpeg file for you. "
              + "<br>Put in your base map or relief map, and it will spit out a small "
              + "scaled copy of it."
              + "<br>Please note that the quality of the image will be worse than if you use a "
              + "real painting program."
              + "<br>So we suggest you instead shrink the image with paint.net or photoshop or "
              + "gimp, etc, then clean it up before saving."
              + "</html>"));
  final File mapFile =
      new FileOpen("Select The Large Image", mapFolderLocation, ".gif", ".png").getFile();
  if (mapFile == null || !mapFile.exists()) {
    throw new IllegalStateException(mapFile + "File does not exist");
  }
  if (mapFolderLocation == null) {
    mapFolderLocation = mapFile.getParentFile();
  }
  final String input = JOptionPane.showInputDialog(null, "Select scale");
  final float scale = Float.parseFloat(input);
  final Image baseImg = ImageIO.read(mapFile);
  final int thumbWidth = (int) (baseImg.getWidth(null) * scale);
  final int thumbHeight = (int) (baseImg.getHeight(null) * scale);
  // based on code from
  // http://www.geocities.com/marcoschmidt.geo/java-save-jpeg-thumbnail.html
  // draw original image to thumbnail image object and scale it to the new size on-the-fly
  final BufferedImage thumbImage =
      new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
  final Graphics2D graphics2D = thumbImage.createGraphics();
  graphics2D.setRenderingHint(
      RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  graphics2D.drawImage(baseImg, 0, 0, thumbWidth, thumbHeight, null);
  // save thumbnail image to OUTFILE
  final File file =
      new File(new File(mapFile.getPath()).getParent() + File.separatorChar + "smallMap.jpeg");
  try (ImageOutputStream out = new FileImageOutputStream(file)) {
    final ImageWriter encoder = ImageIO.getImageWritersByFormatName("JPEG").next();
    final JPEGImageWriteParam param = new JPEGImageWriteParam(null);
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality((float) 1.0);
    encoder.setOutput(out);
    encoder.write(null, new IIOImage(thumbImage, null, null), param);
  }
  log.info("Image successfully written to " + file.getPath());
}