Search in sources :

Example 46 with ImageWriter

use of javax.imageio.ImageWriter in project TrakEM2 by trakem2.

the class ImageSaver method saveAsJpeg.

/**
 * Will not flush the given BufferedImage.
 */
public static final boolean saveAsJpeg(final BufferedImage bi, final String path, float quality, boolean as_grey) {
    if (!checkPath(path))
        return false;
    if (quality < 0f)
        quality = 0f;
    if (quality > 1f)
        quality = 1f;
    synchronized (getPathLock(path)) {
        ImageOutputStream ios = null;
        ImageWriter writer = null;
        BufferedImage grey = bi;
        try {
            writer = ImageIO.getImageWritersByFormatName("jpeg").next();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream(estimateJPEGFileSize(bi.getWidth(), bi.getHeight()));
            ios = ImageIO.createImageOutputStream(baos);
            writer.setOutput(ios);
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);
            if (as_grey && bi.getType() != BufferedImage.TYPE_BYTE_GRAY) {
                grey = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
                // convert the original colored image to grayscale
                // Very slow:
                // ColorConvertOp op = new ColorConvertOp(bi.getColorModel().getColorSpace(), grey.getColorModel().getColorSpace(), null);
                // op.filter(bi, grey);
                // 9 times faster:
                grey.createGraphics().drawImage(bi, 0, 0, null);
            }
            IIOImage iioImage = new IIOImage(grey, null, null);
            writer.write(null, iioImage, param);
            // Now write to disk
            FileChannel ch = null;
            try {
                // Now write to disk in the fastest way possible
                final RandomAccessFile ra = new RandomAccessFile(new File(path), "rw");
                final ByteBuffer bb = ByteBuffer.wrap((byte[]) Bbuf.get(baos), 0, baos.size());
                ch = ra.getChannel();
                while (bb.hasRemaining()) {
                    ch.write(bb);
                }
            } finally {
                if (null != ch)
                    ch.close();
                ios.close();
            }
        } catch (Exception e) {
            IJError.print(e);
            return false;
        } finally {
            if (null != writer)
                try {
                    writer.dispose();
                } catch (Exception ee) {
                }
            // if (null != ios) try { ios.close(); } catch (Exception ee) {} // NOT NEEDED, it's a ByteArrayOutputStream
            if (bi != grey)
                try {
                    grey.flush();
                /*release native resources*/
                } catch (Exception ee) {
                }
            removePathLock(path);
        }
    }
    return true;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileChannel(java.nio.channels.FileChannel) ImageWriter(javax.imageio.ImageWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ByteBuffer(java.nio.ByteBuffer) ImageOutputStream(javax.imageio.stream.ImageOutputStream) BufferedImage(java.awt.image.BufferedImage) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) IIOImage(javax.imageio.IIOImage)

Example 47 with ImageWriter

use of javax.imageio.ImageWriter in project dataverse by IQSS.

the class ImageThumbConverter method rescaleImage.

private static void rescaleImage(BufferedImage fullSizeImage, int width, int height, int size, OutputStream outputStream) throws IOException {
    double scaleFactor = 0.0;
    int thumbHeight = size;
    int thumbWidth = size;
    if (width > height) {
        scaleFactor = ((double) size) / (double) width;
        thumbHeight = (int) (height * scaleFactor);
    } else {
        scaleFactor = ((double) size) / (double) height;
        thumbWidth = (int) (width * scaleFactor);
    }
    logger.fine("scale factor: " + scaleFactor);
    logger.fine("thumbnail dimensions: " + thumbWidth + "x" + thumbHeight);
    // If we are willing to spend a few extra CPU cycles to generate
    // better-looking thumbnails, we can the SCALE_SMOOTH flag.
    // SCALE_FAST trades quality for speed.
    // logger.fine("Start image rescaling ("+size+" pixels), SCALE_FAST used;");
    Image thumbImage = fullSizeImage.getScaledInstance(thumbWidth, thumbHeight, java.awt.Image.SCALE_FAST);
    // logger.fine("Finished image rescaling.");
    // if transparency is defined, we should preserve it in the png:
    /*   
         OK, turns out *nothing* special needs to be done in order to preserve
         the transparency; the transparency is already there, because ImageIO.read()
         creates a BufferedImage with the color type BufferedImage.TYPE_INT_ARGB;
         all we need to do, is to create the output BufferedImage lowRes, 
         below, with this same color type. The transparency was getting lost 
         only because that BufferedImage was made with TYPE_INT_RGB, thus
         stripping the transparency off.
            
         BufferedImage bufferedImageForTransparency = new BufferedImage(thumbWidth, thumbgetHeight, BufferedImage.TYPE_INT_ARGB);
         Graphics2D g2 = bufferedImageForTransparency.createGraphics();
         g2.drawImage(thumbImage, 0, 0, null);
         g2.dispose();
            
         int color = bufferedImageForTransparency.getRGB(0, 0);
            
         logger.info("color we'll be using for transparency: "+color);
            
         thumbImage = makeColorTransparent(bufferedImageForTransparency, new Color(color));
         */
    ImageWriter writer = null;
    Iterator iter = ImageIO.getImageWritersByFormatName("png");
    if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
    } else {
        throw new IOException("Failed to locatie ImageWriter plugin for image type PNG");
    }
    BufferedImage lowRes = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = lowRes.createGraphics();
    g2.drawImage(thumbImage, 0, 0, null);
    g2.dispose();
    try {
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
        writer.setOutput(ios);
        // finally, save thumbnail image:
        writer.write(lowRes);
        writer.dispose();
        ios.close();
        thumbImage.flush();
        // fullSizeImage.flush();
        lowRes.flush();
    } catch (Exception ex) {
        logger.warning("Caught exception trying to generate thumbnail: " + ex.getMessage());
        throw new IOException("Caught exception trying to generate thumbnail: " + ex.getMessage());
    }
}
Also used : ImageWriter(javax.imageio.ImageWriter) Iterator(java.util.Iterator) IOException(java.io.IOException) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Graphics2D(java.awt.Graphics2D)

