Search in sources :

Example 76 with ImageWriter

use of javax.imageio.ImageWriter 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)

Example 77 with ImageWriter

use of javax.imageio.ImageWriter in project robolectric by robolectric.

the class ImageUtil method writeToStream.

public static boolean writeToStream(Bitmap realBitmap, CompressFormat format, int quality, OutputStream stream) {
    if ((quality < 0) || (quality > 100)) {
        throw new IllegalArgumentException("Quality out of bounds!");
    }
    try {
        ImageWriter writer = null;
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(getFormatName(format));
        if (iter.hasNext()) {
            writer = iter.next();
        }
        if (writer == null) {
            return false;
        }
        try (ImageOutputStream ios = ImageIO.createImageOutputStream(stream)) {
            writer.setOutput(ios);
            ImageWriteParam iwparam = writer.getDefaultWriteParam();
            iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            iwparam.setCompressionQuality((quality / 100f));
            int width = realBitmap.getWidth();
            int height = realBitmap.getHeight();
            boolean needAlphaChannel = needAlphaChannel(format);
            BufferedImage bufferedImage = Shadows.shadowOf(realBitmap).getBufferedImage();
            if (bufferedImage == null) {
                bufferedImage = new BufferedImage(realBitmap.getWidth(), realBitmap.getHeight(), BufferedImage.TYPE_INT_ARGB);
            }
            int outputImageType = getBufferedImageType(realBitmap.getConfig(), needAlphaChannel);
            if (outputImageType != BufferedImage.TYPE_INT_ARGB) {
                // re-encode image data with a type that is compatible with the output format.
                BufferedImage outputBufferedImage = new BufferedImage(width, height, outputImageType);
                Graphics2D g = outputBufferedImage.createGraphics();
                g.drawImage(bufferedImage, 0, 0, null);
                g.dispose();
                bufferedImage = outputBufferedImage;
            }
            writer.write(null, new IIOImage(bufferedImage, null, null), iwparam);
            ios.flush();
            writer.dispose();
        }
    } catch (IOException ignore) {
        return false;
    }
    return true;
}
Also used : ImageWriter(javax.imageio.ImageWriter) IIOException(javax.imageio.IIOException) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) Point(android.graphics.Point) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D) IIOImage(javax.imageio.IIOImage)

Example 78 with ImageWriter

use of javax.imageio.ImageWriter in project photon-core by 1000Memories.

the class PhotoResource method getPhoto.

