views:

209

answers:

2

We're using JAI (https://jai-imageio.dev.java.net/) to scale and crop images in Java. We would like to create round corners on our images. How do we do that?

The images are JPG and PNG. I would think it's easier to do this with JPGs?

The image is a PlanarImage from JAI

PlanarImage src = JAI.create(...,...);

which can be transformed to a java.awt.Graphics object

Has anyone done this before?

A: 

What prevents you from drawing whatever corners you like onto the Graphics object obtained from the Image? I'm not really sure what your "round corners" are supposed to look like, but you can perform all reasonable paint operations on the Graphics object.

jarnbjo
Yes, I figured some kind of mask is needed to "cut out" the corners. But how?
Tommy
+2  A: 

PNG supports a transparent alpha channel, but JPG does not. So, for JPG you would have to also pick a color to paint the "invisible" part of the rectangle for the rounded corners.

There is a class java.awt.geom.RoundRectangle2D available to do this:

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    RoundRectangle2D rr = new RoundRectangle2D.Float(50, 50, 200, 100, 10, 10);
    g2d.draw(rr);
}

The Float() method of the class RoundRectangle2D takes six arguments:

  • The first two represent the location of the upper left corner.
  • Arguments 3 and 4 represent the width and height of the rounded rectangle.
  • The last two arguments represent the width and height of the arc drawn in the corners.

So, draw a rounded rectangle that will just contain the image you want to have rounded corners and then either overlay or use a mask to get the desired effect.

shadit