Example 48 with ImageWriter

use of javax.imageio.ImageWriter in project skin-composer by raeleus.

the class TexturePacker method writeImages.

private void writeImages(File outputDir, String scaledPackFileName, Array<Page> pages) {
    File packFileNoExt = new File(outputDir, scaledPackFileName);
    File packDir = packFileNoExt.getParentFile();
    String imageName = packFileNoExt.getName();
    int fileIndex = 0;
    for (Page page : pages) {
        int width = page.width, height = page.height;
        int paddingX = settings.paddingX;
        int paddingY = settings.paddingY;
        if (settings.duplicatePadding) {
            paddingX /= 2;
            paddingY /= 2;
        }
        width -= settings.paddingX;
        height -= settings.paddingY;
        if (settings.edgePadding) {
            page.x = paddingX;
            page.y = paddingY;
            width += paddingX * 2;
            height += paddingY * 2;
        }
        if (settings.pot) {
            width = MathUtils.nextPowerOfTwo(width);
            height = MathUtils.nextPowerOfTwo(height);
        }
        width = Math.max(settings.minWidth, width);
        height = Math.max(settings.minHeight, height);
        page.imageWidth = width;
        page.imageHeight = height;
        File outputFile;
        while (true) {
            outputFile = new File(packDir, imageName + (fileIndex++ == 0 ? "" : fileIndex) + "." + settings.outputFormat);
            if (!outputFile.exists())
                break;
        }
        new FileHandle(outputFile).parent().mkdirs();
        page.imageName = outputFile.getName();
        BufferedImage canvas = new BufferedImage(width, height, getBufferedImageType(settings.format));
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        if (!settings.silent)
            System.out.println("Writing " + canvas.getWidth() + "x" + canvas.getHeight() + ": " + outputFile);
        for (Rect rect : page.outputRects) {
            BufferedImage image = rect.getImage(imageProcessor);
            int iw = image.getWidth();
            int ih = image.getHeight();
            int rectX = page.x + rect.x, rectY = page.y + page.height - rect.y - rect.height;
            if (settings.duplicatePadding) {
                int amountX = settings.paddingX / 2;
                int amountY = settings.paddingY / 2;
                if (rect.rotated) {
                    // Copy corner pixels to fill corners of the padding.
                    for (int i = 1; i <= amountX; i++) {
                        for (int j = 1; j <= amountY; j++) {
                            plot(canvas, rectX - j, rectY + iw - 1 + i, image.getRGB(0, 0));
                            plot(canvas, rectX + ih - 1 + j, rectY + iw - 1 + i, image.getRGB(0, ih - 1));
                            plot(canvas, rectX - j, rectY - i, image.getRGB(iw - 1, 0));
                            plot(canvas, rectX + ih - 1 + j, rectY - i, image.getRGB(iw - 1, ih - 1));
                        }
                    }
                    // Copy edge pixels into padding.
                    for (int i = 1; i <= amountY; i++) {
                        for (int j = 0; j < iw; j++) {
                            plot(canvas, rectX - i, rectY + iw - 1 - j, image.getRGB(j, 0));
                            plot(canvas, rectX + ih - 1 + i, rectY + iw - 1 - j, image.getRGB(j, ih - 1));
                        }
                    }
                    for (int i = 1; i <= amountX; i++) {
                        for (int j = 0; j < ih; j++) {
                            plot(canvas, rectX + j, rectY - i, image.getRGB(iw - 1, j));
                            plot(canvas, rectX + j, rectY + iw - 1 + i, image.getRGB(0, j));
                        }
                    }
                } else {
                    // Copy corner pixels to fill corners of the padding.
                    for (int i = 1; i <= amountX; i++) {
                        for (int j = 1; j <= amountY; j++) {
                            plot(canvas, rectX - i, rectY - j, image.getRGB(0, 0));
                            plot(canvas, rectX - i, rectY + ih - 1 + j, image.getRGB(0, ih - 1));
                            plot(canvas, rectX + iw - 1 + i, rectY - j, image.getRGB(iw - 1, 0));
                            plot(canvas, rectX + iw - 1 + i, rectY + ih - 1 + j, image.getRGB(iw - 1, ih - 1));
                        }
                    }
                    // Copy edge pixels into padding.
                    for (int i = 1; i <= amountY; i++) {
                        copy(image, 0, 0, iw, 1, canvas, rectX, rectY - i, rect.rotated);
                        copy(image, 0, ih - 1, iw, 1, canvas, rectX, rectY + ih - 1 + i, rect.rotated);
                    }
                    for (int i = 1; i <= amountX; i++) {
                        copy(image, 0, 0, 1, ih, canvas, rectX - i, rectY, rect.rotated);
                        copy(image, iw - 1, 0, 1, ih, canvas, rectX + iw - 1 + i, rectY, rect.rotated);
                    }
                }
            }
            copy(image, 0, 0, iw, ih, canvas, rectX, rectY, rect.rotated);
            if (settings.debug) {
                g.setColor(Color.magenta);
                g.drawRect(rectX, rectY, rect.width - settings.paddingX - 1, rect.height - settings.paddingY - 1);
            }
        }
        if (settings.bleed && !settings.premultiplyAlpha && !(settings.outputFormat.equalsIgnoreCase("jpg") || settings.outputFormat.equalsIgnoreCase("jpeg"))) {
            canvas = new ColorBleedEffect().processImage(canvas, settings.bleedIterations);
            g = (Graphics2D) canvas.getGraphics();
        }
        if (settings.debug) {
            g.setColor(Color.magenta);
            g.drawRect(0, 0, width - 1, height - 1);
        }
        ImageOutputStream ios = null;
        try {
            if (settings.outputFormat.equalsIgnoreCase("jpg") || settings.outputFormat.equalsIgnoreCase("jpeg")) {
                BufferedImage newImage = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
                newImage.getGraphics().drawImage(canvas, 0, 0, null);
                canvas = newImage;
                Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
                ImageWriter writer = writers.next();
                ImageWriteParam param = writer.getDefaultWriteParam();
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(settings.jpegQuality);
                ios = ImageIO.createImageOutputStream(outputFile);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(canvas, null, null), param);
            } else {
                if (settings.premultiplyAlpha)
                    canvas.getColorModel().coerceData(canvas.getRaster(), true);
                ImageIO.write(canvas, "png", outputFile);
            }
        } catch (IOException ex) {
            throw new RuntimeException("Error writing file: " + outputFile, ex);
        } finally {
            if (ios != null) {
                try {
                    ios.close();
                } catch (Exception ignored) {
                }
            }
        }
    }
}
Also used : FileHandle(com.badlogic.gdx.files.FileHandle) ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) BufferedImage(java.awt.image.BufferedImage) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) IOException(java.io.IOException) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 49 with ImageWriter

