Search in sources :

Example 21 with IIOImage

use of javax.imageio.IIOImage in project jdk8u_jdk by JetBrains.

the class ShortHistogramTest method writeImageWithHist.

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, // no thumbnails
    null, imgMetadata);
    writer.write(iio_img);
    ios.flush();
    ios.close();
    return f;
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) ImageWriter(javax.imageio.ImageWriter) ImageWriteParam(javax.imageio.ImageWriteParam) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage)

Example 22 with IIOImage

use of javax.imageio.IIOImage in project libgdx by libgdx.

the class TexturePacker method writeImages.

private void writeImages(File outputDir, String scaledPackFileName, Array<Page> pages) {
    File packFileNoExt = new File(outputDir, scaledPackFileName);
    File packDir = packFileNoExt.getParentFile();
    String imageName = packFileNoExt.getName();
    int fileIndex = 0;
    for (Page page : pages) {
        int width = page.width, height = page.height;
        int paddingX = settings.paddingX;
        int paddingY = settings.paddingY;
        if (settings.duplicatePadding) {
            paddingX /= 2;
            paddingY /= 2;
        }
        width -= settings.paddingX;
        height -= settings.paddingY;
        if (settings.edgePadding) {
            page.x = paddingX;
            page.y = paddingY;
            width += paddingX * 2;
            height += paddingY * 2;
        }
        if (settings.pot) {
            width = MathUtils.nextPowerOfTwo(width);
            height = MathUtils.nextPowerOfTwo(height);
        }
        width = Math.max(settings.minWidth, width);
        height = Math.max(settings.minHeight, height);
        page.imageWidth = width;
        page.imageHeight = height;
        File outputFile;
        while (true) {
            outputFile = new File(packDir, imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat);
            if (!outputFile.exists())
                break;
        }
        new FileHandle(outputFile).parent().mkdirs();
        page.imageName = outputFile.getName();
        BufferedImage canvas = new BufferedImage(width, height, getBufferedImageType(settings.format));
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        if (!settings.silent)
            System.out.println("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile);
        for (Rect rect : page.outputRects) {
            BufferedImage image = rect.getImage(imageProcessor);
            int iw = image.getWidth();
            int ih = image.getHeight();
            int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height;
            if (settings.duplicatePadding) {
                int amountX = settings.paddingX / 2;
                int amountY = settings.paddingY / 2;
                if (rect.rotated) {
                    // Copy corner pixels to fill corners of the padding.
                    for (int i = 1; i <= amountX; i++) {
                        for (int j = 1; j <= amountY; j++) {
                            plot(canvas, rectX - j, rectY + iw - 1 + i, image.getRGB(0, 0));
                            plot(canvas, rectX + ih - 1 + j, rectY + iw - 1 + i, image.getRGB(0, ih - 1));
                            plot(canvas, rectX - j, rectY - i, image.getRGB(iw - 1, 0));
                            plot(canvas, rectX + ih - 1 + j, rectY - i, image.getRGB(iw - 1, ih - 1));
                        }
                    }
                    // Copy edge pixels into padding.
                    for (int i = 1; i <= amountY; i++) {
                        for (int j = 0; j < iw; j++) {
                            plot(canvas, rectX - i, rectY + iw - 1 - j, image.getRGB(j, 0));
                            plot(canvas, rectX + ih - 1 + i, rectY + iw - 1 - j, image.getRGB(j, ih - 1));
                        }
                    }
                    for (int i = 1; i <= amountX; i++) {
                        for (int j = 0; j < ih; j++) {
                            plot(canvas, rectX + j, rectY - i, image.getRGB(iw - 1, j));
                            plot(canvas, rectX + j, rectY + iw - 1 + i, image.getRGB(0, j));
                        }
                    }
                } else {
                    // Copy corner pixels to fill corners of the padding.
                    for (int i = 1; i <= amountX; i++) {
                        for (int j = 1; j <= amountY; j++) {
                            plot(canvas, rectX - i, rectY - j, image.getRGB(0, 0));
                            plot(canvas, rectX - i, rectY + ih - 1 + j, image.getRGB(0, ih - 1));
                            plot(canvas, rectX + iw - 1 + i, rectY - j, image.getRGB(iw - 1, 0));
                            plot(canvas, rectX + iw - 1 + i, rectY + ih - 1 + j, image.getRGB(iw - 1, ih - 1));
                        }
                    }
                    // Copy edge pixels into padding.
                    for (int i = 1; i <= amountY; i++) {
                        copy(image, 0, 0, iw, 1, canvas, rectX, rectY - i, rect.rotated);
                        copy(image, 0, ih - 1, iw, 1, canvas, rectX, rectY + ih - 1 + i, rect.rotated);
                    }
                    for (int i = 1; i <= amountX; i++) {
                        copy(image, 0, 0, 1, ih, canvas, rectX - i, rectY, rect.rotated);
                        copy(image, iw - 1, 0, 1, ih, canvas, rectX + iw - 1 + i, rectY, rect.rotated);
                    }
                }
            }
            copy(image, 0, 0, iw, ih, canvas, rectX, rectY, rect.rotated);
            if (settings.debug) {
                g.setColor(Color.magenta);
                g.drawRect(rectX, rectY, rect.width - settings.paddingX - 1, rect.height - settings.paddingY - 1);
            }
        }
        if (settings.bleed && !settings.premultiplyAlpha && !(settings.outputFormat.equalsIgnoreCase("jpg") || settings.outputFormat.equalsIgnoreCase("jpeg"))) {
            canvas = new ColorBleedEffect().processImage(canvas, settings.bleedIterations);
            g = (Graphics2D) canvas.getGraphics();
        }
        if (settings.debug) {
            g.setColor(Color.magenta);
            g.drawRect(0, 0, width - 1, height - 1);
        }
        ImageOutputStream ios = null;
        try {
            if (settings.outputFormat.equalsIgnoreCase("jpg") || settings.outputFormat.equalsIgnoreCase("jpeg")) {
                BufferedImage newImage = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
                newImage.getGraphics().drawImage(canvas, 0, 0, null);
                canvas = newImage;
                Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
                ImageWriter writer = writers.next();
                ImageWriteParam param = writer.getDefaultWriteParam();
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(settings.jpegQuality);
                ios = ImageIO.createImageOutputStream(outputFile);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(canvas, null, null), param);
            } else {
                if (settings.premultiplyAlpha)
                    canvas.getColorModel().coerceData(canvas.getRaster(), true);
                ImageIO.write(canvas, "png", outputFile);
            }
        } catch (IOException ex) {
            throw new RuntimeException("Error writing file: " + outputFile, ex);
        } finally {
            if (ios != null) {
                try {
                    ios.close();
                } catch (Exception ignored) {
                }
            }
        }
    }
}
Also used : FileHandle(com.badlogic.gdx.files.FileHandle) ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) BufferedImage(java.awt.image.BufferedImage) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) IOException(java.io.IOException) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 23 with IIOImage

