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

The following examples show how to use javax.imageio.ImageIO#getImageWritersBySuffix() . 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Test
    public void lossless() throws Exception {
        File f = File.createTempFile("test-jpeg2000-lossless", ".jp2");
        f.deleteOnExit();        
        Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jp2");
        assertTrue(writers.hasNext());
        ImageWriter writer = writers.next();
        J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam();
        writeParams.setLossless(true);
//        writeParams.setFilter(J2KImageWriteParam.FILTER_53);
//        writeParams.setEncodingRate(64.0f);
//        writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//        writeParams.setCompressionType("JPEG2000");
//        writeParams.setCompressionQuality(1.0f);
        
        ImageOutputStream ios = ImageIO.createImageOutputStream(f);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(image, null, null), writeParams);
        writer.dispose();
        ios.close();
        assertTrue("Expected file size > 128kB", f.length() > 128*1024);
        //System.out.println(f.length());
        BufferedImage read = ImageIO.read(f);
        assertEquals(SIZE, read.getWidth());
    }
 
Example 2
Source Project: netbeans   File: ScreenshotComponent.java    License: Apache License 2.0 6 votes vote down vote up
void save(File file) throws IOException {
    ImageWriter iw = null;
    String name = file.getName();
    int i = name.lastIndexOf('.');
    if (i >= 0) {
        String extension = name.substring(i + 1);
        Iterator<ImageWriter> imageWritersBySuffix = ImageIO.getImageWritersBySuffix(extension);
        if (imageWritersBySuffix.hasNext()) {
            iw = imageWritersBySuffix.next();
        }
    }
    if (iw != null) {
        file.delete();
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);
        try {
            iw.write((BufferedImage) image);
        } finally {
            iw.dispose();
            ios.flush();
            ios.close();
        }
    } else {
        ImageIO.write((BufferedImage) image, "PNG", file);
    }
}
 
Example 3
Source Project: gcs   File: JPEGFactory.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private static ImageWriter getJPEGImageWriter() throws IOException
{
    ImageWriter writer = null;
    Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jpeg");
    while (writers.hasNext())
    {
        if (writer != null)
        {
            writer.dispose();
        }
        writer = writers.next();
        if (writer == null)
        {
            continue;
        }
        // PDFBOX-3566: avoid CLibJPEGImageWriter, which is not a JPEGImageWriteParam
        if (writer.getDefaultWriteParam() instanceof JPEGImageWriteParam)
        {
            return writer;
        }
    }
    throw new IOException("No ImageWriter found for JPEG format");
}
 
Example 4
Source Project: wenku   File: FileConverHandler.java    License: MIT License 6 votes vote down vote up
/**
 * 
 * 将指定pdf文件的首页转换为指定路径的缩略图
 * @param pdfFilePath 原文件路径,例如d:/test.pdf
 * @param imagePath 图片生成路径,例如 d:/test-1.jpg
 * @param zoom 缩略图显示倍数,1表示不缩放,0.3则缩小到30%
 */
public void tranfer(String pdfFilePath, String imagePath, float zoom) throws PDFException, PDFSecurityException, IOException {
    float rotation = 0f;

    Document document = new Document();
    document.setFile(pdfFilePath);

    BufferedImage img = (BufferedImage) document.getPageImage(0, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, zoom);

    Iterator<?> iter = ImageIO.getImageWritersBySuffix(FileExtConstant.FILETYPE_PNG);
    ImageWriter writer = (ImageWriter) iter.next();
    File outFile = new File(imagePath);

    if (!new File(FilenameUtils.getFullPath(imagePath)).exists()) {
        new File(FilenameUtils.getFullPath(imagePath)).mkdirs();
    }
    FileOutputStream out = new FileOutputStream(outFile);
    ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
    writer.setOutput(outImage);
    writer.write(new IIOImage(img, null, null));

    IOUtils.closeQuietly(out);
    IOUtils.closeQuietly(outImage);
}
 
Example 5
public Object load(AssetInfo info) throws IOException {
    if (ImageIO.getImageWritersBySuffix(info.getKey().getExtension()) != null){
        
        boolean flip = ((TextureKey) info.getKey()).isFlipY();
        InputStream in = null;
        try {
            in = info.openStream();
            Image img = load(in, flip);
            return img;
        } finally {
            if (in != null){
                in.close();
            }
        }
    }
    return null;
}
 
Example 6
@Test
    public void lossyWrite() throws Exception {
        File f = File.createTempFile("test-jpeg2000-lossy", ".jp2");
        f.deleteOnExit();
        Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix("jp2");
        assertTrue(writers.hasNext());
        ImageWriter writer = writers.next();
        J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam();
        writeParams.setLossless(false);
        writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        writeParams.setCompressionType("JPEG2000");
//        writeParams.setFilter(J2KImageWriteParam.FILTER_97);


        
        writeParams.setCompressionQuality(0.0f);
        writeParams.setEncodingRate(0.5f);
        ImageOutputStream ios = ImageIO.createImageOutputStream(f);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(image, null, null), writeParams);
        writer.dispose();
        ios.close();
        assertTrue("Expected file size < 1MB", f.length() < 128*1024);
        //System.out.println(f.length());
        BufferedImage read = ImageIO.read(f);
        assertEquals(SIZE, read.getWidth());
    }
 
