-1

I need a function/method that can mold(crop and resize) an imported (.png format) image into a circle of exact 150x150 pixels and it should keep transparency. I have searched all over internet, also I have my own code but I think its completely useless. I need this function for a code I am using to make GUI of a social-media app database.

private ImageIcon logo = new ImageIcon(getClass().getResource("/test/test200x200.png"));
toCircle(logo);

I need the code for the following function:

public ImageIcon toCircle(ImageIcon icon)
{
    //code
    return icon;
 }

This function should convert this picture:

To this:

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Ammar H Sufyan
  • 97
  • 1
  • 3
  • 13
  • 1
    StackOverflow is not a code-request site. It is a question-and-answer site where you present problems that you face when programming, including all the research you have done and your best effort at the code, and we give an answer to your specific problem. Please read [ask]. – RealSkeptic Feb 26 '17 at 10:34
  • I'm voting to close this question as off-topic because it is a request for code rather than a question. – RealSkeptic Feb 26 '17 at 10:34
  • i am sorry i have my code but i thought it would make the question confusing – Ammar H Sufyan Feb 26 '17 at 10:55

2 Answers2

4
  • Create a new transparent image
  • Get a Graphics object from the image.
  • Set a clip for the graphics object.
  • Paint the PNG format image.

See also this answer that uses a clipped region.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

An alternative approach, that might be more straight-forward to implement for this use case, is:

  • Create a transparent BufferedImage the size of your icon
  • Create Graphics2D from image, set hints for antialias
  • Fill a circle the size of your background circle
  • Draw the image on top of your circle, using AlphaComposite.SrcIn

Something like:

public Icon toCircle(ImageIcon logo) {
    BufferedImage image = new BufferedImage(150, 150); // Assuming logo 150x150
    Graphics2D g = image.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.fillOval(1, 1, 148, 148); // Leaving some room for antialiasing if needed
    g.setComposite(AlphaComposite.SrcIn);
    g.drawImage(logo.getImage(), 0, 0, null);
    g.dispose();

    return new ImageIcon(image);
}
Harald K
  • 26,314
  • 7
  • 65
  • 111