Example usage for javax.imageio IIOImage IIOImage

List of usage examples for javax.imageio IIOImage IIOImage

Introduction

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

Prototype

public IIOImage(Raster raster, List<? extends BufferedImage> thumbnails, IIOMetadata metadata) 

Source Link

Document

Constructs an IIOImage containing a Raster , and thumbnails and metadata associated with it.

Usage

From source file:net.groupbuy.util.ImageUtils.java

/**
 * ?/* w ww  .j  a  va2 s. com*/
 * 
 * @param srcFile
 *            ?
 * @param destFile
 *            
 * @param watermarkFile
 *            ?
 * @param watermarkPosition
 *            ??
 * @param alpha
 *            ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            FileUtils.copyFile(srcFile, destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(watermarkFile.getPath());
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.el.ecom.utils.ImageUtils.java

/**
 * ?/*  w ww . j  a va 2  s .  co  m*/
 * 
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);

    if (watermarkFile == null || !watermarkFile.exists() || !watermarkFile.isFile() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            if (!StringUtils.equals(srcFile.getCanonicalPath(), destFile.getCanonicalPath())) {
                FileUtils.copyFile(srcFile, destFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return;
    }
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            try {
                if (imageOutputStream != null) {
                    imageOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        try {
            operation.addImage(watermarkFile.getCanonicalPath());
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

/************************************************************************************
 * Write the renderedimage to an {@link OutputStream}
 * /*from ww  w . j  a  va 2 s  . com*/
 * @param outStream the {@link OutputStream} to write to
 ************************************************************************************/
@Override
public void writeToStream(FileOutputStream fos, OutputStream outStream) {
    if (this.renderedimage == null) { // no image available
        return;
    }
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        if (fos != null) {
            ImageOutputStream imageToFile = ImageIO.createImageOutputStream(fos);
            writer.setOutput(imageToFile);
            writer.prepareWriteSequence(null);
            writer.write(null, iioImage, writerParam);
            writer.endWriteSequence();
            imageToFile.flush();
            imageToFile.close();
            fos.flush();
            fos.close();
        }

        // ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // byte [] data = wi.getImageAsByteArray();

        writer.dispose();
        imageOutStream.close();

    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
}

From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

private byte[] getJPGBytes(BufferedImage image) {
    ByteArrayOutputStream outputStream = null;

    try {/*from w w w . ja  v a  2  s.  co m*/
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
        jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpgWriteParam.setCompressionQuality(1.0f);

        outputStream = new ByteArrayOutputStream();
        jpgWriter.setOutput(new MemoryCacheImageOutputStream((outputStream)));
        IIOImage outputImage = new IIOImage(image, null, null);

        jpgWriter.write(null, outputImage, jpgWriteParam);
        jpgWriter.dispose();
        outputStream.flush();

        return outputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        closeOutputStream(outputStream);
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

@Override
public byte[] writeToStreamAndByteArray(OutputStream outStream) {
    byte[] data = null;
    if (this.renderedimage == null) { // no image available
        return data;
    }//from  w  w w .  j a va2s . com
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageOutputStream imageToFile = ImageIO.createImageOutputStream(baos);
        writer.setOutput(imageToFile);
        writer.prepareWriteSequence(null);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageToFile.flush();
        imageToFile.close();
        baos.flush();
        data = baos.toByteArray();
        baos.close();
        writer.dispose();
        imageOutStream.close();
    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
    return data;
}

From source file:org.gallery.web.controller.ImageController.java

public static boolean compressImg(BufferedImage src, File outfile, double d) {
    FileOutputStream out = null;//  ww w  .j  a v a2 s .  c om
    ImageWriter imgWrier;
    ImageWriteParam imgWriteParams;

    // ? jpg
    imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
    imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
    // ??MODE_EXPLICIT
    imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
    // ?qality?0~1
    imgWriteParams.setCompressionQuality((float) d);
    imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
    ColorModel colorModel = ColorModel.getRGBdefault();
    // ?
    imgWriteParams.setDestinationType(
            new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));

    try {
        out = new FileOutputStream(outfile);
        imgWrier.reset();
        //  out?write, ImageOutputStream?
        // OutputStream
        imgWrier.setOutput(ImageIO.createImageOutputStream(out));
        // write???
        imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void saveJPG(BufferedImage img, File file) {
    ImageWriter writer = null;/*from   w w  w. jav  a2  s.  c om*/
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(1);
        output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage iioImage = new IIOImage(img, null, null);
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (writer != null) {
                writer.dispose();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:it.geosolutions.imageio.plugins.nitronitf.NITFImageWriter.java

/**
 * Encode a RenderedImage as a JP2K codestream on the specified outputFile, using the proper set of compression parameters.
 * /*from   ww w.  j a va 2  s .co m*/
 * @param outputFile
 * @param compression
 * @param ri
 * @throws FileNotFoundException
 * @throws IOException
 */
private void prepareJP2Image(final RenderedImage ri, final File outputFile, final WriteCompression compression)
        throws FileNotFoundException, IOException {
    JP2KKakaduImageWriter kakaduWriter = null;

    try {
        // TODO: Check PAN/MULTI can really be known from number of bands
        final int numBands = ri.getSampleModel().getNumBands();
        final boolean isMulti = numBands == 1 ? false : true;
        kakaduWriter = new JP2KKakaduImageWriter(KAKADU_SPI);
        kakaduWriter.setOutput(outputFile);
        JP2KKakaduImageWriteParam param = NITFUtilities.getCompressionParam(kakaduWriter, compression, isMulti);

        kakaduWriter.write(null, new IIOImage(ri, null, null), param);
    } finally {
        if (kakaduWriter != null) {
            try {
                kakaduWriter.dispose();
            } catch (Throwable t) {

            }
        }
    }
}