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

The following are Jave code examples for showing how to use getImageWritersByFormatName() of the javax.imageio.ImageIO class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: shareMySheet   File: ImageTransformation.java   View Source Code Vote up 10 votes
public static byte[] compress(BufferedImage image, float scale) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = writers.next();
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(scale);
    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(image, null, null), param);
    byte[] data = baos.toByteArray();
    writer.dispose();
    return data;
}
 
Example 2
Project: litiengine   File: ImageSerializer.java   View Source Code Vote up 6 votes
public static void saveImage(final String fileName, final BufferedImage image, ImageFormat imageFormat) {
  try {
    final File file = new File(fileName);
    final String extension = FileUtilities.getExtension(fileName);
    Iterator<ImageWriter> iter = null;
    if (canWriteFormat(extension)) {
      iter = ImageIO.getImageWritersByFormatName(extension);
    } else {
      iter = ImageIO.getImageWritersByFormatName(imageFormat.toString());
    }

    final ImageWriter writer = iter.next();
    final ImageWriteParam iwp = writer.getDefaultWriteParam();

    file.getParentFile().mkdirs();
    try (final FileImageOutputStream output = new FileImageOutputStream(file.getAbsoluteFile())) {
      writer.setOutput(output);
      final IIOImage outimage = new IIOImage(image, null, null);
      writer.write(null, outimage, iwp);
      writer.dispose();
    }
  } catch (final IOException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
 
Example 3
Project: parabuild-ci   File: SunJPEGEncoderAdapter.java   View Source Code Vote up 6 votes
/**
 * 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 4
Project: openjdk-jdk10   File: ImageCompressionTypesTest.java   View Source Code Vote up 6 votes
public ImageCompressionTypesTest(String format) {
    Iterator it = ImageIO.getImageWritersByFormatName(format);
    while (it.hasNext()) {
        writer = (ImageWriter) it.next();
        break;
    }
    ImageWriteParam param = writer.getDefaultWriteParam();

    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    System.out.println("Checking compression types for : " + format);
    String compTypes[] = param.getCompressionTypes();
    if (compTypes.length > 1) {
        for (int i = 0; i < compTypes.length; i++) {
            for (int j = i + 1; j < compTypes.length; j++) {
                if (compTypes[i].equalsIgnoreCase(compTypes[j])) {
                    throw new RuntimeException("Duplicate compression"
                            + " type exists for image format " + format);
                }
            }
        }
    }
}
 
Example 5
Project: openjdk-jdk10   File: WriteProgressive.java   View Source Code Vote up 6 votes
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 6
Project: AntiSocial-Platform   File: ImageServiceImpl.java   View Source Code Vote up 6 votes
public void compressSave(MultipartFile file, String uploadLocation) throws IOException {
    //Compresses JPG file but kills the quality.
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
    File compressedImageFile = new File(uploadLocation);
    OutputStream os = new FileOutputStream(compressedImageFile);
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);
    ImageWriteParam param = writer.getDefaultWriteParam();
    if(param.canWriteCompressed()) {
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.05f);
    }

    writer.write(null, new IIOImage(image, null, null), param);
}
 
Example 7
Project: AntiSocial-Platform   File: ImageServiceImpl.java   View Source Code Vote up 6 votes
public void compressSave(MultipartFile file, String uploadLocation) throws IOException {
    //Compresses JPG file but kills the quality.
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
    File compressedImageFile = new File(uploadLocation);
    OutputStream os = new FileOutputStream(compressedImageFile);
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);
    ImageWriteParam param = writer.getDefaultWriteParam();
    if(param.canWriteCompressed()) {
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.05f);
    }

    writer.write(null, new IIOImage(image, null, null), param);
}
 
Example 8
Project: springboot-training   File: ImageUtil.java   View Source Code Vote up 6 votes
/**
 * 根据质量压缩图片,不改变图片的尺寸
 * 
 * @param imgContent
 *            图片内容
 * @param quality
 *            缩放比例
 * @param extName
 *            后缀名
 * @return
 */
public byte[] compress(byte[] imgContent, float quality, String extName) {
	if (quality > 1 || quality <= 0 || imgContent == null || WakaUtils.string.isEmpty(extName)) {
		throw new ZhhrUtilException("压缩文件失败!入参为空");
	}
	try (InputStream is = new ByteArrayInputStream(imgContent);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageOutputStream ios = ImageIO.createImageOutputStream(os);) {
		BufferedImage image = ImageIO.read(is);

		Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(extName);
		ImageWriter writer = writers.next();
		writer.setOutput(ios);

		ImageWriteParam param = writer.getDefaultWriteParam();
		param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		param.setCompressionQuality(quality);

		writer.write(null, new IIOImage(image, null, null), param);
		writer.dispose();

		return os.toByteArray();
	} catch (IOException e) {
		throw new ZhhrUtilException(e.getMessage(), e);
	}
}
 
Example 9
Project: GlitchKernel   File: ImageUtil.java   View Source Code Vote up 5 votes
public static byte[] setGlitchQuality(byte[] inputImageBytes, int quality) throws Exception
{
	Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png");
	ImageWriter writer = (ImageWriter)iter.next();  
	ImageWriteParam iwp = writer.getDefaultWriteParam(); 
    BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(inputImageBytes)); 
    IIOImage image = new IIOImage(originalImage, null, null);
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    ImageOutputStream imageOut=ImageIO.createImageOutputStream(out);
    writer.setOutput(imageOut);  
    writer.write(null, image, iwp);  
    byte[] qualityImageBytes = out.toByteArray();
    return qualityImageBytes;
}
 
Example 10
Project: SpotSpotter   File: ImageReader2File.java   View Source Code Vote up 5 votes
public static void IR2F(ImageReader input, String formatname, String output) throws IOException {
	final Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatname);
	final ImageWriter writer = writers.next();
	final File f = new File(output);
	final ImageOutputStream ios = ImageIO.createImageOutputStream(f);
	writer.setOutput(ios);
}
 
