Search in sources :

Example 56 with ImageWriteParam

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

the class GeoTiffVrtTest method write.

/**
 * Test Writing capabilities.
 *
 * @throws FileNotFoundException
 * @throws IOException
 */
@Test
public void write() throws IOException, FileNotFoundException {
    if (!isGDALAvailable) {
        return;
    }
    final File outputFile = TestData.temp(this, "writetest.tif", false);
    outputFile.deleteOnExit();
    final File inputFile = TestData.file(this, "utmByte.tif.vrt");
    ImageReadParam rparam = new ImageReadParam();
    rparam.setSourceRegion(new Rectangle(1, 1, 300, 500));
    rparam.setSourceSubsampling(1, 2, 0, 0);
    ImageReader reader = new VRTImageReaderSpi().createReaderInstance();
    reader.setInput(inputFile);
    final IIOMetadata metadata = reader.getImageMetadata(0);
    final ParameterBlockJAI pbjImageRead = new ParameterBlockJAI("ImageRead");
    pbjImageRead.setParameter("Input", inputFile);
    pbjImageRead.setParameter("reader", reader);
    pbjImageRead.setParameter("readParam", rparam);
    final ImageLayout l = new ImageLayout();
    l.setTileGridXOffset(0).setTileGridYOffset(0).setTileHeight(256).setTileWidth(256);
    RenderedOp image = JAI.create("ImageRead", pbjImageRead, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, l));
    if (TestData.isInteractiveTest())
        Viewer.visualizeAllInformation(image, "geotiff");
    // ////////////////////////////////////////////////////////////////
    // preparing to write
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageWrite = new ParameterBlockJAI("ImageWrite");
    ImageWriter writer = new GeoTiffImageWriterSpi().createWriterInstance();
    pbjImageWrite.setParameter("Output", outputFile);
    pbjImageWrite.setParameter("writer", writer);
    pbjImageWrite.setParameter("ImageMetadata", metadata);
    pbjImageWrite.setParameter("Transcode", false);
    ImageWriteParam param = new ImageWriteParam(Locale.getDefault());
    param.setSourceRegion(new Rectangle(10, 10, 100, 100));
    param.setSourceSubsampling(2, 1, 0, 0);
    pbjImageWrite.setParameter("writeParam", param);
    pbjImageWrite.addSource(image);
    final RenderedOp op = JAI.create("ImageWrite", pbjImageWrite);
    final ImageWriter writer2 = (ImageWriter) op.getProperty(ImageWriteDescriptor.PROPERTY_NAME_IMAGE_WRITER);
    writer2.dispose();
    // ////////////////////////////////////////////////////////////////
    // preparing to read again
    // ////////////////////////////////////////////////////////////////
    final ParameterBlockJAI pbjImageReRead = new ParameterBlockJAI("ImageRead");
    pbjImageReRead.setParameter("Input", outputFile);
    pbjImageReRead.setParameter("Reader", new GeoTiffImageReaderSpi().createReaderInstance());
    final RenderedOp image2 = JAI.create("ImageRead", pbjImageReRead);
    if (TestData.isInteractiveTest())
        Viewer.visualizeAllInformation(image2, "geotif2");
    else
        Assert.assertNotNull(image2.getTiles());
}
Also used : ParameterBlockJAI(javax.media.jai.ParameterBlockJAI) ImageWriter(javax.imageio.ImageWriter) ImageWriteParam(javax.imageio.ImageWriteParam) GeoTiffImageReaderSpi(it.geosolutions.imageio.plugins.geotiff.GeoTiffImageReaderSpi) IIOMetadata(javax.imageio.metadata.IIOMetadata) ImageReadParam(javax.imageio.ImageReadParam) RenderedOp(javax.media.jai.RenderedOp) GeoTiffImageWriterSpi(it.geosolutions.imageio.plugins.geotiff.GeoTiffImageWriterSpi) ImageReader(javax.imageio.ImageReader) File(java.io.File) ImageLayout(javax.media.jai.ImageLayout) AbstractGDALTest(it.geosolutions.imageio.gdalframework.AbstractGDALTest) Test(org.junit.Test)

Example 57 with ImageWriteParam

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

the class CustomByteIndexImageTypesTest method testCustomIndexedImage.