use of javax.imageio.IIOImage in project Lucee by lucee.

the class Image method _writeOut.

private void _writeOut(ImageOutputStream ios, String format, float quality, boolean noMeta) throws IOException, ExpressionException {
    if (quality < 0 || quality > 1)
        throw new IOException("quality has an invalid value [" + quality + "], value has to be between 0 and 1");
    if (StringUtil.isEmpty(format))
        format = this.format;
    if (StringUtil.isEmpty(format))
        throw new IOException("missing format");
    BufferedImage im = image();
    // IIOMetadata meta = noMeta?null:metadata(format);
    IIOMetadata meta = noMeta ? null : getMetaData(null);
    ImageWriter writer = null;
    ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format);
    if (iter.hasNext()) {
        writer = iter.next();
    }
    if (writer == null)
        throw new IOException("no writer for format [" + format + "] available, available writer formats are [" + ListUtil.arrayToList(ImageUtil.getWriterFormatNames(), ",") + "]");
    ImageWriteParam iwp = getImageWriteParam(im, writer, quality, this.format, format);
    writer.setOutput(ios);
    try {
        writer.write(meta, new IIOImage(im, null, meta), iwp);
    } finally {
        writer.dispose();
        ios.flush();
        this.format = format;
    }
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage)

Example 24 with IIOImage

use of javax.imageio.IIOImage in project pdfbox by apache.

the class ImageIOUtil method writeImage.

/**
 * Writes a buffered image to a file using the given image format.
 * Compression is fixed for PNG, GIF, BMP and WBMP, dependent of the quality
 * parameter for JPG, and dependent of bit count for TIFF (a bitonal image
 * will be compressed with CCITT G4, a color image with LZW). Creating a
 * TIFF image is only supported if the jai_imageio library is in the class
 * path.
 *
 * @param image the image to be written
 * @param formatName the target format (ex. "png")
 * @param output the output stream to be used for writing
 * @param dpi the resolution in dpi (dots per inch) to be used in metadata
 * @param quality quality to be used when compressing the image (0 &lt;
 * quality &lt; 1.0f)
 * @return true if the image file was produced, false if there was an error.
 * @throws IOException if an I/O error occurs
 */