use of javax.imageio.ImageWriter in project basicv2 by EgonOlsen71.

the class Graphics method savePng.

/**
 * Saves an image as PNG file.
 *
 * @param bi
 *            the image
 * @param os
 *            the output stream. It will be closed when this method
 *            terminates.
 */
public static void savePng(BufferedImage bi, OutputStream os) {
    try (BufferedOutputStream bos = new BufferedOutputStream(os);
        ImageOutputStream ios = ImageIO.createImageOutputStream(bos)) {
        Iterator<ImageWriter> itty = ImageIO.getImageWritersBySuffix("png");
        if (itty.hasNext()) {
            ImageWriter iw = (ImageWriter) itty.next();
            ImageWriteParam iwp = iw.getDefaultWriteParam();
            iw.setOutput(ios);
            iw.write(null, new IIOImage((RenderedImage) bi, null, null), iwp);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ImageWriter(javax.imageio.ImageWriter) ImageWriteParam(javax.imageio.ImageWriteParam) RenderedImage(java.awt.image.RenderedImage) BufferedOutputStream(java.io.BufferedOutputStream) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IIOImage(javax.imageio.IIOImage)

Example 50 with ImageWriter

use of javax.imageio.ImageWriter in project chordatlas by twak.

the class Mosaic method tile.

public int tile(String s, File result) {
    Matcher m = p.matcher(s);
    if (m.matches()) {
        String panoid = m.group(1);
        BufferedImage mosaic = new BufferedImage(26 * 512, 13 * 512, BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = mosaic.getGraphics();
        for (int x = 0; x <= 25; x++) for (int y = 0; y <= 12; y++) {
            URL url;
            try {
                url = new URL("http://cbk0.google.com/cbk?output=tile&panoid=" + panoid + "&zoom=5&x=" + x + "&y=" + y);
                g.drawImage(ImageIO.read(url), x * 512, y * 512, null);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
        g.dispose();
        try {
            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            // Needed see javadoc
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            // Highest quality
            param.setCompressionQuality(1f);
            ImageOutputStream ios = ImageIO.createImageOutputStream(new File(result, s + ".jpg"));
            writer.setOutput(ios);
            writer.write(mosaic);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return 1;
}
Also used : Graphics(java.awt.Graphics) Matcher(java.util.regex.Matcher) ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) IIOException(javax.imageio.IIOException) ImageWriteParam(javax.imageio.ImageWriteParam) File(java.io.File) BufferedImage(java.awt.image.BufferedImage) URL(java.net.URL) 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