Search in sources :

Example 71 with ImageWriter

use of javax.imageio.ImageWriter in project imageio-ext by geosolutions-it.

the class JP2KKakaduWriteTest method testOutputStream.

public void testOutputStream() throws IOException {
    if (!isKakaduAvailable) {
        LOGGER.warning("Kakadu libs not found: test are skipped ");
        return;
    }
    final File outFile = File.createTempFile("stream", "temp");
    final FileImageOutputStream stream = new FileImageOutputStream(outFile);
    stream.writeBytes("This is an Image Header written before the j2c raw codestream");
    final ImageReader reader = new BMPImageReaderSpi().createReaderInstance();
    final File file = TestData.file(this, "RGB24.bmp");
    reader.setInput(ImageIO.createImageInputStream(file));
    BufferedImage bi = reader.read(0);
    final ImageWriter writer = new JP2KKakaduImageWriterSpi().createWriterInstance();
    JP2KKakaduImageWriteParam param = new JP2KKakaduImageWriteParam();
    param.setQuality(0.8);
    param.setWriteCodeStreamOnly(true);
    writer.setOutput(stream);
    writer.write(null, new IIOImage(bi, null, null), param);
    writer.dispose();
    LOGGER.info(writeOperations + " write operations performed");
}
Also used : FileImageOutputStream(javax.imageio.stream.FileImageOutputStream) ImageWriter(javax.imageio.ImageWriter) BMPImageReaderSpi(com.sun.imageio.plugins.bmp.BMPImageReaderSpi) ImageReader(javax.imageio.ImageReader) File(java.io.File) BufferedImage(java.awt.image.BufferedImage) IIOImage(javax.imageio.IIOImage)

Example 72 with ImageWriter

use of javax.imageio.ImageWriter in project imageio-ext by geosolutions-it.

the class NITFImageWriter method writeNITF.

/**
 * Do the real write operation (writing images, texts, ...)
 *
 * @param record
 * @param images
 * @param shp
 * @param fis
 * @param text
 * @return
 * @throws NITFException
 * @throws IOException
 */
private boolean writeNITF(final Record record, final List<ImageWrapper> images, final ShapeFileWrapper shp, final FileImageInputStreamExt fis, final List<TextWrapper> texts) throws NITFException, IOException {
    final int numImages = images.size();
    ImageWrapper image = images.get(0);
    RenderedImage ri = image.getImage();
    WriteCompression compression = image.getCompression();
    int nBands = ri.getSampleModel().getNumBands();
    boolean written = false;
    Writer writer = new Writer();
    IOHandle handle = new IOHandle(outputFile.getCanonicalPath(), IOHandle.NITF_ACCESS_WRITEONLY, IOHandle.NITF_CREATE);
    byte[] shapeFileData = null;
    final boolean isJP2 = !(compression == WriteCompression.UNCOMPRESSED);
    if (shp != null) {
        shapeFileData = getShapeData(record, shp);
    }
    boolean prepared = false;
    if (isJP2) {
        // //
        // 
        // get the JP2 Codestream previously written with Kakadu and transfer its content within
        // the NITF imageSegment
        // 
        // //
        WriteHandler codeStream = null;
        IOInterface io;
        final int size = (int) fis.length();
        io = new IOFileInputStream(fis);
        writer.prepare(record, handle);
        if (shapeFileData != null) {
            writeData(shapeFileData, writer);
        }
        codeStream = new StreamIOWriteHandler(io, 0, size);
        writer.setImageWriteHandler(0, codeStream);
        prepared = true;
    }
    if (!isJP2 || numImages > 1) {
        if (!prepared) {
            writer.prepare(record, handle);
        }
        if (numImages == 1) {
            // setup a Writer
            if (shapeFileData != null) {
                writeData(shapeFileData, writer);
            }
            ImageSource imageSource = new ImageSource();
            nitf.ImageWriter imageWriter = writer.getNewImageWriter(0);
            boolean[] successes = new boolean[nBands];
            final boolean isMono = images.get(0).getImage().getSampleModel().getNumBands() == 1;
            if (isMono) {
                DataBufferByte dbb = (DataBufferByte) ri.getData().getDataBuffer();
                BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
                successes[0] = imageSource.addBand(bs);
            } else {
                for (int i = 0; i < nBands; i++) {
                    RenderedImage band = BandSelectDescriptor.create(ri, new int[] { i }, null);
                    DataBufferByte dbb = (DataBufferByte) band.getData().getDataBuffer();
                    BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
                    successes[i] = imageSource.addBand(bs);
                }
            }
            imageWriter.attachSource(imageSource);
        } else {
            ImageWrapper img = images.get(1);
            ri = img.getImage();
            nBands = ri.getSampleModel().getNumBands();
            ImageSource imageSource = new ImageSource();
            nitf.ImageWriter imageWriter2 = writer.getNewImageWriter(1);
            boolean[] successes = new boolean[nBands];
            DataBufferByte dbb = (DataBufferByte) ri.getData().getDataBuffer();
            BandSource bs = new MemorySource(dbb.getData(), dbb.getSize(), 0, 0, 0);
            successes[0] = imageSource.addBand(bs);
            imageWriter2.attachSource(imageSource);
        }
    }
    // Adding text
    if (texts != null && !texts.isEmpty()) {
        int i = 0;
        for (TextWrapper text : texts) {
            byte[] textContent = text.getTextContent();
            if (textContent != null) {
                SegmentWriter textWriter = writer.getNewTextWriter(i++);
                SegmentSource source = SegmentSource.makeSegmentMemorySource(textContent, textContent.length, 0, 0);
                textWriter.attachSource(source);
            }
        }
    }
    written = writer.write();
    if (handle != null) {
        handle.close();
    }
    return written;
}
Also used : IOHandle(nitf.IOHandle) StreamIOWriteHandler(nitf.StreamIOWriteHandler) DataBufferByte(java.awt.image.DataBufferByte) SegmentSource(nitf.SegmentSource) BandSource(nitf.BandSource) TextWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.TextWrapper) ImageWrapper(it.geosolutions.imageio.plugins.nitronitf.wrapper.ImageWrapper) WriteHandler(nitf.WriteHandler) StreamIOWriteHandler(nitf.StreamIOWriteHandler) IOInterface(nitf.IOInterface) ImageSource(nitf.ImageSource) MemorySource(nitf.MemorySource) RenderedImage(java.awt.image.RenderedImage) SegmentWriter(nitf.SegmentWriter) JP2KKakaduImageWriter(it.geosolutions.imageio.plugins.jp2k.JP2KKakaduImageWriter) SegmentWriter(nitf.SegmentWriter) Writer(nitf.Writer) ImageWriter(javax.imageio.ImageWriter) WriteCompression(it.geosolutions.imageio.plugins.nitronitf.NITFUtilities.WriteCompression)

