Reputation:
I want to circle crop image File with transparent background and save it again. This is the code that works in android but I am new in JavaFX. this code crop image from the center like a circle. I want to do this in JavaFX!
public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius, false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(), finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(), finalBitmap.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f,
finalBitmap.getWidth() / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, rect, paint);
return output;
}
Upvotes: 1
Views: 431
Reputation:
I find solution myself and put it here.
private Image getRoundImage(Image image, int radius) {
int width = (int) image.getWidth();
int height = (int) image.getHeight();
WritableImage wImage = new WritableImage(radius * 2, radius * 2);
PixelWriter pixelWriter = wImage.getPixelWriter();
PixelReader pixelReader = image.getPixelReader();
Color c1 = new Color(0, 0, 0, 0);
int w = (width / 2);
int h = (height / 2);
int r = radius * radius;
for (int i = (width / 2) - radius, k = 0; i < w + radius; i++, k++)
for (int j = (height / 2) - radius, b = 0; j < h + radius; j++, b++) {
if ((i - w) * (i - w) + (j - h) * (j - h) > r)
pixelWriter.setColor(k, b, c1);
else
pixelWriter.setColor(k, b, pixelReader.getColor(i, j));
}
return wImage;
}
Upvotes: 2
Reputation: 4258
Node
's Clip property:
Specifies a Node to use to define the clipping shape for this Node. This clipping Node is not a child of this Node in the scene graph sense. Rather, it is used to define the clip for this Node.
Here is how you can use it to achieve your goal:
private static Image getRoundedImage(Image image, double radius) {
Circle clip = new Circle(image.getWidth() / 2, image.getHeight() / 2, radius);
ImageView imageView = new ImageView(image);
imageView.setClip(clip);
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
return imageView.snapshot(parameters, null);
}
Upvotes: 2