Search in sources :

Example 26 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project zm-mailbox by Zimbra.

the class NativeFormatter method getResizedImageData.

/**
 * If the image stored in the {@code MimePart} exceeds the given width,
 * shrinks the image and returns the shrunk data.  If the
 * image width is smaller than {@code maxWidth} or resizing is not supported,
 * returns {@code null}.
 */
public static byte[] getResizedImageData(InputStream in, String contentType, String fileName, Integer maxWidth, Integer maxHeight) throws IOException {
    ImageReader reader = null;
    ImageWriter writer = null;
    if (maxWidth == null)
        maxWidth = LC.max_image_size_to_resize.intValue();
    if (maxHeight == null)
        maxHeight = LC.max_image_size_to_resize.intValue();
    try {
        // Get ImageReader for stream content.
        reader = ImageUtil.getImageReader(contentType, fileName);
        if (reader == null) {
            log.debug("No ImageReader available.");
            return null;
        }
        // Read message content.
        reader.setInput(new MemoryCacheImageInputStream(in));
        BufferedImage img = reader.read(0);
        int width = img.getWidth(), height = img.getHeight();
        if (width <= maxWidth && height <= maxHeight) {
            log.debug("Image %dx%d is less than max %dx%d.  Not resizing.", width, height, maxWidth, maxHeight);
            return RETURN_CODE_NO_RESIZE.getBytes();
        }
        // Resize.
        writer = ImageIO.getImageWriter(reader);
        if (writer == null) {
            log.debug("No ImageWriter available.");
            return null;
        }
        double ratio = Math.min((double) maxWidth / width, (double) maxHeight / height);
        width *= ratio;
        height *= ratio;
        BufferedImage small = ImageUtil.resize(img, width, height);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(out));
        writer.write(small);
        return out.toByteArray();
    } finally {
        ByteUtil.closeStream(in);
        if (reader != null) {
            reader.dispose();
        }
        if (writer != null) {
            writer.dispose();
        }
    }
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) ImageWriter(javax.imageio.ImageWriter) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage)

Example 27 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project ma-core-public by infiniteautomation.

the class ImageUtils method encodeImage.

public static byte[] encodeImage(BufferedImage image, BaseImageFormat encodingFormat) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (encodingFormat.supportsCompression()) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(encodingFormat.getType());
        ImageWriter writer = iter.next();
        if (writer == null)
            throw new ShouldNeverHappenException("No writers for image format type " + encodingFormat.getType());
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(encodingFormat.getCompressionQuality());
        ImageOutputStream ios = new MemoryCacheImageOutputStream(out);
        writer.setOutput(ios);
        IIOImage iioImage = new IIOImage(image, null, null);
        writer.write(null, iioImage, iwp);
        ios.close();
    } else
        ImageIO.write(image, encodingFormat.getType(), out);
    return out.toByteArray();
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) ImageWriter(javax.imageio.ImageWriter) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) IIOImage(javax.imageio.IIOImage)

Example 28 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project BroadleafCommerce by BroadleafCommerce.

the class ImageArtifactProcessor method convert.

