Search in sources :

Example 26 with IIOImage

use of javax.imageio.IIOImage in project hutool by looly.

the class ImgUtil method write.

/**
 * 通过{@link ImageWriter}写出图片到输出流
 *
 * @param image   图片
 * @param writer  {@link ImageWriter}
 * @param output  输出的Image流{@link ImageOutputStream}
 * @param quality 质量,数字为0~1(不包括0和1)表示质量压缩比,除此数字外设置表示不压缩
 * @return 是否成功写出
 * @since 4.3.2
 */
public static boolean write(Image image, ImageWriter writer, ImageOutputStream output, float quality) {
    if (writer == null) {
        return false;
    }
    writer.setOutput(output);
    final RenderedImage renderedImage = toRenderedImage(image);
    // 设置质量
    ImageWriteParam imgWriteParams = null;
    if (quality > 0 && quality < 1) {
        imgWriteParams = writer.getDefaultWriteParam();
        if (imgWriteParams.canWriteCompressed()) {
            imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imgWriteParams.setCompressionQuality(quality);
            // ColorModel.getRGBdefault();
            final ColorModel colorModel = renderedImage.getColorModel();
            imgWriteParams.setDestinationType(new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));
        }
    }
    try {
        if (null != imgWriteParams) {
            writer.write(null, new IIOImage(renderedImage, null, null), imgWriteParams);
        } else {
            writer.write(renderedImage);
        }
        output.flush();
    } catch (IOException e) {
        throw new IORuntimeException(e);
    } finally {
        writer.dispose();
    }
    return true;
}
Also used : IORuntimeException(cn.hutool.core.io.IORuntimeException) ColorModel(java.awt.image.ColorModel) IOException(java.io.IOException) RenderedImage(java.awt.image.RenderedImage) ImageWriteParam(javax.imageio.ImageWriteParam) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage)

Example 27 with IIOImage

use of javax.imageio.IIOImage in project JFramework by gugumall.

the class JUtilImage method resize.

/**
 * 将srcFile调整为newWidth*newHeight大小,并保存为destFile
 *
 * @param srcFile
 * @param destFile
 * @param newWidth
 * @param newHeight
 * @param imageFormat
 * @return
 * @throws Exception
 */
public void resize(File srcFile, File destFile, int newWidth, int newHeight, String imageFormat) throws Exception {
    if (!chkImageFormat(imageFormat)) {
        throw new Exception("图片类型不合法");
    }
    if (imageFormat.equalsIgnoreCase(FORMAT_GIF) || srcFile.getName().toLowerCase().endsWith(".gif")) {
        resizeGifImage(srcFile, destFile, newWidth, newHeight, true);
        return;
    }
    Image src = Toolkit.getDefaultToolkit().getImage(srcFile.getAbsolutePath());
    src = new ImageIcon(src).getImage();
    BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = tag.createGraphics();
    // 设置透明
    if (imageFormat.equals(JUtilImage.FORMAT_PNG)) {
        tag = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight, Transparency.TRANSLUCENT);
    }
    g2d.dispose();
    g2d = tag.createGraphics();
    // 设置透明 end
    // 绘制缩小后的图
    g2d.drawImage(src, 0, 0, newWidth, newHeight, this);
    // 如果父目录不存在,则创建目录
    if (!destFile.getParentFile().exists()) {
        destFile.getParentFile().mkdirs();
    }
    // 输出到文件流
    FileOutputStream os = new FileOutputStream(destFile);
    ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(imageFormat).next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);
    ImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality);
    writer.write(null, new IIOImage(tag, null, null), param);
    writer.dispose();
    ios.flush();
    ios.close();
    os.close();
}
Also used : ImageIcon(javax.swing.ImageIcon) FileOutputStream(java.io.FileOutputStream) ImageWriter(javax.imageio.ImageWriter) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) IIOImage(javax.imageio.IIOImage) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) GifImage(com.gif4j.GifImage) ImageWriteParam(javax.imageio.ImageWriteParam) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) ImageOutputStream(javax.imageio.stream.ImageOutputStream) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage)

