Java Code Examples for javax.imageio.ImageIO#getImageWritersByFormatName()

The following examples show how to use javax.imageio.ImageIO#getImageWritersByFormatName() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Encodes an image in JPEG format and writes it to an output stream.
 *
 * @param bufferedImage  the image to be encoded (<code>null</code> not
 *     permitted).
 * @param outputStream  the OutputStream to write the encoded image to
 *     (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O problem.
 * @throws NullPointerException if <code>bufferedImage</code> is
 *     <code>null</code>.
 */
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
        throws IOException {
    if (bufferedImage == null) {
        throw new IllegalArgumentException("Null 'image' argument.");
    }
    if (outputStream == null) {
        throw new IllegalArgumentException("Null 'outputStream' argument.");
    }
    Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iterator.next();
    ImageWriteParam p = writer.getDefaultWriteParam();
    p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    p.setCompressionQuality(this.quality);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(bufferedImage, null, null), p);
    ios.flush();
    writer.dispose();
    ios.close();
}
 
Example 2
Source Project: olat   File: ImageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 3
/**
 * Encodes an image in JPEG format and writes it to an output stream.
 *
 * @param bufferedImage  the image to be encoded (<code>null</code> not
 *     permitted).
 * @param outputStream  the OutputStream to write the encoded image to
 *     (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O problem.
 * @throws NullPointerException if <code>bufferedImage</code> is
 *     <code>null</code>.
 */
@Override
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
        throws IOException {
    ParamChecks.nullNotPermitted(bufferedImage, "bufferedImage");
    ParamChecks.nullNotPermitted(outputStream, "outputStream");
    Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iterator.next();
    ImageWriteParam p = writer.getDefaultWriteParam();
    p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    p.setCompressionQuality(this.quality);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(bufferedImage, null, null), p);
    ios.flush();
    writer.dispose();
    ios.close();
}
 
Example 4
public static void saveImageInPng(BufferedImage img, File f) throws IOException {
	Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName("png");
	
	if(!iw.hasNext())
		throw new IOException("PNG Writer not found");
	
	
	ImageWriter writer = iw.next();

	ImageWriteParam writeParam = writer.getDefaultWriteParam();
	ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
	IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
	setDPI(metadata);

	ImageOutputStream stream = ImageIO.createImageOutputStream(f);
	try {
		writer.setOutput(stream);
		writer.write(metadata, new IIOImage(img, null, metadata), writeParam);
	} finally {
		stream.close();
	}

}
 
Example 5
Source Project: geopackage-java   File: ImageUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Compress and write the image to bytes in the provided format and quality
 * 
 * @param image
 *            buffered image
 * @param formatName
 *            image format name
 * @param quality
 *            quality between 0.0 and 1.0
 * @return compressed image bytes
 * @since 1.1.2
 */
public static byte[] compressAndWriteImageToBytes(BufferedImage image,
		String formatName, float quality) {

	byte[] bytes = null;

	Iterator<ImageWriter> writers = ImageIO
			.getImageWritersByFormatName(formatName);
	if (writers == null || !writers.hasNext()) {
		throw new GeoPackageException(
				"No Image Writer to compress format: " + formatName);
	}
	ImageWriter writer = writers.next();
	ImageWriteParam writeParam = writer.getDefaultWriteParam();
	writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
	writeParam.setCompressionQuality(quality);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ImageOutputStream ios = null;
	try {
		ios = ImageIO.createImageOutputStream(baos);
		writer.setOutput(ios);
		writer.write(null, new IIOImage(image, null, null), writeParam);
		writer.dispose();

		bytes = baos.toByteArray();

	} catch (IOException e) {
		throw new GeoPackageException(
				"Failed to compress image to format: " + formatName
						+ ", with quality: " + quality, e);
	} finally {
		closeQuietly(ios);
		closeQuietly(baos);
	}

	return bytes;
}
 