Example 7
Source Project: BlockMap   File: GifSequenceWriter.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the first available GIF ImageWriter using ImageIO.getImageWritersBySuffix("gif").
 * 
 * @return a GIF ImageWriter object
 * @throws IIOException
 *             if no GIF image writers are returned
 */
private static ImageWriter getWriter() throws IIOException {
	Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
	if (!iter.hasNext()) {
		throw new IIOException("No GIF Image Writers Exist");
	} else {
		return iter.next();
	}
}
 
Example 8
Source Project: graphicsfuzz   File: GifSequenceWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first available GIF ImageWriter using
 * ImageIO.getImageWritersBySuffix("gif").
 *
 * @return a GIF ImageWriter object
 * @throws IIOException if no GIF image writers are returned
 */
private static ImageWriter getWriter() throws IIOException {
  Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
  if (!iter.hasNext()) {
    throw new IIOException("No GIF Image Writers Exist");
  } else {
    return iter.next();
  }
}
 
Example 9
private static void testGetWriterFileSuffixes() {
    String[] suffixes = ImageIO.getWriterFileSuffixes();
    for (String s : suffixes) {
        Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix(s);
        if (!it.hasNext()) {
            throw new RuntimeException("getWriterFileSuffixes returned " +
                                       "an unknown suffix: " + s);
        }
    }
}
 
Example 10
private static void testGetWriterFileSuffixes() {
    String[] suffixes = ImageIO.getWriterFileSuffixes();
    for (String s : suffixes) {
        Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix(s);
        if (!it.hasNext()) {
            throw new RuntimeException("getWriterFileSuffixes returned " +
                                       "an unknown suffix: " + s);
        }
    }
}
 
Example 11
Source Project: basicv2   File: GraphicsDevice.java    License: The Unlicense 5 votes vote down vote up
/**
 * Saves the current image into a PNG file.
 * 
 * @param machine the machine
 * @param name    the name of the target file
 */