Example 28 with IIOImage

use of javax.imageio.IIOImage in project JFramework by gugumall.

the class JUtilImage method zoom.

/**
 * 将srcFile按比例scale缩放,长宽比例不变,并保存为destFile
 *
 * @param srcFile
 * @param destFile
 * @param scale
 * @param imageFormat
 * @return
 * @throws Exception
 */
public void zoom(File srcFile, File destFile, double scale, String imageFormat) throws Exception {
    if (!chkImageFormat(imageFormat)) {
        throw new Exception("图片类型不合法");
    }
    Image src = Toolkit.getDefaultToolkit().getImage(srcFile.getAbsolutePath());
    src = new ImageIcon(src).getImage();
    double oldWidth = (double) src.getWidth(this);
    double oldHeight = (double) src.getHeight(this);
    int newWidth = JUtilMath.toInt(oldWidth * scale);
    int newHeight = JUtilMath.toInt(oldHeight * scale);
    if (imageFormat.equalsIgnoreCase(FORMAT_GIF) || srcFile.getName().toLowerCase().endsWith(".gif")) {
        resizeGifImage(srcFile, destFile, newWidth, newHeight, true);
        return;
    }
    BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = tag.createGraphics();
    // 设置透明
    if (imageFormat.equals(JUtilImage.FORMAT_PNG)) {
        tag = g2d.getDeviceConfiguration().createCompatibleImage(newWidth, newHeight, Transparency.TRANSLUCENT);
    }
    g2d.dispose();
    g2d = tag.createGraphics();
    // 设置透明 end
    // 绘制缩小后的图
    g2d.drawImage(src, 0, 0, newWidth, newHeight, this);
    // 如果父目录不存在,则创建目录
    if (!destFile.getParentFile().exists()) {
        destFile.getParentFile().mkdirs();
    }
    // 输出到文件流
    FileOutputStream os = new FileOutputStream(destFile);
    ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(imageFormat).next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);
    ImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality);
    writer.write(null, new IIOImage(tag, null, null), param);
    writer.dispose();
    ios.flush();
    ios.close();
    os.close();
}
Also used : ImageIcon(javax.swing.ImageIcon) ImageWriter(javax.imageio.ImageWriter) IIOImage(javax.imageio.IIOImage) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) GifImage(com.gif4j.GifImage) ImageWriteParam(javax.imageio.ImageWriteParam) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage) FileOutputStream(java.io.FileOutputStream) JPEGImageWriteParam(javax.imageio.plugins.jpeg.JPEGImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 29 with IIOImage

use of javax.imageio.IIOImage 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 30 with IIOImage

use of javax.imageio.IIOImage in project ultimate-java by pantinor.

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();
        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")) {
            canvas = new ColorBleedEffect().processImage(canvas, 2);
            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")) {
                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) IOException(java.io.IOException) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage) GdxRuntimeException(com.badlogic.gdx.utils.GdxRuntimeException) File(java.io.File) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Aggregations

IIOImage (javax.imageio.IIOImage)123 ImageWriter (javax.imageio.ImageWriter)92 ImageWriteParam (javax.imageio.ImageWriteParam)79 ImageOutputStream (javax.imageio.stream.ImageOutputStream)79 BufferedImage (java.awt.image.BufferedImage)66 File (java.io.File)45 IOException (java.io.IOException)41 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 IIOMetadata (javax.imageio.metadata.IIOMetadata)32 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)25 ByteArrayInputStream (java.io.ByteArrayInputStream)22 FileImageOutputStream (javax.imageio.stream.FileImageOutputStream)17 ImageReader (javax.imageio.ImageReader)16 MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)16 Graphics2D (java.awt.Graphics2D)14 JPEGImageWriteParam (javax.imageio.plugins.jpeg.JPEGImageWriteParam)14 Test (org.junit.Test)14 FileOutputStream (java.io.FileOutputStream)13 Iterator (java.util.Iterator)11 RenderedImage (java.awt.image.RenderedImage)10