Example 11
Project: jdk8u-jdk   File: PngDitDepthTest.java   View Source Code Vote up 5 votes
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
Project: openjdk-jdk10   File: GetReaderWriterInfo.java   View Source Code Vote up 5 votes
private static void testGetWriterFormatNames() {
    String[] names = ImageIO.getWriterFormatNames();
    for (String n : names) {
        Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(n);
        if (!it.hasNext()) {
            throw new RuntimeException("getWriterFormatNames returned " +
                                       "an unknown name: " + n);
        }
    }
}
 
Example 13
Project: openjdk-jdk10   File: WBMPPluginTest.java   View Source Code Vote up 5 votes
private static void init() {

        Iterator i = ImageIO.getImageWritersByFormatName(format);
        if (!i.hasNext()) {
            throw new RuntimeException("No available ImageWrites for "+format+" format!");
        }
        iw = (ImageWriter)i.next();

        i = ImageIO.getImageReadersByFormatName(format);
        if (!i.hasNext()) {
            throw new RuntimeException("No available ImageReaders for " +format+" format!");
        }

        ir = (ImageReader)i.next();
    }
 
Example 14
Project: openjdk-jdk10   File: WriteProgressListenerTest.java   View Source Code Vote up 5 votes
public void doTest() {
    try {
        System.out.println("Progress test for " + compression_type);
        BufferedImage bi = new BufferedImage(20, 300, BufferedImage.TYPE_INT_RGB);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baos);

        Iterator iter = ImageIO.getImageWritersByFormatName(format);
        if (!iter.hasNext()) {
            throw new RuntimeException("No available writer for " + format);
        }
        ImageWriter writer = (ImageWriter)iter.next();

        writer.setOutput(ios);
        writer.addIIOWriteProgressListener(listener);

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

        ImageWriteParam param = writer.getDefaultWriteParam();

        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionType(compression_type);


        writer.write(null, iio_img, param);

        if (!listener.isTestPassed) {
            throw new RuntimeException("Test for " + compression_type + " does not finish correctly!");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Project: openjdk-jdk10   File: BMPPluginTest.java   View Source Code Vote up 5 votes
private static void init() {

        Iterator i = ImageIO.getImageWritersByFormatName(format);
        if (!i.hasNext()) {
            throw new RuntimeException("No available ImageWrites for "+format+" format!");
        }
        iw = (ImageWriter)i.next();

        i = ImageIO.getImageReadersByFormatName(format);
        if (!i.hasNext()) {
            throw new RuntimeException("No available ImageReaders for " +format+" format!");
        }

        ir = (ImageReader)i.next();
    }
 
Example 16
Project: openjdk-jdk10   File: PngDitDepthTest.java   View Source Code Vote up 5 votes
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 17
Project: litiengine   File: ImageSerializer.java   View Source Code Vote up 4 votes
private static boolean canWriteFormat(final String formatName) {
  final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatName);
  return iter.hasNext();
}
 
Example 18
Project: openjdk-jdk10   File: WbmpDefaultImageMetadataTest.java   View Source Code Vote up 4 votes
public WbmpDefaultImageMetadataTest(String format) {
    try {
        bimg = new BufferedImage(200, 200, bimg.TYPE_INT_RGB);
        Graphics gg = bimg.getGraphics();
        gg.setColor(Color.red);
        gg.fillRect(50, 50, 100, 100);

        Iterator it = ImageIO.getImageWritersByFormatName(format);
        if (it.hasNext()) {
            writer = (ImageWriter) it.next();
        }
        if (writer == null) {
            throw new RuntimeException("No writer available for the given format."
                                       + " Test failed.");
        }
        writeParam = writer.getDefaultWriteParam();

        System.out.println("Testing Image Metadata for "+format+"\n");
        imageData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(bimg), writeParam);
        if (imageData == null) {
            System.out.println("return value is null. No default image metadata is associated with "+format+" writer");
            throw new RuntimeException("Default image metadata is null."
                                       + " Test failed.");
        }
        int j = 0;
        String imageDataNames[] = null;
        if(imageData != null) {
            System.out.println("Is standard metadata format supported (Image) ? "+
                               imageData.isStandardMetadataFormatSupported() );
            imageDataNames = imageData.getMetadataFormatNames();
            System.out.println("\nAll supported Metadata Format Names\n");
            if(imageDataNames!=null){
                for(j=0; j<imageDataNames.length; j++)  {
                    System.out.println("FORMAT NAME: "+imageDataNames[j]);
                    if (imageDataNames[j].equals(imageData.getNativeMetadataFormatName())) {
                        System.out.println("This is a Native Metadata format\n");
                    } else {
                        System.out.println("\n");
                    }
                    System.out.println("");
                    System.out.println("IIOImageMetadata DOM tree for "+imageDataNames[j]);
                    System.out.println("");
                    Node imageNode = imageData.getAsTree(imageDataNames[j]);
                    displayMetadata(imageNode);
                    System.out.println("\n\n");
                }
            }
        }
    }catch(Exception e){
        e.printStackTrace();
        throw new RuntimeException("Exception was thrown."
                                   + " Test failed.");
    }
}
 