public void save(Machine machine, String name) {
	try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name));
			ImageOutputStream ios = ImageIO.createImageOutputStream(bos)) {
		Iterator<ImageWriter> itty = ImageIO.getImageWritersBySuffix("png");
		if (itty.hasNext()) {
			ImageWriter iw = (ImageWriter) itty.next();
			ImageWriteParam iwp = iw.getDefaultWriteParam();
			iw.setOutput(ios);
			iw.write(null, new IIOImage((RenderedImage) getScreen(), null, null), iwp);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 12
Source Project: basicv2   File: Graphics.java    License: The Unlicense 5 votes vote down vote up
/**
 * Saves an image as PNG file.
 * 
 * @param bi the image
 * @param os the output stream. It will be closed when this method terminates.
 */
public static void savePng(BufferedImage bi, OutputStream os) {
	try (BufferedOutputStream bos = new BufferedOutputStream(os);
			ImageOutputStream ios = ImageIO.createImageOutputStream(bos)) {
		Iterator<ImageWriter> itty = ImageIO.getImageWritersBySuffix("png");
		if (itty.hasNext()) {
			ImageWriter iw = (ImageWriter) itty.next();
			ImageWriteParam iwp = iw.getDefaultWriteParam();
			iw.setOutput(ios);
			iw.write(null, new IIOImage((RenderedImage) bi, null, null), iwp);
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 13
Source Project: binnavi   File: GraphExporters.java    License: Apache License 2.0 5 votes vote down vote up
public static ImageOutputHandler createPNGOutputHandler() {
  // Use the services of Java Image I/O API to see whether there is an image
  // writer registered that is capable of writing the PNG graphics file format.
  final Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix("png");
  final ImageWriter iw = it.hasNext() ? it.next() : null;

  // Return an image output handler that serves as an adapter to this image
  // writer.
  return iw == null ? null : new ImageIoOutputHandler(iw);
}
 
Example 14
private String getImageExtension(String imageUrl) {
    String ext = imageUrl.substring(imageUrl.lastIndexOf('.') + 1);
    java.util.Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix(ext);
    if (it.next() != null) {
        return ext;
    } else {
        return "jpg";
    }
}
 
Example 15
/**
 * Get an image extension from the image url
 * @param imageUrl
 * @return
 */
public static String getImageExtension(String imageUrl) {
    String ext = imageUrl.substring(imageUrl.lastIndexOf('.') + 1);
    try {
        java.util.Iterator<ImageWriter> it =
                ImageIO.getImageWritersBySuffix(ext);
        if (it.next() != null) {
            return ext;
        }
    } catch (NoSuchElementException ex) {
        return DEFAULT_IMG_EXTENSION;
    }
    return DEFAULT_IMG_EXTENSION;
}
 
Example 16
Source Project: shrink-pdf   File: ShrinkPDF.java    License: MIT License 5 votes vote down vote up
/**
 * Shrink a PDF
 * @param f {@code File} pointing to the PDF to shrink
 * @param compQual Compression quality parameter. 0 is
 *                 smallest file, 1 is highest quality.
 * @return The compressed {@code PDDocument}
 * @throws FileNotFoundException
 * @throws IOException 
 */
private PDDocument shrinkMe() 
        throws FileNotFoundException, IOException {
     if(compQual < 0)
         compQual = compQualDefault;
     final RandomAccessBufferedFileInputStream rabfis = 
             new RandomAccessBufferedFileInputStream(input);
     final PDFParser parser = new PDFParser(rabfis);
     parser.parse();
     final PDDocument doc = parser.getPDDocument();
     final PDPageTree pages = doc.getPages();
     final ImageWriter imgWriter;
     final ImageWriteParam iwp;
     if(tiff) {
         final Iterator<ImageWriter> tiffWriters =
               ImageIO.getImageWritersBySuffix("png");
         imgWriter = tiffWriters.next();
         iwp = imgWriter.getDefaultWriteParam();
         //iwp.setCompressionMode(ImageWriteParam.MODE_DISABLED);
     } else {
         final Iterator<ImageWriter> jpgWriters = 
               ImageIO.getImageWritersByFormatName("jpeg");
         imgWriter = jpgWriters.next();
         iwp = imgWriter.getDefaultWriteParam();
         iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
         iwp.setCompressionQuality(compQual);
     }
     for(PDPage p : pages) {
          scanResources(p.getResources(), doc, imgWriter, iwp);
     }
     return doc;
}
 
Example 17
public static void main(String[] args) {
    Locale.setDefault(Locale.US);

    final BufferedImage image
        = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);

    final Graphics2D g2d = image.createGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                             RenderingHints.VALUE_RENDER_QUALITY);
        g2d.scale(2.0, 2.0);

        g2d.setColor(Color.red);
        g2d.draw(new Rectangle2D.Float(10, 10, 100, 100));
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle2D.Float(12, 12, 98, 98));
        g2d.setColor(Color.green);
        g2d.setFont(new Font(Font.SERIF, Font.BOLD, 14));

        for (int i = 0; i < 15; i++) {
            g2d.drawString("Testing Compression ...", 20, 20 + i * 16);
        }

        final String[] fileSuffixes = ImageIO.getWriterFileSuffixes();

        final Set<String> testedWriterClasses = new HashSet<String>();

        for (String suffix : fileSuffixes) {

            if (!IGNORE_FILE_SUFFIXES.contains(suffix)) {
                final Iterator<ImageWriter> itWriters
                    = ImageIO.getImageWritersBySuffix(suffix);

                final ImageWriter writer;
                final ImageWriteParam writerParams;

                if (itWriters.hasNext()) {
                    writer = itWriters.next();

                    if (testedWriterClasses.add(writer.getClass().getName())) {
                        writerParams = writer.getDefaultWriteParam();

                        if (writerParams.canWriteCompressed()) {
                            testCompression(image, writer, writerParams, suffix);
                        }
                    }
                } else {
                    throw new RuntimeException("Unable to get writer !");
                }
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException("IO failure", ioe);
    }
    finally {
        g2d.dispose();
    }
}
 
Example 18
/**
 * Method to get the list of supported file extensions for writing
 *
 * @return List of supported file extensions for writing
 * @throws OpenStegoException
 */
@Override
public List<String> getWritableFileExtensions() throws OpenStegoException {
    if (writeFormats != null) {
        return writeFormats;
    }

    super.getWritableFileExtensions();
    String format = null;
    String[] compTypes = null;
    Iterator<ImageWriter> iter = null;
    ImageWriteParam writeParam = null;

    for (int i = writeFormats.size() - 1; i >= 0; i--) {
        format = writeFormats.get(i);
        iter = ImageIO.getImageWritersBySuffix(format);
        while (iter.hasNext()) {
            writeParam = (iter.next()).getDefaultWriteParam();
            try {
                writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                compTypes = writeParam.getCompressionTypes();
                if (compTypes.length > 0) {
                    writeParam.setCompressionType(compTypes[0]);
                }
            } catch (UnsupportedOperationException uoEx) {
                // Compression not supported
                break;
            }

            // Only lossless image compression is supported
            if (writeParam.isCompressionLossless()) {
                break;
            }
            writeFormats.remove(i);
        }
    }

    // Expicilty removing GIF and WBMP formats, as they use unsupported color models
    writeFormats.remove("gif");
    writeFormats.remove("wbmp");
    // Expicilty removing TIF(F) formats, as they are not working correctly - TODO check why
    writeFormats.remove("tif");
    writeFormats.remove("tiff");

    return writeFormats;
}
 
Example 19
/**
 * Returns the first available GIF ImageWriter using
 * ImageIO.getImageWritersBySuffix("gif").
 * 
 * @return a GIF ImageWriter object
 * @throws IIOException
 *             if no GIF image writers are returned
 */
private static ImageWriter getWriter() throws IIOException {
	Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
	if (!iter.hasNext()) {
		throw new IIOException("No GIF Image Writers Exist");
	}
	return iter.next();
}