perlimagemagickperlmagick

Image::Magick draw a blurred circle


Have an background image. (for this example the mesh.png)

To the image need add one circle, with blurred border. Currently have this:

use 5.014;
use warnings;
use Image::Magick;

my $bgimg = Image::Magick->new();
$bgimg->Read('png:mesh.png');

draw_my_circle($bgimg, 150, 150, 100);  #img, center_x, center_y, radius
$bgimg->Write("win:");  #display

sub draw_my_circle {
    my($img, $center_x, $center_y, $radius) = @_;
    $img->Draw(
        fill => 'black',
        points => "$center_x,$center_y @{[$center_x + $radius]},$center_y",
        primitive => 'circle',
    );
}

This produces the next image:

black circle on a mesh

but I need a circle with "blurred edge", like the next (created manually)

blurred circle on the mesh

Can anyone help how to get a such blurred circle with Image::Magick?

If someone want the mesh.png, it is created with the next script:

use 5.014;
use warnings;
use Image::Magick;

my $image=Image::Magick->new(size=>'300x300');
$image->Read('xc:white');

for( my $i=0; $i < 300; $i += 10 ) {
    $image->Draw(primitive=>'line',points=>"$i,0 $i,300",stroke=>"#ccf");
    $image->Draw(primitive=>'line',points=>"0,$i 300,$i",stroke=>"#ccf");
}
$image->Write('png:mesh.png');

Solution

  • You can use Gaussian blur, like this:

    #!/usr/bin/perl
    use 5.014;
    use strict;
    use warnings;
    use Image::Magick;
    my $x;
    my $circle;
    my $mesh;
    
    $mesh=Image::Magick->new(size=>'300x300');
    $mesh->Read('xc:white');
    
    for( my $i=0; $i < 300; $i += 10 ) {
        $mesh->Draw(primitive=>'line',points=>"$i,0 $i,300",stroke=>"#ccf");
        $mesh->Draw(primitive=>'line',points=>"0,$i 300,$i",stroke=>"#ccf");
    }
    $mesh->Write(filename=>'mesh.png');
    
    $circle=Image::Magick->new(size=>'300x300');
    $circle->ReadImage('xc:transparent');
    $circle->Draw(
            fill => 'black',
            points => "150,150 @{[250]},100",
            primitive => 'circle',
        );
    $circle->GaussianBlur('10x50');
    $circle->Write(filename=>'circle.png');
    
    $mesh->Composite(image => $circle, qw(compose SrcAtop  gravity Center));
    $mesh->Write(filename=>'out.png');