@Test
public void testCustomIndexedImage() throws Exception {
    byte[] colors = new byte[ncolors];
    for (int i = 0; i < ncolors; i++) {
        colors[i] = (byte) i;
    }
    int nbits;
    if (ncolors <= 2) {
        nbits = 1;
    } else {
        nbits = (int) Math.ceil(Math.log(ncolors) / Math.log(2));
        if ((nbits & (nbits - 1)) != 0) {
            int nextPower = (int) (Math.floor(Math.log(nbits) / Math.log(2)) + 1);
            nbits = (int) Math.pow(2, nextPower);
        }
    }
    IndexColorModel icm = new IndexColorModel(nbits, ncolors, colors, colors, colors);
    SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, size, size, nbits);
    int pixelsPerByte = 8 / nbits;
    int bytesPerRow = (int) Math.max(1, Math.ceil(1d * size / pixelsPerByte));
    int bytes = bytesPerRow * size;
    DataBufferByte dataBuffer = new DataBufferByte(bytes);
    WritableRaster wr = (WritableRaster) Raster.createWritableRaster(sm, dataBuffer, new Point(0, 0));
    BufferedImage bi = new BufferedImage(icm, wr, false, null);
    Graphics2D graphics = bi.createGraphics();
    graphics.setColor(Color.BLACK);
    graphics.fillRect(0, 0, 16, 32);
    graphics.setColor(Color.WHITE);
    graphics.fillRect(16, 0, 16, 32);
    graphics.dispose();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    float quality = 5f / 9 - 1;
    new PNGWriter().writePNG(bi, bos, -quality, FilterType.FILTER_NONE);
    BufferedImage read = ImageIO.read(new ByteArrayInputStream(bos.toByteArray()));
    ImageAssert.assertImagesEqual(bi, read);
    // now using imagewriter interface
    ImageWriter writer = new PNGImageWriterSPI().createWriterInstance();
    writer.setOutput(bos);
    ImageWriteParam wp = writer.getDefaultWriteParam();
    wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    wp.setCompressionQuality(-quality);
    writer.write(null, new IIOImage(bi, null, null), wp);
    writer.dispose();
    ImageAssert.assertImagesEqual(bi, ImageIO.read(new ByteArrayInputStream(bos.toByteArray())));
}
Also used : PNGImageWriterSPI(it.geosolutions.imageio.plugins.png.PNGImageWriterSPI) ImageWriter(javax.imageio.ImageWriter) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) Point(java.awt.Point) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataBufferByte(java.awt.image.DataBufferByte) ImageWriteParam(javax.imageio.ImageWriteParam) Point(java.awt.Point) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage) SampleModel(java.awt.image.SampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) ByteArrayInputStream(java.io.ByteArrayInputStream) WritableRaster(java.awt.image.WritableRaster) PNGWriter(it.geosolutions.imageio.plugins.png.PNGWriter) IndexColorModel(java.awt.image.IndexColorModel) Test(org.junit.Test)

Example 58 with ImageWriteParam

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

the class BufferedImageChildTest method testSubImage.

private void testSubImage(int x, int y, int w, int h) throws Exception {
    BufferedImage bi = getSample();
    // ImageAssert.showImage("Original", 2000, bi);
    BufferedImage subimage = bi.getSubimage(x, y, w, h);
    // ImageAssert.showImage("Subimage", 2000, subimage);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    float quality = 4f / 9 - 1;
    new PNGWriter().writePNG(subimage, bos, -quality, FilterType.FILTER_NONE);
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    BufferedImage readBack = ImageIO.read(bis);
    // ImageAssert.showImage("ReadBack", 2000, readBack);
    ImageAssert.assertImagesEqual(subimage, readBack);
    // now using imagewriter interface
    ImageWriter writer = new PNGImageWriterSPI().createWriterInstance();
    writer.setOutput(bos);
    ImageWriteParam wp = writer.getDefaultWriteParam();
    wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    wp.setCompressionQuality(-quality);
    writer.write(null, new IIOImage(subimage, null, null), wp);
    writer.dispose();
    bis = new ByteArrayInputStream(bos.toByteArray());
    readBack = ImageIO.read(bis);
    // ImageAssert.showImage("ReadBack", 2000, readBack);
    ImageAssert.assertImagesEqual(subimage, readBack);
}
Also used : PNGImageWriterSPI(it.geosolutions.imageio.plugins.png.PNGImageWriterSPI) ByteArrayInputStream(java.io.ByteArrayInputStream) PNGImageWriter(it.geosolutions.imageio.plugins.png.PNGImageWriter) ImageWriter(javax.imageio.ImageWriter) PNGWriter(it.geosolutions.imageio.plugins.png.PNGWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) BufferedImage(java.awt.image.BufferedImage) IIOImage(javax.imageio.IIOImage)

Example 59 with ImageWriteParam

use of javax.imageio.ImageWriteParam 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 60 with ImageWriteParam

use of javax.imageio.ImageWriteParam in project nutz by nutzam.

the class Images method writeJpeg.

/**
 * 写入一个 JPG 图像
 *
 * @param im
 *            图像对象
 * @param targetJpg
 *            目标输出 JPG 图像文件
 * @param quality
 *            质量 0.1f ~ 1.0f
 */
public static void writeJpeg(RenderedImage im, Object targetJpg, float quality) {
    ImageWriter writer = null;
    try {
        writer = ImageIO.getImageWritersBySuffix("jpg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        ImageOutputStream os = ImageIO.createImageOutputStream(targetJpg);
        writer.setOutput(os);
        writer.write((IIOMetadata) null, new IIOImage(im, null, null), param);
        os.flush();
        os.close();
    } catch (IOException e) {
        throw Lang.wrapThrow(e);
    } finally {
        if (writer != null) {
            try {
                writer.dispose();
            } catch (Throwable e) {
            }
        }
    }
}
Also used : ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IIOImage(javax.imageio.IIOImage)

Aggregations

ImageWriteParam (javax.imageio.ImageWriteParam)120 ImageWriter (javax.imageio.ImageWriter)100 IIOImage (javax.imageio.IIOImage)74 ImageOutputStream (javax.imageio.stream.ImageOutputStream)53 BufferedImage (java.awt.image.BufferedImage)51 File (java.io.File)51 IOException (java.io.IOException)38 Test (org.junit.Test)33 ByteArrayOutputStream (java.io.ByteArrayOutputStream)28 ImageReadParam (javax.imageio.ImageReadParam)24 ParameterBlockJAI (javax.media.jai.ParameterBlockJAI)23 RenderedOp (javax.media.jai.RenderedOp)23 IIOMetadata (javax.imageio.metadata.IIOMetadata)22 FileImageOutputStreamExtImpl (it.geosolutions.imageio.stream.output.FileImageOutputStreamExtImpl)20 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)18 ByteArrayInputStream (java.io.ByteArrayInputStream)17 Graphics2D (java.awt.Graphics2D)12 JPEGImageWriteParam (javax.imageio.plugins.jpeg.JPEGImageWriteParam)12 FileImageOutputStream (javax.imageio.stream.FileImageOutputStream)12 MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)12