Example 73 with ImageWriter

use of javax.imageio.ImageWriter in project digilib by robcast.

the class ImageLoaderDocuImage method writeImage.

/* 
     * (non-Javadoc)
     * @see digilib.image.DocuImageImpl#writeImage(java.lang.String, java.io.OutputStream)
     */
public void writeImage(String mt, OutputStream ostream) throws ImageOpException, FileOpException {
    logger.debug("writeImage");
    // setup output
    ImageWriter writer = null;
    ImageOutputStream imgout = null;
    try {
        imgout = ImageIO.createImageOutputStream(ostream);
        if (mt == "image/jpeg") {
            /*
                 * JPEG doesn't do transparency so we have to convert any RGBA
                 * image to RGB or we the client will think its CMYK :-( *Java2D
                 * BUG*
                 */
            if (img.getColorModel().hasAlpha()) {
                logger.debug("BARF: JPEG with transparency!!");
                BufferedImage rgbImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
                rgbImg.createGraphics().drawImage(img, null, 0, 0);
                img = rgbImg;
            }
            writer = ImageIO.getImageWritersByFormatName("jpeg").next();
            if (writer == null) {
                throw new ImageOpException("Unable to get JPEG writer");
            }
            ImageWriteParam param = writer.getDefaultWriteParam();
            if (quality > 1) {
                // change JPEG compression quality
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(0.9f);
            }
            writer.setOutput(imgout);
            // render output
            logger.debug("writing JPEG");
            writer.write(null, new IIOImage(img, null, null), param);
        } else if (mt == "image/png") {
            // render output
            writer = ImageIO.getImageWritersByFormatName("png").next();
            if (writer == null) {
                throw new ImageOpException("Unable to get PNG writer");
            }
            writer.setOutput(imgout);
            logger.debug("writing PNG");
            writer.write(img);
        } else {
            // unknown mime type
            throw new ImageOpException("Unknown mime type: " + mt);
        }
    } catch (IOException e) {
        logger.error("Error writing image:", e);
        throw new FileOpException("Error writing image!", e);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (imgout != null) {
            /* 
        		 * ImageOutputStream likes to keep ServletOutputStream and close it when disposed.
        		 * Thanks to Tom Van Wietmarschen's mail to tomcat-users on July 4, 2008!
        		 */
            try {
                imgout.close();
            } catch (IOException e) {
                logger.error("Error closing ImageOutputStream!", e);
            }
        }
    }
}
Also used : ImageWriter(javax.imageio.ImageWriter) FileOpException(digilib.io.FileOpException) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) BufferedImage(java.awt.image.BufferedImage) IIOImage(javax.imageio.IIOImage)

