use POSIX;

sub cropToSquare
{
    my ($image, $n) = @_;
    ($origWidth, $origHeight) = $image->Get('width', 'height');
    
    $square = Image::Magick->new;
    $square->Set(size => $origWidth . 'x' . $origHeight);    
    $square->ReadImage('xc:white');
    $square->Composite(image => $image, compose => 'Copy', x => 0, y => 0);
    
    $w = $n;
    $h = $n;
    $x = 0;
    $y = 0;
    if ($origWidth > $origHeight)
    {
        $w = floor($h * $origWidth/$origHeight);
        $x = floor(($w - $n)/2);
    }
    else
    {
        $h = floor($w * $origHeight/$origWidth);
        $y = floor(($h - $n)/2);
    }
    
    $square->Resize(geometry =>  $w . 'x' . $h . '!');
    $square->Crop(geometry =>  $n . 'x' . $n . "+$x+$y");
   
    return $square;
}