public static boolean writeImage(BufferedImage image, String formatName, OutputStream output, int dpi, float quality) throws IOException {
    ImageOutputStream imageOutput = null;
    ImageWriter writer = null;
    try {
        // find suitable image writer
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
        ImageWriteParam param = null;
        IIOMetadata metadata = null;
        // accept a driver that can't, if a better one can't be found
        while (writers.hasNext()) {
            if (writer != null) {
                writer.dispose();
            }
            writer = writers.next();
            if (writer != null) {
                param = writer.getDefaultWriteParam();
                metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
                if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                    break;
                }
            }
        }
        if (writer == null) {
            LOG.error("No ImageWriter found for '" + formatName + "' format");
            StringBuilder sb = new StringBuilder();
            String[] writerFormatNames = ImageIO.getWriterFormatNames();
            for (String fmt : writerFormatNames) {
                sb.append(fmt);
                sb.append(' ');
            }
            LOG.error("Supported formats: " + sb);
            return false;
        }
        // compression
        if (param != null && param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            if (formatName.toLowerCase().startsWith("tif")) {
                // TIFF compression
                TIFFUtil.setCompressionType(param, image);
            } else {
                param.setCompressionType(param.getCompressionTypes()[0]);
                param.setCompressionQuality(quality);
            }
        }
        if (formatName.toLowerCase().startsWith("tif")) {
            // TIFF metadata
            TIFFUtil.updateMetadata(metadata, image, dpi);
        } else if ("jpeg".equals(formatName.toLowerCase()) || "jpg".equals(formatName.toLowerCase())) {
            // This segment must be run before other meta operations,
            // or else "IIOInvalidTreeException: Invalid node: app0JFIF"
            // The other (general) "meta" methods may not be used, because
            // this will break the reading of the meta data in tests
            JPEGUtil.updateMetadata(metadata, dpi);
        } else {
            // write metadata is possible
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                setDPI(metadata, dpi, formatName);
            }
        }
        // write
        imageOutput = ImageIO.createImageOutputStream(output);
        writer.setOutput(imageOutput);
        writer.write(null, new IIOImage(image, null, metadata), param);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (imageOutput != null) {
            imageOutput.close();
        }
    }
    return true;
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) ImageWriter(javax.imageio.ImageWriter) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage)

Example 25 with IIOImage

use of javax.imageio.IIOImage in project quick-media by liuyueyi.

the class ImageIOImageWriter method writeImage.

/**
 * @see ImageWriter#writeImage(java.awt.image.RenderedImage, java.io.OutputStream, ImageWriterParams)
 */
public void writeImage(RenderedImage image, OutputStream out, ImageWriterParams params) throws IOException {
    Iterator iter;
    iter = ImageIO.getImageWritersByMIMEType(getMIMEType());
    javax.imageio.ImageWriter iiowriter = null;
    try {
        iiowriter = (javax.imageio.ImageWriter) iter.next();
        if (iiowriter != null) {
            iiowriter.addIIOWriteWarningListener(this);
            ImageOutputStream imgout = null;
            try {
                imgout = ImageIO.createImageOutputStream(out);
                ImageWriteParam iwParam = getDefaultWriteParam(iiowriter, image, params);
                ImageTypeSpecifier type;
                if (iwParam.getDestinationType() != null) {
                    type = iwParam.getDestinationType();
                } else {
                    type = ImageTypeSpecifier.createFromRenderedImage(image);
                }
                // Handle metadata
                IIOMetadata meta = iiowriter.getDefaultImageMetadata(type, iwParam);
                // meta might be null for some JAI codecs as they don't support metadata
                if (params != null && meta != null) {
                    meta = updateMetadata(meta, params);
                }
                // Write image
                iiowriter.setOutput(imgout);
                IIOImage iioimg = new IIOImage(image, null, meta);
                iiowriter.write(null, iioimg, iwParam);
            } finally {
                if (imgout != null) {
                    imgout.close();
                }
            }
        } else {
            throw new UnsupportedOperationException("No ImageIO codec for writing " + getMIMEType() + " is available!");
        }
    } finally {
        if (iiowriter != null) {
            iiowriter.dispose();
        }
    }
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) Iterator(java.util.Iterator) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage)

Aggregations

IIOImage (javax.imageio.IIOImage)123 ImageWriter (javax.imageio.ImageWriter)92 ImageWriteParam (javax.imageio.ImageWriteParam)79 ImageOutputStream (javax.imageio.stream.ImageOutputStream)79 BufferedImage (java.awt.image.BufferedImage)66 File (java.io.File)45 IOException (java.io.IOException)41 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 IIOMetadata (javax.imageio.metadata.IIOMetadata)32 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)25 ByteArrayInputStream (java.io.ByteArrayInputStream)22 FileImageOutputStream (javax.imageio.stream.FileImageOutputStream)17 ImageReader (javax.imageio.ImageReader)16 MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)16 Graphics2D (java.awt.Graphics2D)14 JPEGImageWriteParam (javax.imageio.plugins.jpeg.JPEGImageWriteParam)14 Test (org.junit.Test)14 FileOutputStream (java.io.FileOutputStream)13 Iterator (java.util.Iterator)11 RenderedImage (java.awt.image.RenderedImage)10