user903772
user903772

Reputation: 1562

Bufferedimage into circle shape

I have a buffered image from byte array. How do I make the image into a circle? Crop? I don't want a circle, I want the orginal image to become circle shape and display

 def bufferedImage = imgSvc.convertByteArrayToBufferedImage(crop.image)

Upvotes: 1

Views: 9772

Answers (4)

Jan
Jan

Reputation: 432

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageCircle {
    static Image img;
    static String imgFile =
            "yourFileName.jpg";
    public static void main(String[] args) {
        try {
            img = ImageIO.read(new File(imgFile));
        } catch (IOException fne) {
            fne.printStackTrace();
        }
        int width = img.getWidth(null);
        int height = img.getHeight(null);

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bi.createGraphics();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        int circleDiameter = Math.min(width,height);
        Ellipse2D.Double circle = new Ellipse2D.Double(0,0,circleDiameter,circleDiameter);
        g2.setClip(circle);
        g2.drawImage(img,0,0,null);
        try {
            ImageIO.write(bi, "PNG", new File("yourFileName.png"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Upvotes: 0

johanvs
johanvs

Reputation: 4393

If bufferedImage is squared, then with this code :

int width = bufferedImage.getWidth();
BufferedImage circleBuffer = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = circleBuffer.createGraphics();
g2.setClip(new Ellipse2D.Float(0, 0, width, width));
g2.drawImage(bufferedImage, 0, 0, width, width, null);

you get a circular cropped image in circleBuffer

Upvotes: 4

Rahul
Rahul

Reputation: 299

this can help

    g.setClip(new Ellipse2D.Float(x, y, w, h));
    g.drawImage(yourBufferedImage, x, y, w, h, null);

Upvotes: 1

lbalazscs
lbalazscs

Reputation: 17809

You can use setClip() method of the Graphics class to restrict the drawing area of a graphics context to a specific region. The drawback of this is that this clipping will not be anti-aliased.

There are some more advanced tricks to achieve a better-looking result, see the answers to the following questions:

Drawing a part of an image (Java)

How to make a rounded corner image in Java

Upvotes: 0

Related Questions