Search in sources :

Example 1 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream 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) {
    try {
        ImageWriter 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);
    }
}
Also used : ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IIOImage(javax.imageio.IIOImage)

Example 2 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream in project jforum2 by rafaelsteil.

the class ImageUtils method saveCompressedImage.

/**
	 * Compress and save an image to the disk. Currently this method only supports JPEG images.
	 * 
	 * @param image The image to save
	 * @param toFileName The filename to use
	 * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
	 * or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
	 */
public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
    try {
        if (type == IMAGE_PNG) {
            throw new UnsupportedOperationException("PNG compression not implemented");
        }
        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer;
        writer = (ImageWriter) iter.next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
        writer.setOutput(ios);
        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(0.7F);
        writer.write(null, new IIOImage(image, null, null), iwparam);
        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IOException e) {
        throw new ForumException(e);
    }
}
Also used : ForumException(net.jforum.exceptions.ForumException) Iterator(java.util.Iterator) ImageWriter(javax.imageio.ImageWriter) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream) IIOImage(javax.imageio.IIOImage)

Example 3 with ImageOutputStream

use of javax.imageio.stream.ImageOutputStream in project libgdx by libgdx.

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 4 with ImageOutputStream

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

the class CanWriteSequence method test.

private static void test(final ImageWriter writer) throws Exception {
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new FileOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    final IIOMetadata data = writer.getDefaultStreamMetadata(null);
    if (writer.canWriteSequence()) {
        writer.prepareWriteSequence(data);
    } else {
        try {
            writer.prepareWriteSequence(data);
            throw new RuntimeException("UnsupportedOperationException was not thrown");
        } catch (final UnsupportedOperationException ignored) {
        // expected
        }
    }
    writer.dispose();
    ios.close();
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 5 with ImageOutputStream

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

the class WriteAfterAbort method test.

private void test(final ImageWriter writer) throws IOException {
    // Image initialization
    final BufferedImage imageWrite = new BufferedImage(WIDTH, HEIGHT, TYPE_BYTE_BINARY);
    final Graphics2D g = imageWrite.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    g.dispose();
    // File initialization
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new SkipWriteOnAbortOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    writer.addIIOWriteProgressListener(this);
    // This write will be aborted, and file will not be touched
    writer.write(imageWrite);
    if (!isStartedCalled) {
        throw new RuntimeException("Started should be called");
    }
    if (!isProgressCalled) {
        throw new RuntimeException("Progress should be called");
    }
    if (!isAbortCalled) {
        throw new RuntimeException("Abort should be called");
    }
    if (isCompleteCalled) {
        throw new RuntimeException("Complete should not be called");
    }
    // Flush aborted data
    ios.flush();
    // This write should be completed successfully and the file should
    // contain correct image data.
    abortFlag = false;
    isAbortCalled = false;
    isCompleteCalled = false;
    isProgressCalled = false;
    isStartedCalled = false;
    writer.write(imageWrite);
    if (!isStartedCalled) {
        throw new RuntimeException("Started should be called");
    }
    if (!isProgressCalled) {
        throw new RuntimeException("Progress should be called");
    }
    if (isAbortCalled) {
        throw new RuntimeException("Abort should not be called");
    }
    if (!isCompleteCalled) {
        throw new RuntimeException("Complete should be called");
    }
    writer.dispose();
    ios.close();
    // Validates content of the file.
    final BufferedImage imageRead = ImageIO.read(file);
    for (int x = 0; x < WIDTH; ++x) {
        for (int y = 0; y < HEIGHT; ++y) {
            if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
                throw new RuntimeException("Test failed.");
            }
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedImage(java.awt.image.BufferedImage) ImageOutputStream(javax.imageio.stream.ImageOutputStream) Graphics2D(java.awt.Graphics2D)

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