Example usage for javax.imageio ImageWriter write

List of usage examples for javax.imageio ImageWriter write

Introduction

In this page you can find the example usage for javax.imageio ImageWriter write.

Prototype

public abstract void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param)
        throws IOException;

Source Link

Document

Appends a complete image stream containing a single image and associated stream and image metadata and thumbnails to the output.

Usage

From source file:net.intelliant.util.UtilCommon.java

private static String generateCompressedImageForInputFile(String locationInFileSystem, String srcFileName)
        throws NoSuchAlgorithmException, IOException {
    String outputFileName = srcFileName;
    File srcFile = new File(locationInFileSystem, srcFileName);
    File compressedFile = null;//from   w  w w .  ja  va 2  s .com
    FileImageOutputStream outputStream = null;
    try {
        if (srcFile.exists()) {
            String md5sum = getMD5SumForFile(srcFile.getAbsolutePath());
            int extentionIndex = srcFileName.lastIndexOf("."); // find index of extension.
            if (extentionIndex != -1) {
                outputFileName = outputFileName.replaceFirst("\\.", "_" + md5sum + ".");
            }
            compressedFile = new File(locationInFileSystem, outputFileName);
            if (Debug.infoOn()) {
                Debug.logInfo("[generateCompressedImageFor] sourceFile >> " + srcFile.getAbsolutePath(),
                        module);
                Debug.logInfo("[generateCompressedImageFor] md5sum >> " + md5sum, module);
                Debug.logInfo(
                        "[generateCompressedImageFor] compressedFile >> " + compressedFile.getAbsolutePath(),
                        module);
            }
            if (!compressedFile.exists()) {
                if (Debug.infoOn()) {
                    Debug.logInfo("[generateCompressedImageFor] compressed file does NOT exist..", module);
                }
                Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
                ImageWriter imageWriter = (ImageWriter) iter.next();
                ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(Float.parseFloat(imageCompressionQuality)); // an integer between 0 and 1, 1 specifies minimum compression and maximum quality
                BufferedImage bufferedImage = ImageIO.read(srcFile);
                outputStream = new FileImageOutputStream(compressedFile);
                imageWriter.setOutput(outputStream);
                IIOImage image = new IIOImage(bufferedImage, null, null);
                imageWriter.write(null, image, iwp);
            } else {
                if (Debug.infoOn()) {
                    Debug.logInfo(
                            "[generateCompressedImageFor] compressed file exists, not compressing again..",
                            module);
                }
            }
        } else {
            Debug.logWarning(String.format("Source image file does NOT exist..", srcFile), module);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
            outputStream = null;
        }
    }
    return outputFileName;
}

From source file:com.oneis.utils.ImageColouring.java

/**
 * Transform the colours in an image.//www  .  j  a  v  a2s  .com
 *
 * @param Filename Full pathname to the source file
 * @param Method Which colouring method to use, use METHOD_* constants
 * @param Colours Array of 0xRRGGBB colours for recolouring
 * @param JPEGQuality If the image is a JPEG, the output quality for
 * reencoding
 * @param Output An OutputStream to write the file. Will be closed.
 */
static public void colourImage(String Filename, int Method, int[] Colours, int JPEGQuality, OutputStream Output)
        throws IOException {
    ColouringInfo colouringInfo = prepareForColouring(Method, Colours);

    String extension = Filename.substring(Filename.lastIndexOf('.') + 1, Filename.length());
    String outputFormat = extension;

    if (outputFormat.equals("gif")) {
        if (!colourImageGIF(Filename, colouringInfo, Output)) {
            throw new RuntimeException("Failed to directly colour GIF file");
        }
        return;
    }

    BufferedImage image = ImageIO.read(new File(Filename));
    int width = image.getWidth();
    int height = image.getHeight();

    // Rewrite the pixels
    int[] pixelBuffer = new int[width];
    for (int y = 0; y < height; ++y) {
        image.getRGB(0, y, width, 1, pixelBuffer, 0, width);
        doColouring(pixelBuffer, colouringInfo);
        image.setRGB(0, y, width, 1, pixelBuffer, 0, width);
    }

    // Writing is done the hard way to enable the JPEG quality to be set.
    // Get a writer
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(outputFormat);
    if (!iter.hasNext()) {
        throw new RuntimeException("Couldn't write image of type " + outputFormat);
    }

    ImageWriter writer = iter.next();

    ImageWriteParam iwparam = null;

    // Is it JPEG? If so, might want to set the quality
    if (outputFormat.equals("jpeg") || outputFormat.equals("jpg")) {
        // Clamp value
        int q = JPEGQuality;
        if (q < 10) {
            q = 10;
        }
        if (q > 100) {
            q = 100;
        }

        JPEGImageWriteParam jparam = new JPEGImageWriteParam(null);
        jparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jparam.setCompressionQuality((float) (((float) q) / 100.0));
        iwparam = jparam;
    }

    ImageOutputStream output = ImageIO.createImageOutputStream(Output);
    writer.setOutput(output);
    writer.write(null, new IIOImage(image, null, null), iwparam);

    output.close();
}

