6

I am very new to image processing. I have a PNG image (read using ImageIO.read()) that yields BufferedImage.TYPE_CUSTOM when I call getType() on it.

BufferedImage bi = ImageIO.read(new URL("file:/C:/samp1.png"));
int type =bi.getType(); //TYPE_CUSTOM for samp1.png

Now I would like to convert it to one of the following models:

  1. TYPE_USHORT_GRAY
  2. TYPE_3BYTE_BGR
  3. TYPE_BYTE_GRAY
  4. TYPE_INT_RGB
  5. TYPE_INT_ARGB

The above needs to be done to process the image further using a library that recognises only the above types.

How do I convert from TYPE_CUSTOM color model to other models?

Any help/pointers would be much appreciated. If there aren't any existing library to do this, any link/post to steps/algorithm would be great.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Neville
  • 97
  • 1
  • 5

2 Answers2

12

Try this:

public static BufferedImage convert(BufferedImage src, int bufImgType) {
    BufferedImage img= new BufferedImage(src.getWidth(), src.getHeight(), bufImgType);
    Graphics2D g2d= img.createGraphics();
    g2d.drawImage(src, 0, 0, null);
    g2d.dispose();
    return img;
}
eric2323223
  • 3,518
  • 8
  • 40
  • 55
  • 1
    this answer works the best, the answer marked as acceptable only creates a blank image. You still have to fill the data in it. –  Oct 08 '16 at 00:13
0

Have you tried this?

BufferedImage rgbImg = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
Charles Ma
  • 47,141
  • 22
  • 87
  • 101
  • 5
    Doesn't this just create a new blank image? You and Eric seem to have chosen the same method, using the graphics object to redraw the image, even if it looks like you only wrote the first line of it. I'm convinced there's a faster way, perhaps buried in the AWT files or something you would need to implement yourself, converting the WritableRaster returned by getData(). (That is, unless drawImage takes these shortcuts as it is, but I doubt that.) Any ideas? – John P Oct 19 '13 at 12:59