@Override
public InputStream convert(InputStream artifactStream, Operation[] operations, String mimeType) throws Exception {
    if (operations != null && operations.length > 0) {
        ImageInputStream iis = ImageIO.createImageInputStream(artifactStream);
        Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        ImageReader reader = iter.next();
        String formatName = reader.getFormatName();
        artifactStream.reset();
        BufferedImage image = ImageIO.read(ImageIO.createImageInputStream(artifactStream));
        // before
        if (formatName.toLowerCase().equals("jpeg") || formatName.toLowerCase().equals("jpg")) {
            image = stripAlpha(image);
        }
        for (Operation operation : operations) {
            image = effectsManager.renderEffect(operation.getName(), operation.getFactor(), operation.getParameters(), image);
        }
        // and after - some applications have a problem reading jpeg images with an alpha channel associated
        if (formatName.toLowerCase().equals("jpeg") || formatName.toLowerCase().equals("jpg")) {
            image = stripAlpha(image);
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(byteArrayOutputStream);
        if (formatName.toLowerCase().equals("gif")) {
            formatName = "png";
        }
        Iterator<ImageWriter> writerIter = ImageIO.getImageWritersByFormatName(formatName);
        ImageWriter writer = writerIter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        if (formatName.toLowerCase().equals("jpeg") || formatName.toLowerCase().equals("jpg")) {
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            iwp.setCompressionQuality(compressionQuality);
        }
        MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(bos);
        writer.setOutput(output);
        IIOImage iomage = new IIOImage(image, null, null);
        writer.write(null, iomage, iwp);
        bos.flush();
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    } else {
        return artifactStream;
    }
}
Also used : ImageInputStream(javax.imageio.stream.ImageInputStream) ImageWriter(javax.imageio.ImageWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) BufferedImage(java.awt.image.BufferedImage) IIOImage(javax.imageio.IIOImage) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageReader(javax.imageio.ImageReader) BufferedOutputStream(java.io.BufferedOutputStream)

Example 29 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project Openfire by igniterealtime.

the class PhotoResizer method cropAndShrink.

public static byte[] cropAndShrink(final byte[] bytes, final int targetDimension, final ImageWriter iw) {
    Log.debug("Original image size: {} bytes.", bytes.length);
    BufferedImage avatar;
    try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
        avatar = ImageIO.read(stream);
        if (avatar.getWidth() <= targetDimension && avatar.getHeight() <= targetDimension) {
            Log.debug("Original image dimension ({}x{}) is within acceptable bounds ({}x{}). No need to resize.", new Object[] { avatar.getWidth(), avatar.getHeight(), targetDimension, targetDimension });
            return null;
        }
    } catch (IOException | RuntimeException ex) {
        Log.warn("Failed to resize avatar. An unexpected exception occurred while reading the original image.", ex);
        return null;
    }
    /* We're going to be resizing, let's crop the image so that it's square and figure out the new starting size. */
    Log.debug("Original image is " + avatar.getWidth() + "x" + avatar.getHeight() + " pixels");
    final int targetWidth, targetHeight;
    if (avatar.getHeight() == avatar.getWidth()) {
        Log.debug("Original image is already square ({}x{})", avatar.getWidth(), avatar.getHeight());
        targetWidth = targetHeight = avatar.getWidth();
    } else {
        final int x, y;
        if (avatar.getHeight() > avatar.getWidth()) {
            Log.debug("Original image is taller ({}) than wide ({}).", avatar.getHeight(), avatar.getWidth());
            x = 0;
            y = (avatar.getHeight() - avatar.getWidth()) / 2;
            targetWidth = targetHeight = avatar.getWidth();
        } else {
            Log.debug("Original image is wider ({}) than tall ({}).", avatar.getWidth(), avatar.getHeight());
            x = (avatar.getWidth() - avatar.getHeight()) / 2;
            y = 0;
            targetWidth = targetHeight = avatar.getHeight();
        }
        // pull out a square image, centered.
        avatar = avatar.getSubimage(x, y, targetWidth, targetHeight);
    }
    /* Let's crop/scale the image as necessary out the new dimensions. */
    final BufferedImage resizedAvatar = new BufferedImage(targetDimension, targetDimension, avatar.getType());
    final AffineTransform scale = AffineTransform.getScaleInstance((double) targetDimension / (double) targetWidth, (double) targetDimension / (double) targetHeight);
    final Graphics2D g = resizedAvatar.createGraphics();
    g.drawRenderedImage(avatar, scale);
    Log.debug("Resized image is {}x{}.", resizedAvatar.getWidth(), resizedAvatar.getHeight());
    /* Now we have to dump the new jpeg, png, etc. to a byte array */
    try (final ByteArrayOutputStream bostream = new ByteArrayOutputStream();
        final ImageOutputStream iostream = new MemoryCacheImageOutputStream(bostream)) {
        iw.setOutput(iostream);
        iw.write(resizedAvatar);
        final byte[] data = bostream.toByteArray();
        Log.debug("Resized image size: {} bytes.", data.length);
        return data;
    } catch (IOException | RuntimeException ex) {
        Log.warn("Failed to resize avatar. An unexpected exception occurred while writing the resized image.", ex);
        return null;
    }
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AffineTransform(java.awt.geom.AffineTransform) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedImage(java.awt.image.BufferedImage) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Example 30 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream 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
 */
private static boolean writeTo(BufferedImage image, OutputStream 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 MemoryCacheImageOutputStream(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 : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) 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

MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)30 ByteArrayOutputStream (java.io.ByteArrayOutputStream)22 ImageOutputStream (javax.imageio.stream.ImageOutputStream)16 BufferedImage (java.awt.image.BufferedImage)15 IIOImage (javax.imageio.IIOImage)13 ImageWriter (javax.imageio.ImageWriter)13 ImageWriteParam (javax.imageio.ImageWriteParam)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 IOException (java.io.IOException)7 ImageReader (javax.imageio.ImageReader)6 MemoryCacheImageInputStream (javax.imageio.stream.MemoryCacheImageInputStream)5 IIOMetadata (javax.imageio.metadata.IIOMetadata)4 WritableRaster (java.awt.image.WritableRaster)3 OutputStream (java.io.OutputStream)3 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)3 Graphics2D (java.awt.Graphics2D)2 AffineTransform (java.awt.geom.AffineTransform)2 InputStream (java.io.InputStream)2 JPEGImageWriteParam (javax.imageio.plugins.jpeg.JPEGImageWriteParam)2 FileImageOutputStream (javax.imageio.stream.FileImageOutputStream)2