From source file:de.jwic.ecolib.controls.chart.ChartControl.java

public void renderImage() throws IOException {
    // create image to draw into
    BufferedImage bi = new BufferedImage(width < 10 ? 10 : width, height < 10 ? 10 : height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    if (chart != null) {
        chart.setBackgroundPaint(Color.WHITE);
        chart.draw(g2d, new Rectangle2D.Double(0, 0, width < 10 ? 10 : width, height < 10 ? 10 : height));
    } else {//ww  w.  ja v  a2s. c o  m
        g2d.setColor(Color.BLACK);
        g2d.drawString("No chart has been assigned.", 1, 20);
    }
    // finish drawing
    g2d.dispose();

    // write image data into output stream
    ByteArrayOutputStream out = getImageOutputStream();
    out.reset();
    // create a PNG image
    ImageWriter imageWriter = new PNGImageWriter(null);
    ImageWriteParam param = imageWriter.getDefaultWriteParam();
    imageWriter.setOutput(new MemoryCacheImageOutputStream(out));
    imageWriter.write(null, new IIOImage(bi, null, null), param);
    imageWriter.dispose();

    setMimeType(MIME_TYPE_PNG);
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi, OutputStream out)
        throws IOException {
    // encode to JPEG
    ImageOutputStream ios = null;
    ImageWriter imageWriter = null;
    try {/*  w  ww.j a v  a 2 s  . c  o m*/
        // find JAI writer
        imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
        ios = ImageIO.createImageOutputStream(out);
        imageWriter.setOutput(ios);

        // add compression
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(quality);

        // add metadata
        ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
        IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam);
        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"); // 1 = dots/inch

        // write
        imageWriter.write(data, new IIOImage(image, null, null), jpegParam);
    } finally {
        // clean up
        IOUtils.closeQuietly(out);
        if (ios != null) {
            ios.close();
        }
        if (imageWriter != null) {
            imageWriter.dispose();
        }
    }
}

From source file:net.rptools.tokentool.AppActions.java

public static void saveToken(File rptok_file, boolean overwrite) {
    if (rptok_file != null) {
        if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) {
            rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok");
        }//from  www  . j  ava  2 s.c  o m

        if (rptok_file.exists() && !overwrite) {
            if (!TokenTool.confirm("File exists.  Overwrite?")) {
                return;
            } else {
                rptok_file.delete();
            }
        }

        String tokenName = FilenameUtils.removeExtension(rptok_file.getName());

        try {
            // Write out the token image first or aka POG image.
            File tokenImageFile = File.createTempFile("tokenImage", ".png");

            // PW: This code addes the pHYs chunk to the
            // output png file with X & Y dpi set.
            BufferedImage tokenImg = TokenTool.getFrame().getComposedToken();
            BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage();

            ImageWriter writer = getImageWriterBySuffix("png");
            // Created object for outputStream so we can properly close it! No longer locks .png files until app closes!
            ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile);
            writer.setOutput(ios);
            ImageWriteParam param = writer.getDefaultWriteParam();

            PNGMetadata png = new PNGMetadata();
            // 39.375 inches per meter
            // I'm using the image width for the DPI under
            // the assumption that the token fits within
            // one cell.
            int resX = (int) (tokenImg.getWidth() * 39.375f);
            png.pHYs_pixelsPerUnitXAxis = resX;
            png.pHYs_pixelsPerUnitYAxis = resX;
            png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown"
            png.pHYs_present = true;

            writer.write(null, new IIOImage(tokenImg, null, png), param);
            ios.close();

            // Now write out the Portrait image, here we'll use JPEG to save space
            File portraitImageFile = File.createTempFile("portraitImage", ".jpg");
            writer.reset();
            writer = getImageWriterBySuffix("jpg");
            ios = ImageIO.createImageOutputStream(portraitImageFile);
            writer.setOutput(ios);
            param = writer.getDefaultWriteParam();

            writer.write(null, new IIOImage(portraitImg, null, null), param);
            writer.dispose();
            ios.close();

            // Lets create the token!
            Token _token = new Token();
            Asset tokenImage = null;
            tokenImage = AssetManager.createAsset(tokenImageFile);
            AssetManager.putAsset(tokenImage);
            _token = new Token(tokenName, tokenImage.getId());
            _token.setGMName(tokenName);

            // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool
            //_token.setImageAsset(tokenImage.getName());
            //_token.setImageAsset(tokenImage.getName(), tokenImage.getId());

            // set the image shape
            Image image = ImageIO.read(tokenImageFile);
            _token.setShape(TokenUtil.guessTokenType(image));

            // set the height/width, fixes dragging to stamp layer issue
            _token.setHeight(tokenImg.getHeight());
            _token.setWidth(tokenImg.getWidth());

            // set the portrait image asset
            Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait
            AssetManager.putAsset(portrait);
            _token.setPortraitImage(portrait.getId());

            // Time to write out the .rptok token file...
            PackedFile pakFile = null;
            try {
                pakFile = new PackedFile(rptok_file);
                saveAssets(_token.getAllImageAssets(), pakFile);
                pakFile.setContent(_token);
                BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null);
                pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png"));
                pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION);
                pakFile.save();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (pakFile != null)
                    pakFile.close();
                tokenImageFile.delete();
                portraitImageFile.delete();
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
            TokenTool.showError("Unable to write image: " + ioe);
        }
    }
}