Example 6
public static void main(String[] args) throws IOException {
    Iterator witer = ImageIO.getImageWritersByFormatName("png");
    ImageWriter w = (ImageWriter)witer.next();

    File f = File.createTempFile("WriteProgressive", ".png");
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    w.setOutput(ios);

    BufferedImage bi = new BufferedImage(100, 100,
                                         BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = bi.createGraphics();
    Random r = new Random(10);
    for (int i = 0; i < 10000; i++) {
        Color c =
            new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
        g.setColor(c);
        g.fillRect(r.nextInt(100), r.nextInt(100), 1, 1);
    }

    IIOImage iioimage = new IIOImage(bi, null, null);

    ImageWriteParam param = w.getDefaultWriteParam();
    param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);

    try {
        w.write(null, iioimage, param);
    } catch (NullPointerException npe) {
        throw new RuntimeException("Got NPE during write!");
    }

    ios.close();

    BufferedImage bi2 = ImageIO.read(f);
    f.delete();

    ImageCompare.compare(bi, bi2);
}
 
Example 7
public static void main(String[] args) throws IIOInvalidTreeException {

        // getting the writer for the png format
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        ImageWriter writer = (ImageWriter) iter.next();

        // creating a color model
        ColorModel colorModel = ColorModel.getRGBdefault();

        // creating a sample model
        SampleModel sampleModel = colorModel.createCompatibleSampleModel(640, 480);

        // creating a default metadata object
        IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(colorModel, sampleModel), null);
        String formatName = metaData.getNativeMetadataFormatName();

        // first call
        Node metaDataNode = metaData.getAsTree(formatName);
        try {
            metaData.setFromTree(formatName, metaDataNode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // second call (bitdepht is already set to an invalid value)
        metaDataNode = metaData.getAsTree(formatName);

        metaData.setFromTree(formatName, metaDataNode);

    }
 
Example 8
public static void main(String[] args) throws IIOInvalidTreeException {

        // getting the writer for the png format
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        ImageWriter writer = (ImageWriter) iter.next();

        // creating a color model
        ColorModel colorModel = ColorModel.getRGBdefault();

        // creating a sample model
        SampleModel sampleModel = colorModel.createCompatibleSampleModel(640, 480);

        // creating a default metadata object
        IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(colorModel, sampleModel), null);
        String formatName = metaData.getNativeMetadataFormatName();

        // first call
        Node metaDataNode = metaData.getAsTree(formatName);
        try {
            metaData.setFromTree(formatName, metaDataNode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // second call (bitdepht is already set to an invalid value)
        metaDataNode = metaData.getAsTree(formatName);

        metaData.setFromTree(formatName, metaDataNode);

    }
 
Example 9
Source Project: ghidra   File: GImage.java    License: Apache License 2.0 5 votes vote down vote up
private ImageWriter getImageWriter(String format) throws IOException {
	Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(format);
	if (!imageWriters.hasNext()) {
		throw new IOException("No image writer found for PNG.");
	}
	ImageWriter imageWriter = imageWriters.next();
	return imageWriter;
}
 
Example 10
Source Project: SwissQRBill   File: PNGCanvas.java    License: MIT License 5 votes vote down vote up
/**
 * Saves image as PDF and stores meta data to indicate the resolution.
 */
private static void createPNG(BufferedImage image, OutputStream os, int resolution) throws IOException {

    ImageWriter writer = null;
    ImageWriteParam writeParam = null;
    IIOMetadata metadata = null;

    for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName("png"); iw.hasNext(); ) {
        writer = iw.next();
        writeParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(image.getType());
        metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
        if (!metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported())
            break;
    }

    if (writer == null || writeParam == null)
        throw new QRBillGenerationException("No valid PNG writer found");

    addDpiMetadata(metadata, resolution);
    addTextMetadata(metadata);

    try (ImageOutputStream stream = ImageIO.createImageOutputStream(os)) {
        writer.setOutput(stream);
        writer.write(metadata, new IIOImage(image, null, metadata), writeParam);
    }
}
 
Example 11
public static void main(String[] args) throws IIOInvalidTreeException {

        // getting the writer for the png format
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        ImageWriter writer = (ImageWriter) iter.next();

        // creating a color model
        ColorModel colorModel = ColorModel.getRGBdefault();

        // creating a sample model
        SampleModel sampleModel = colorModel.createCompatibleSampleModel(640, 480);

        // creating a default metadata object
        IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(colorModel, sampleModel), null);
        String formatName = metaData.getNativeMetadataFormatName();

        // first call
        Node metaDataNode = metaData.getAsTree(formatName);
        try {
            metaData.setFromTree(formatName, metaDataNode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // second call (bitdepht is already set to an invalid value)
        metaDataNode = metaData.getAsTree(formatName);

        metaData.setFromTree(formatName, metaDataNode);

    }
 
Example 12
public static void main(String[] args) throws IIOInvalidTreeException {

        // getting the writer for the png format
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        ImageWriter writer = (ImageWriter) iter.next();

        // creating a color model
        ColorModel colorModel = ColorModel.getRGBdefault();

        // creating a sample model
        SampleModel sampleModel = colorModel.createCompatibleSampleModel(640, 480);

        // creating a default metadata object
        IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(colorModel, sampleModel), null);
        String formatName = metaData.getNativeMetadataFormatName();

        // first call
        Node metaDataNode = metaData.getAsTree(formatName);
        try {
            metaData.setFromTree(formatName, metaDataNode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // second call (bitdepht is already set to an invalid value)
        metaDataNode = metaData.getAsTree(formatName);

        metaData.setFromTree(formatName, metaDataNode);

    }
 
Example 13
private void writeJPG(BufferedImage bufferedImage, OutputStream outputStream, double quality) throws IOException {
    Iterator<ImageWriter> iterator =
        ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter imageWriter = iterator.next();
    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    imageWriteParam.setCompressionQuality((float) quality);
    ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(outputStream);
    imageWriter.setOutput(imageOutputStream);
    IIOImage iioimage = new IIOImage(bufferedImage, null, null);
    imageWriter.write(null, iioimage, imageWriteParam);
    imageOutputStream.flush();
}
 
Example 14
private static ImageWriter getImageWriter(String type) {
	Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(type);
	if (!writers.hasNext()) {
		throw new DSSException("No writer for '" + type + "' found");
	}
	return writers.next();
}
 
Example 15
private static void writeJPGtoStream(BufferedImage image,
                                     ImageInputStream ios,
                                     JpegInfo config,
                                     ProgressTracker tracker) throws IOException {
    Iterator<ImageWriter> jpgWriters = ImageIO.getImageWritersByFormatName("jpg");
    if (!jpgWriters.hasNext()) {
        throw new IllegalStateException("No JPG writers found");
    }
    ImageWriter writer = jpgWriters.next();

    ImageWriteParam imageWriteParam = writer.getDefaultWriteParam();

    if (config.isProgressive()) {
        imageWriteParam.setProgressiveMode(MODE_DEFAULT);
    } else {
        imageWriteParam.setProgressiveMode(MODE_DISABLED);
    }

    imageWriteParam.setCompressionMode(MODE_EXPLICIT);
    imageWriteParam.setCompressionQuality(config.getQuality());

    IIOImage iioImage = new IIOImage(image, null, null);

    writer.setOutput(ios);
    if (tracker != null) {
        writer.addIIOWriteProgressListener(new TrackerWriteProgressListener(tracker));
    }
    writer.write(null, iioImage, imageWriteParam);

    ios.flush();
    ios.close();
}
 
Example 16
/**
 * Save image.
 *
 * @param image the grid image
 * @param formatName the format name
 * @param destinationFile the output
 * @param dpi the dpi
 * @return true, if successful
 * @throws IOException Signals that an I/O exception has occurred.
 */
private boolean saveGridImage(
        BufferedImage image, String formatName, File destinationFile, int dpi)
        throws IOException {
    if (!Files.delete(destinationFile)) {
        ConsoleManager.getInstance()
                .information(
                        this,
                        String.format(
                                "Failed to delete '%s'", destinationFile.getAbsolutePath()));
    }

    boolean finish = false;

    for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName);
            iw.hasNext() && !finish; ) {
        ImageWriter writer = iw.next();
        ImageWriteParam writeParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier typeSpecifier =
                ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
        IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
        if (!(metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported())) {

            setDPI(metadata, dpi);

            final ImageOutputStream stream = ImageIO.createImageOutputStream(destinationFile);
            try {
                writer.setOutput(stream);
                writer.write(metadata, new IIOImage(image, null, metadata), writeParam);
            } finally {
                stream.close();
            }
            finish = true;
        }
    }

    return true;
}
 
Example 17
public static void main(String[] args) throws IOException {
    Iterator witer = ImageIO.getImageWritersByFormatName("png");
    ImageWriter w = (ImageWriter)witer.next();

    File f = File.createTempFile("WriteProgressive", ".png");
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    w.setOutput(ios);

    BufferedImage bi = new BufferedImage(100, 100,
                                         BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = bi.createGraphics();
    Random r = new Random(10);
    for (int i = 0; i < 10000; i++) {
        Color c =
            new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
        g.setColor(c);
        g.fillRect(r.nextInt(100), r.nextInt(100), 1, 1);
    }

    IIOImage iioimage = new IIOImage(bi, null, null);

    ImageWriteParam param = w.getDefaultWriteParam();
    param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);

    try {
        w.write(null, iioimage, param);
    } catch (NullPointerException npe) {
        throw new RuntimeException("Got NPE during write!");
    }

    ios.close();

    BufferedImage bi2 = ImageIO.read(f);
    f.delete();

    ImageCompare.compare(bi, bi2);
}
 
Example 18
Source Project: minifierbeans   File: ImageUtil.java    License: Apache License 2.0 5 votes vote down vote up
public void compressJPG(String inputFilePath, String outputFilePath, String fileType) {
    InputOutput io = IOProvider.getDefault().getIO(Bundle.CTL_Base64Encode(), false);
    try {
        File imageFile = new File(inputFilePath);
        File compressedImageFile = new File(outputFilePath);

        InputStream is = new FileInputStream(imageFile);
        OutputStream os = new FileOutputStream(compressedImageFile);
        float quality = 0.5f;
        
        // create a BufferedImage as the result of decoding the supplied InputStream
        BufferedImage image = ImageIO.read(is);
        
        // get all image writers for JPG format
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(fileType);

        if (!writers.hasNext()) {
            throw new IllegalStateException("No writers found");
        }
        
        ImageWriter writer = writers.next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        writer.setOutput(ios);
        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        
        // appends a complete image stream containing a single image and
        //associated stream and image metadata and thumbnails to the output
        writer.write(null, new IIOImage(image, null, null), param);

        is.close();
        os.close();
        ios.close();
        writer.dispose();
    } catch (IOException ex) {
        io.getOut().println("Exception: " + ex.toString());
    }
}
 
Example 19
public static void main(String[] args) throws IIOInvalidTreeException {

        // getting the writer for the png format
        Iterator iter = ImageIO.getImageWritersByFormatName("png");
        ImageWriter writer = (ImageWriter) iter.next();

        // creating a color model
        ColorModel colorModel = ColorModel.getRGBdefault();

        // creating a sample model
        SampleModel sampleModel = colorModel.createCompatibleSampleModel(640, 480);

        // creating a default metadata object
        IIOMetadata metaData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(colorModel, sampleModel), null);
        String formatName = metaData.getNativeMetadataFormatName();

        // first call
        Node metaDataNode = metaData.getAsTree(formatName);
        try {
            metaData.setFromTree(formatName, metaDataNode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // second call (bitdepht is already set to an invalid value)
        metaDataNode = metaData.getAsTree(formatName);

        metaData.setFromTree(formatName, metaDataNode);

    }
 
Example 20
/**
 * Export to a picture file
 *
 * @param fileName File path
 * @param dpi DPI
 * @throws java.io.FileNotFoundException
 * @throws javax.print.PrintException
 */
public void exportToPicture(String fileName, Integer dpi) throws FileNotFoundException, PrintException, IOException {
    if (dpi == null) {
        exportToPicture(fileName);
    } else {
        File output = new File(fileName);
        output.delete();

        int width = _pageBounds.width;
        int height = _pageBounds.height;
        String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);
        if (formatName.equals("jpg")) {
            formatName = "jpeg";
            saveImage_Jpeg(fileName, width, height, dpi);
            return;
        }

        double scaleFactor = dpi / 72.0;
        BufferedImage image = new BufferedImage((int)(width * scaleFactor), (int)(height * scaleFactor), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        AffineTransform at = g.getTransform();
        at.scale(scaleFactor, scaleFactor);
        g.setTransform(at);
        paintGraphics(g);
        for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
            ImageWriter writer = iw.next();
            ImageWriteParam writeParam = writer.getDefaultWriteParam();
            ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
            IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
            if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
                continue;
            }

            ImageUtil.setDPI(metadata, dpi);

            final ImageOutputStream stream = ImageIO.createImageOutputStream(output);
            try {
                writer.setOutput(stream);
                writer.write(metadata, new IIOImage(image, null, metadata), writeParam);
            } finally {
                stream.close();
            }
            break;
        }
        g.dispose();
    }
}