Example 19
Project: openjdk-jdk10   File: BmpDefaultImageMetadataTest.java   View Source Code Vote up 4 votes
public BmpDefaultImageMetadataTest(String format) {
    try {
        bimg = new BufferedImage(200, 200, bimg.TYPE_INT_RGB);
        Graphics gg = bimg.getGraphics();
        gg.setColor(Color.red);
        gg.fillRect(50, 50, 100, 100);

        Iterator it = ImageIO.getImageWritersByFormatName(format);
        if (it.hasNext()) {
            writer = (ImageWriter) it.next();
        }
        if (writer == null) {
            throw new RuntimeException("No writer available for the given format."
                                       + " Test failed.");
        }
        writeParam = writer.getDefaultWriteParam();

        System.out.println("Testing Image Metadata for "+format+"\n");
        imageData = writer.getDefaultImageMetadata(new ImageTypeSpecifier(bimg), writeParam);
        if (imageData == null) {
            System.out.println("return value is null. No default image metadata is associated with "+format+" writer");
            throw new RuntimeException("Default image metadata is null."
                                       + " Test failed.");
        }
        int j = 0;
        String imageDataNames[] = null;
        if(imageData != null) {
            System.out.println("Is standard metadata format supported (Image) ? "+
                               imageData.isStandardMetadataFormatSupported() );
            imageDataNames = imageData.getMetadataFormatNames();
            System.out.println("\nAll supported Metadata Format Names\n");
            if(imageDataNames!=null){
                for(j=0; j<imageDataNames.length; j++)  {
                    System.out.println("FORMAT NAME: "+imageDataNames[j]);
                    if (imageDataNames[j].equals(imageData.getNativeMetadataFormatName())) {
                        System.out.println("This is a Native Metadata format\n");
                    } else {
                        System.out.println("\n");
                    }
                    System.out.println("");
                    System.out.println("IIOImageMetadata DOM tree for "+imageDataNames[j]);
                    System.out.println("");
                    Node imageNode = imageData.getAsTree(imageDataNames[j]);
                    displayMetadata(imageNode);
                    System.out.println("\n\n");
                }
            }
        }
    }catch(Exception e){
        e.printStackTrace();
        throw new RuntimeException("Exception was thrown."
                                   + " Test failed.");
    }
}