From source file:org.shredzone.cilla.service.resource.ImageProcessorImpl.java

/**
 * Writes a JPEG file with adjustable compression quality.
 *
 * @param image//  w  w w .  j a va  2  s . co m
 *            {@link BufferedImage} to write
 * @param out
 *            {@link ImageOutputStream} to write to
 * @param quality
 *            Compression quality between 0.0f (worst) and 1.0f (best)
 */
private void jpegQualityWriter(BufferedImage image, ImageOutputStream out, float quality) throws IOException {
    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();

    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);

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

    writer.setOutput(out);
    writer.write(null, ioImage, iwp);
    writer.dispose();
}

From source file:org.deegree.securityproxy.wms.responsefilter.clipping.SimpleRasterClipper.java

private void writeImage(OutputStream destination, String format, BufferedImage outputImage)
        throws ClippingException, IOException {
    ImageWriter imageWriter = createImageWriter(format);
    ImageWriteParam writerParam = configureWriterParameters(format, imageWriter);
    imageWriter.setOutput(ImageIO.createImageOutputStream(destination));
    imageWriter.write(null, new IIOImage(outputImage, null, null), writerParam);
    imageWriter.dispose();//ww w. j  ava  2s .c  o m
}

From source file:doge.photo.DogePhotoManipulator.java

@Override
public Photo manipulate(Photo photo) throws IOException {
    BufferedImage sourceImage = readImage(photo);
    BufferedImage destinationImage = manipulate(sourceImage);
    Photo resultPhoto = () -> {//from   w  w  w  .  ja v a2s  .  c  o m
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.85f);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(destinationImage, null, null), param);
        ImageIO.write(destinationImage, "jpeg", outputStream);
        return new ByteArrayInputStream(outputStream.toByteArray());
    };
    return resultPhoto;
}

From source file:gr.iti.mklab.reveal.forensics.util.Util.java

public static BufferedImage recompressImage(BufferedImage imageIn, int quality) {
    // Apply in-memory JPEG compression to a BufferedImage given a quality setting (0-100)
    // and return the resulting BufferedImage
    float fQuality = (float) (quality / 100.0);
    BufferedImage outputImage = null;
    try {/*from  w w  w.  ja v  a  2s. c  o  m*/
        ImageWriter writer;
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
        writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(fQuality);
        byte[] imageInByte;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(baos);
            writer.setOutput(mcios);
            IIOImage tmpImage = new IIOImage(imageIn, null, null);
            writer.write(null, tmpImage, iwp);
            writer.dispose();
            baos.flush();
            imageInByte = baos.toByteArray();
        }
        InputStream in = new ByteArrayInputStream(imageInByte);
        outputImage = ImageIO.read(in);
    } catch (Exception ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    }
    return outputImage;
}

From source file:compressor.Compressor.java

void compress_images(String src, String dest) throws IOException {

    File f = null;//from ww  w  . java  2 s  .  c om
    String[] paths;

    try {
        // create new file
        f = new File(src);

        // array of files and directory
        paths = f.list();

        File file = new File(dest + "compressed");
        if (!file.exists()) {
            if (file.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }
        dest = dest + "compressed/";

        // for each name in the path array
        for (String path : paths) {
            // prints filename and directory name

            File input = new File(src + path);
            BufferedImage image = ImageIO.read(input);

            File compressedImageFile = new File(dest + path);
            OutputStream os = new FileOutputStream(compressedImageFile);

            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = (ImageWriter) writers.next();

            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            writer.setOutput(ios);

            ImageWriteParam param = writer.getDefaultWriteParam();

            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.05f);
            writer.write(null, new IIOImage(image, null, null), param);

            os.close();
            ios.close();
            writer.dispose();

        }
    } catch (Exception e) {
    }

}