Example 74 with ImageWriter

use of javax.imageio.ImageWriter in project ChatGameFontificator by GlitchCog.

the class AnimatedGifUtil method loadDittoAnimatedGif.

/**
 * Fix (ditto) for Java's animated GIF interpretation
 *
 * Adapted from http://stackoverflow.com/questions/26801433/fix-frame-rate-of-animated-gif-in-java#answer-26829534
 *
 * @param url
 *            The URL for the animated GIF to be loaded
 * @param dim
 *            The dimension object to be filled by the width and height of the loaded animated GIF
 * @return The loaded animated GIF
 * @throws Exception
 */
public static Image loadDittoAnimatedGif(final URL url, Dimension dim) {
    final Image dimImage = new ImageIcon(url).getImage();
    Image image = null;
    try {
        ImageReader gifReader = ImageIO.getImageReadersByFormatName(GIF_EXTENSION).next();
        InputStream imageStream = url.openStream();
        gifReader.setInput(ImageIO.createImageInputStream(imageStream));
        IIOMetadata imageMetaData = gifReader.getImageMetadata(0);
        String metaFormatName = imageMetaData.getNativeMetadataFormatName();
        final int frameCount = gifReader.getNumImages(true);
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
        ImageWriter writer = ImageIO.getImageWriter(gifReader);
        writer.setOutput(ios);
        writer.prepareWriteSequence(null);
        final int imgWidth = dimImage.getWidth(null);
        final int imgHeight = dimImage.getHeight(null);
        dim.setSize(imgWidth, imgHeight);
        for (int i = 0; i < frameCount; i++) {
            // This read method takes into account the frame's top and left coordinates
            BufferedImage frame = gifReader.read(i);
            IIOMetadataNode nodes = (IIOMetadataNode) gifReader.getImageMetadata(i).getAsTree(metaFormatName);
            for (int j = 0; j < nodes.getLength(); j++) {
                IIOMetadataNode node = (IIOMetadataNode) nodes.item(j);
                if (GRAPHIC_CTRL_EXT.equalsIgnoreCase(node.getNodeName())) {
                    int delay = Integer.parseInt(node.getAttribute(ATTRIBUTE_DELAY_TIME));
                    // Minimum delay for browsers, which delay animated GIFs much more than would be to spec
                    if (delay < MIN_ANI_GIF_DELAY) {
                        node.setAttribute(ATTRIBUTE_DELAY_TIME, Integer.toString(MIN_ANI_GIF_DELAY));
                    }
                    // at least not for BTTV's (ditto)
                    if (node.getAttribute(ATTRIBUTE_DISPOSAL_METHOD).equals(DISPOSE_RESTORE_TO_PREVIOUS)) {
                        node.setAttribute(ATTRIBUTE_DISPOSAL_METHOD, DISPOSE_RESTORE_TO_BGCOLOR);
                    }
                }
            }
            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frame), null);
            metadata.setFromTree(metadata.getNativeMetadataFormatName(), nodes);
            // This modified frame is necessary to get the correct image placement, width, and height in the final GIF
            BufferedImage frameMod = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics big = frameMod.getGraphics();
            big.drawImage(frame, 0, 0, null);
            IIOImage fixedFrame = new IIOImage(frameMod, null, metadata);
            writer.writeToSequence(fixedFrame, writer.getDefaultWriteParam());
        }
        writer.endWriteSequence();
        if (ios != null) {
            ios.close();
        }
        image = Toolkit.getDefaultToolkit().createImage(baoStream.toByteArray());
    } catch (Exception e) {
        // If anything goes wrong, just load it normally
        logger.error("Error loading animated GIF (ditto) from " + url, e);
        image = new ImageIcon(url).getImage();
        dim.setSize(image.getWidth(null), image.getHeight(null));
    }
    return image;
}
Also used : ImageIcon(javax.swing.ImageIcon) InputStream(java.io.InputStream) ImageWriter(javax.imageio.ImageWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IIOImage(javax.imageio.IIOImage) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage) IIOMetadata(javax.imageio.metadata.IIOMetadata) Graphics(java.awt.Graphics) ImageReader(javax.imageio.ImageReader) IIOMetadataNode(javax.imageio.metadata.IIOMetadataNode) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 75 with ImageWriter

use of javax.imageio.ImageWriter in project ChatGameFontificator by GlitchCog.

the class ControlWindow method saveScreenshot.

