Skip to content

Instantly share code, notes, and snippets.

@vividsnow
Created July 27, 2017 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vividsnow/b746c97bf93894a9998645768295c28f to your computer and use it in GitHub Desktop.
Save vividsnow/b746c97bf93894a9998645768295c28f to your computer and use it in GitHub Desktop.
imager rounded corner mask with transparency
sub rounded_mask {
my ($img, $rad) = @_;
state $ss = 4; # subsample smooth
my $srad = int $rad*$ss;
my $corner = Imager->new(xsize => $srad, ysize => $srad, channels => 1)
->arc(qw'x 0 y 0 d1 0 d2 90', r => $srad - $ss/2)
->scale(scalefactor => 1/$ss);
my ($w, $h) = ($img->getwidth, $img->getheight);
my $mask = Imager->new(xsize => $w, ysize => $h, channels => 1);
$mask->box(box => [$rad, 0, $w - 1 - $rad, $h - 1], filled => 1);
$mask->box(box => [0, $rad, $w - 1, $h - 1 - $rad], filled => 1);
$mask->paste(left => $w - $rad, top => $h - $rad, img => $corner); # br
$mask->paste(top => $h - $rad, img => $corner->flip(qw'dir h')); # bl
$mask->paste(img => $corner->flip(qw'dir v')); # tl
$mask->paste(left => $w - $rad, img => $corner->flip(qw'dir h')); # tr
my $out = Imager->new(xsize => $w, ysize => $h, channels => 4);
$out->compose(src => $img, mask => $mask);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment