Search in sources :

Example 26 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream in project screenbird by adamhub.

the class ImageUtil method markAndCompress.

/**
     * Adds a watermark to the image and compresses it.
     * @param imageSource
     * @param compressionQuality
     * @param mark
     * @param markImageSource 
     */
public static void markAndCompress(String imageSource, float compressionQuality, boolean mark, String markImageSource) {
    try {
        File fileImageSource = new File(imageSource);
        if (!fileImageSource.exists()) {
            throw new ImageDoesNotExistException("Mark Image doesn't exists: " + fileImageSource.getAbsolutePath());
        }
        BufferedImage bufferedImage = ImageIO.read(fileImageSource);
        if (mark) {
            addMark(bufferedImage, markImageSource, 1.0f, ImageUtil.MARK_LEFT_BOTTOM);
        }
        // Get a jpeg writer
        ImageWriter writer = null;
        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        }
        if (writer == null) {
            throw new IOException("Could not get JPEG writer");
        }
        // Prepare output file
        ImageOutputStream ios = ImageIO.createImageOutputStream(fileImageSource);
        if (ios == null) {
            throw new IOException("Could not open image stream to write image watermark");
        }
        writer.setOutput(ios);
        // Set the compression quality
        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (compressionQuality < 0.0F || compressionQuality > 1.0F) {
            compressionQuality = 1.0F;
        }
        iwparam.setCompressionQuality(compressionQuality);
        // Write the image
        writer.write(null, new IIOImage(bufferedImage, null, null), iwparam);
        // Cleanup
        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IllegalArgumentException e) {
        log(e);
    } catch (IOException e) {
        log(e);
    } catch (ImageDoesNotExistException e) {
        log(e);
    }
}
Also used : ImageWriter(javax.imageio.ImageWriter) Iterator(java.util.Iterator) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) File(java.io.File) BufferedImage(java.awt.image.BufferedImage) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IIOImage(javax.imageio.IIOImage)

Example 27 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream 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)

Example 28 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream 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 29 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream in project jdk8u_jdk by JetBrains.

the class DataTransferer method imageToStandardBytesImpl.

protected byte[] imageToStandardBytesImpl(RenderedImage renderedImage, String mimeType) throws IOException {
    Iterator writerIterator = ImageIO.getImageWritersByMIMEType(mimeType);
    ImageTypeSpecifier typeSpecifier = new ImageTypeSpecifier(renderedImage);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOException ioe = null;
    while (writerIterator.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writerIterator.next();
        ImageWriterSpi writerSpi = imageWriter.getOriginatingProvider();
        if (!writerSpi.canEncodeImage(typeSpecifier)) {
            continue;
        }
        try {
            ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(baos);
            try {
                imageWriter.setOutput(imageOutputStream);
                imageWriter.write(renderedImage);
                imageOutputStream.flush();
            } finally {
                imageOutputStream.close();
            }
        } catch (IOException e) {
            imageWriter.dispose();
            baos.reset();
            ioe = e;
            continue;
        }
        imageWriter.dispose();
        baos.close();
        return baos.toByteArray();
    }
    baos.close();
    if (ioe == null) {
        ioe = new IOException("Registered service providers failed to encode " + renderedImage + " to " + mimeType);
    }
    throw ioe;
}
Also used : ImageWriterSpi(javax.imageio.spi.ImageWriterSpi) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 30 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream in project jmonkeyengine by jMonkeyEngine.

the class MjpegFileWriter method writeImageToBytes.

public byte[] writeImageToBytes(Image image, float quality) throws Exception {
    BufferedImage bi;
    if (image instanceof BufferedImage && ((BufferedImage) image).getType() == BufferedImage.TYPE_INT_RGB) {
        bi = (BufferedImage) image;
    } else {
        bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageWriter imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
    ImageOutputStream imgOutStrm = ImageIO.createImageOutputStream(baos);
    imgWrtr.setOutput(imgOutStrm);
    ImageWriteParam jpgWrtPrm = imgWrtr.getDefaultWriteParam();
    jpgWrtPrm.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    jpgWrtPrm.setCompressionQuality(quality);
    imgWrtr.write(null, new IIOImage(bi, null, null), jpgWrtPrm);
    imgOutStrm.close();
    return baos.toByteArray();
}
Also used : ImageWriter(javax.imageio.ImageWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) BufferedImage(java.awt.image.BufferedImage) ImageOutputStream(javax.imageio.stream.ImageOutputStream) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage)

Aggregations

ImageOutputStream (javax.imageio.stream.ImageOutputStream)56 ImageWriter (javax.imageio.ImageWriter)35 BufferedImage (java.awt.image.BufferedImage)33 IIOImage (javax.imageio.IIOImage)31 ByteArrayOutputStream (java.io.ByteArrayOutputStream)29 ImageWriteParam (javax.imageio.ImageWriteParam)24 File (java.io.File)23 IOException (java.io.IOException)21 IIOMetadata (javax.imageio.metadata.IIOMetadata)15 ByteArrayInputStream (java.io.ByteArrayInputStream)14 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)12 Iterator (java.util.Iterator)9 ImageInputStream (javax.imageio.stream.ImageInputStream)9 ImageReader (javax.imageio.ImageReader)7 MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)7 FileOutputStream (java.io.FileOutputStream)5 Graphics (java.awt.Graphics)4 Graphics2D (java.awt.Graphics2D)4 Color (java.awt.Color)3 IIOMetadataNode (javax.imageio.metadata.IIOMetadataNode)3