/**
 * Takes and saves a screenshot of the current chat window
 *
 * @return whether the screenshot was saved
 */
private boolean saveScreenshot() {
    // Take the screenshot before the save file chooser is shown
    ChatPanel chat = chatWindow.getChatPanel();
    BufferedImage chatImage = new BufferedImage(chat.getWidth(), chat.getHeight(), screenshotOptions.isTransparencyEnabled() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
    Graphics chatGraphics = chatImage.getGraphics();
    chat.paint(chatGraphics);
    final boolean chromaEnabled = Boolean.toString(true).equalsIgnoreCase(fProps.getProperty(FontificatorProperties.KEY_CHAT_CHROMA_ENABLED));
    if (screenshotOptions.isTransparencyEnabled() && chromaEnabled) {
        final int chromaKey = new Color(Integer.parseInt(fProps.getProperty(FontificatorProperties.KEY_COLOR_CHROMA_KEY), 16)).getRGB();
        final int transparentPixel = new Color(0, true).getRGB();
        for (int r = 0; r < chatImage.getHeight(); r++) {
            for (int c = 0; c < chatImage.getWidth(); c++) {
                if (chatImage.getRGB(c, r) == chromaKey) {
                    chatImage.setRGB(c, r, transparentPixel);
                }
            }
        }
    }
    File saveFile = getTargetSaveFile(screenshotSaver, DEFAULT_SCREENSHOT_FILE_EXTENSION);
    if (saveFile != null) {
        try {
            if (screenshotOptions.isMetadataEnabled()) {
                ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next();
                ImageOutputStream stream = ImageIO.createImageOutputStream(saveFile);
                writer.setOutput(stream);
                IIOMetadata metadata = writer.getDefaultImageMetadata(ImageTypeSpecifier.createFromRenderedImage(chatImage), writer.getDefaultWriteParam());
                IIOMetadataNode title = generateMetadataNode("Title", "CGF Screenshot");
                IIOMetadataNode software = generateMetadataNode("Software", "Chat Game Fontificator");
                final String fontGameName = ControlPanelFont.getFontGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_FONT));
                final String borderGameName = ControlPanelFont.getBorderGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_BORDER));
                IIOMetadataNode description = generateMetadataNode("Description", fontGameName + " Font / " + borderGameName + " Border");
                IIOMetadataNode text = new IIOMetadataNode("tEXt");
                text.appendChild(title);
                text.appendChild(software);
                text.appendChild(description);
                final String metadataFormatStr = "javax_imageio_png_1.0";
                IIOMetadataNode root = new IIOMetadataNode(metadataFormatStr);
                root.appendChild(text);
                metadata.mergeTree(metadataFormatStr, root);
                writer.write(metadata, new IIOImage(chatImage, null, metadata), writer.getDefaultWriteParam());
                stream.close();
            } else {
                ImageIO.write(chatImage, "png", saveFile);
            }
            return true;
        } catch (Exception e) {
            logger.error("Unable to save screenshot", e);
            return false;
        }
    }
    return false;
}
Also used : Color(java.awt.Color) ImageWriter(javax.imageio.ImageWriter) ChatPanel(com.glitchcog.fontificator.gui.chat.ChatPanel) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) IIOImage(javax.imageio.IIOImage) Graphics(java.awt.Graphics) IIOMetadata(javax.imageio.metadata.IIOMetadata) File(java.io.File) IIOMetadataNode(javax.imageio.metadata.IIOMetadataNode) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Aggregations

ImageWriter (javax.imageio.ImageWriter)171 ImageWriteParam (javax.imageio.ImageWriteParam)103 IIOImage (javax.imageio.IIOImage)92 ImageOutputStream (javax.imageio.stream.ImageOutputStream)85 BufferedImage (java.awt.image.BufferedImage)80 File (java.io.File)73 IOException (java.io.IOException)53 ByteArrayOutputStream (java.io.ByteArrayOutputStream)44 Test (org.junit.Test)37 IIOMetadata (javax.imageio.metadata.IIOMetadata)36 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)30 ParameterBlockJAI (javax.media.jai.ParameterBlockJAI)28 RenderedOp (javax.media.jai.RenderedOp)28 ImageReadParam (javax.imageio.ImageReadParam)26 Iterator (java.util.Iterator)25 ImageReader (javax.imageio.ImageReader)24 FileImageOutputStreamExtImpl (it.geosolutions.imageio.stream.output.FileImageOutputStreamExtImpl)20 ByteArrayInputStream (java.io.ByteArrayInputStream)20 Graphics2D (java.awt.Graphics2D)19 FileImageOutputStream (javax.imageio.stream.FileImageOutputStream)17