@GET
@Timed
@CacheControl(immutable = true)
public Response getPhoto(@PathParam("name") String name, @MatrixParam("w") Integer width, @MatrixParam("r") RotationParam rotateAngle, @MatrixParam("c") RectangleParam crop) throws Exception {
    InputStream resultStream;
    InputStream imageStream;
    try {
        imageStream = new BufferedInputStream(photoProvider.getPhotoInputStream(name));
    } catch (FileNotFoundException fnfe) {
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
    String mimeType = URLConnection.guessContentTypeFromStream(imageStream);
    if (mimeType == null) {
        // Not implemented
        throw new WebApplicationException(501);
    }
    if (width != null || rotateAngle != null || crop != null) {
        BufferedImage image;
        TimerContext readContext = readTimer.time();
        try {
            image = ImageIO.read(imageStream);
        } finally {
            imageStream.close();
            readContext.stop();
        }
        if (crop != null) {
            image = com.thousandmemories.photon.core.Processor.crop(image, crop.get());
        }
        if (rotateAngle != null) {
            image = com.thousandmemories.photon.core.Processor.rotate(image, rotateAngle.get());
        }
        if (width != null) {
            image = com.thousandmemories.photon.core.Processor.fitToWidth(image, width);
        }
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(mimeType);
        if (!i.hasNext()) {
            mimeType = "image/jpeg";
            i = ImageIO.getImageWritersByMIMEType(mimeType);
        }
        ImageWriter writer = i.next();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(os));
        writer.write(image);
        image.flush();
        image = null;
        resultStream = new ByteArrayInputStream(os.toByteArray());
    } else {
        resultStream = imageStream;
    }
    return Response.ok(resultStream, mimeType).build();
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) TimerContext(com.yammer.metrics.core.TimerContext) ImageWriter(javax.imageio.ImageWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedImage(java.awt.image.BufferedImage) Timed(com.yammer.metrics.annotation.Timed) CacheControl(com.yammer.dropwizard.jersey.caching.CacheControl)

Example 79 with ImageWriter

use of javax.imageio.ImageWriter in project java-swing-tips by aterai.

the class MainPanel method createAnimatedGifFile.

private static File createAnimatedGifFile(List<Shape> list, Dimension size) throws IOException {
    Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName("gif");
    ImageWriter writer = it.hasNext() ? it.next() : null;
    if (Objects.isNull(writer)) {
        throw new IOException();
    }
    File file = File.createTempFile("anime", ".gif");
    file.deleteOnExit();
    try (ImageOutputStream stream = ImageIO.createImageOutputStream(file)) {
        writer.setOutput(stream);
        writer.prepareWriteSequence(null);
        IIOMetadataNode gce = new IIOMetadataNode("GraphicControlExtension");
        gce.setAttribute("disposalMethod", "none");
        gce.setAttribute("userInputFlag", "FALSE");
        gce.setAttribute("transparentColorFlag", "FALSE");
        gce.setAttribute("transparentColorIndex", "0");
        gce.setAttribute("delayTime", Objects.toString(DELAY));
        IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension");
        ae.setAttribute("applicationID", "NETSCAPE");
        ae.setAttribute("authenticationCode", "2.0");
        // last two bytes is an unsigned short (little endian) that
        // indicates the number of times to loop.
        // 0 means loop forever.
        ae.setUserObject(new byte[] { 0x1, 0x0, 0x0 });
        IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions");
        aes.appendChild(ae);
        // Create animated GIF using imageio | Oracle Community
        // https://community.oracle.com/thread/1264385
        BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), iwp);
        String metaFormat = metadata.getNativeMetadataFormatName();
        Node root = metadata.getAsTree(metaFormat);
        root.appendChild(gce);
        root.appendChild(aes);
        metadata.setFromTree(metaFormat, root);
        // make frame
        for (int i = 0; i < list.size() * DELAY; i++) {
            paintFrame(image, list);
            Collections.rotate(list, 1);
            writeToSequence(writer, image, metadata);
            metadata = null;
        }
        writer.endWriteSequence();
    }
    return file;
}
Also used : IIOMetadataNode(javax.imageio.metadata.IIOMetadataNode) Node(org.w3c.dom.Node) ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOMetadata(javax.imageio.metadata.IIOMetadata) File(java.io.File) IIOMetadataNode(javax.imageio.metadata.IIOMetadataNode) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 80 with ImageWriter

use of javax.imageio.ImageWriter in project openolat by klemens.

the class ImageHelperImpl method writeTo.

/**
 * Can change this to choose a better compression level as the default
 * @param image
 * @param scaledImage
 * @return
 */
public static boolean writeTo(BufferedImage image, File scaledImage, Size scaledSize, String outputFormat) {
    try {
        if (!StringHelper.containsNonWhitespace(outputFormat)) {
            outputFormat = OUTPUT_FORMAT;
        }
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat);
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();
            ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize);
            IIOImage iiOImage = new IIOImage(image, null, null);
            ImageOutputStream iOut = new FileImageOutputStream(scaledImage);
            writer.setOutput(iOut);
            writer.write(null, iiOImage, iwp);
            writer.dispose();
            iOut.flush();
            iOut.close();
            return true;
        } else {
            return ImageIO.write(image, outputFormat, scaledImage);
        }
    } catch (IOException e) {
        return false;
    }
}
Also used : FileImageOutputStream(javax.imageio.stream.FileImageOutputStream) ImageWriter(javax.imageio.ImageWriter) IOException(java.io.IOException) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) FileImageOutputStream(javax.imageio.stream.FileImageOutputStream) IIOImage(javax.imageio.IIOImage)

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