0

We have some old code (Java 1.2) that heavily uses JAI_IO for image manipulation. We're now Java 1.6 and so we no longer need this. First off, should I still be using BufferedImage? Or is there a better class? What I fundamentally need to do is:

  1. Convert a bitmap from one format to another (usually to PNG).
  2. Get the metadata of an image: size in pixels, DPI, & bitmap format.
  3. Resize an image.
  4. Draw an image to a Graphics2D object.
  5. walk the pixels in a bitmap to read and/or set them (this can be slow - rarely used).

And I know the answer is "ha ha ha" but is there a class that will convert metafiles to a bitmap?

thanks - dave

David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • What would make a class "better" than `BufferedImage`? What issues do you have with the existing setup? For Java 6, I would probably use the standard `javax.imageio` API. Optionally use the JAI ImageIO plugins, if you need support for the formats it contains. – Harald K Oct 16 '14 at 10:34
  • @haraldK - What we need that BufferedImage does not appear to have are: 1) convert a bitmap to another format, 2) DPI settings for a bitmap, 3) Get format of bitmap. – David Thielen Oct 16 '14 at 11:41
  • The `javax.imageio` API is good for those tasks. `BufferedImage` just represents pixel data. There's a class `IIOImage` that contains metadata (`IIOMetadata`), like file format details and DPI, along with the pixel data (in the form of a `BufferedImage`, or its superclass `RenderedImage`). – Harald K Oct 16 '14 at 11:45
  • @haraldK - how can we use IIOImage to get the DPI and bitmap format? thanks - dave – David Thielen Oct 16 '14 at 22:03

1 Answers1

0

I'd use ImageIO and the javax.imageio API to read the image and adjust DPI/PPI (see below for an example), and probably a package like imgscalr or thumbnailator to resize, depending on your needs/preferences.

The code goes something like:

// input is typically a File or InputStream

// Wrap in ImageInputStream
ImageInputStream stream = ImageIO.createImageInputStream(input);

// Obtain reader
ImageReader reader = ImageIO.getImageReaders(stream).next(); // In real code, test for presence
reader.setInput(stream);

String formatName = reader.getFormatName(); // Get the format name

ImageReadParam param = reader.getDefaultReadParam();

// ... modify params as you see fit, or just go with defaults

IIOImage image = reader.readAll(0, param);

RenderedImage red = image.getRenderedImage();
BufferedImage buf = (BufferedImage) red; // In real code, test if it's safe, or convert

// .. pas buf along to imgscalr or thumnailator

image.setRenderedImage(buf);

IIOMetadata meta = image.getMetadata();

// ... modify DPI in meta data

ImageWriter writer = reader.getImageWriter();
writer.write(null, image, null); // Or modify write params if you need (last parameter)

You can see an example of modifying the DPI for JPEG files here.

Community
  • 1
  • 1
Harald K
  • 26,314
  • 7
  • 65
  • 111