Determining If an Image Format Can Be Read or Written - Java 2D Graphics

Java examples for 2D Graphics:Image

Description

Determining If an Image Format Can Be Read or Written

Demo Code


import java.io.File;
import java.util.Iterator;

import javax.imageio.ImageIO;

public class Main {
  public void m() throws Exception {
    boolean b;/*from ww w. j ava 2s. c o m*/

    // Check availability using a format name
    b = canReadFormat("foo"); // false
    b = canReadFormat("gif"); // true
    b = canReadFormat("giF"); // true
    b = canWriteFormat("foo"); // false
    b = canWriteFormat("gif"); // false
    b = canWriteFormat("PNG"); // true
    b = canWriteFormat("jPeG"); // true

    // Get extension from a File object
    File f = new File("image.jpg");
    String s = f.getName().substring(f.getName().lastIndexOf('.') + 1);

    // Check availability using a filename extension
    b = canReadExtension(s);
    b = canWriteExtension(s);

    // Check availability using a MIME type
    b = canReadMimeType("image/jpg"); // false
    b = canReadMimeType("image/jpeg"); // true
    b = canWriteMimeType("image/gif"); // false
    b = canWriteMimeType("image/jPeg"); // true
  }

  // Returns true if the specified format name can be read
  public static boolean canReadFormat(String formatName) {
    Iterator iter = ImageIO.getImageReadersByFormatName(formatName);
    return iter.hasNext();
  }

  // Returns true if the specified format name can be written
  public static boolean canWriteFormat(String formatName) {
    Iterator iter = ImageIO.getImageWritersByFormatName(formatName);
    return iter.hasNext();
  }

  // Returns true if the specified file extension can be read
  public static boolean canReadExtension(String fileExt) {
    Iterator iter = ImageIO.getImageReadersBySuffix(fileExt);
    return iter.hasNext();
  }

  // Returns true if the specified file extension can be written
  public static boolean canWriteExtension(String fileExt) {
    Iterator iter = ImageIO.getImageWritersBySuffix(fileExt);
    return iter.hasNext();
  }

  // Returns true if the specified mime type can be read
  public static boolean canReadMimeType(String mimeType) {
    Iterator iter = ImageIO.getImageReadersByMIMEType(mimeType);
    return iter.hasNext();
  }

  // Returns true if the specified mime type can be written
  public static boolean canWriteMimeType(String mimeType) {
    Iterator iter = ImageIO.getImageWritersByMIMEType(mimeType);
    return iter.hasNext();
  }
}

Related Tutorials