Hello, i have question how to make square images.
I am developing an alcohol online storefront and in it I need to implement square images of bottles - so that they visually all look the same.
Right now I am using the following code to position and create the images.
<div class="fotorama p-4 bg-white w-full lg:w-2/5 lg:pr-4 hidden lg:block pt-16" data-nav="thumbs">
<?php
if(count($page->get('images'))):
foreach($page->get('images') as $image):
$thumbSize = 500;
$largeSize = 1000;
// If image already 500x500 or less, don't do any scaling
if($image->width <= 500 && $image->height <= 500) {
continue;
}
// If image is not square
else if($image->width != $image->height) {
if($image->height > $image->width) {
$thumb = $image->size(0, $thumbSize);
$large = $image->size(0, $largeSize);
} else {
$ratio = $image->width / $image->height;
$newWidthThumb = $thumbSize * $ratio;
$newWidthLarge = $largeSize * $ratio;
$thumb = $image->size($newWidthThumb, $thumbSize);
$large = $image->size($newWidthLarge, $largeSize);
$differenceThumb = $thumb->width - $thumbSize;
$differenceLarge = $large->width - $largeSize;
$thumb = $thumb->crop($differenceThumb / 2, 0, $thumbSize, $thumbSize);
$large = $large->crop($differenceLarge / 2, 0, $largeSize, $largeSize);
}
if($thumb->width < 500 || $thumb->height < 500 || $large->width < 1000 || $large->height < 1000) {
$imagickSmall = new Imagick($thumb->filename);
$imagickLarge = new Imagick($large->filename);
$canvasSmall = new Imagick();
$canvasLarge = new Imagick();
$canvasSmall->newImage(500, 500, new ImagickPixel('white'));
$canvasLarge->newImage(1000, 1000, new ImagickPixel('white'));
$canvasSmall->compositeimage($imagickSmall, Imagick::COMPOSITE_OVER, ($canvasSmall->getImageWidth() - $thumb->width) / 2, ($canvasSmall->getImageHeight() - $thumb->height) / 2);
$canvasLarge->compositeimage($imagickLarge, Imagick::COMPOSITE_OVER, ($canvasLarge->getImageWidth() - $large->width) / 2, ($canvasLarge->getImageHeight() - $large->height) / 2);
$canvasSmall->writeImage($thumb->filename);
$canvasLarge->writeImage($large->filename);
}
}
// The image is square
else {
$thumb = $image->size($thumbSize, $thumbSize);
$large = $image->size($largeSize, $largeSize);
}
?>
<a href="<?=$large->url?>"><img src="<?=$thumb->url?>" class="pt-2" alt="<?=$page->title?>" width="64" height="64"></a>
<?php endforeach; ?>
<?php else: ?>
<img src="<?=urls()->templates?>images/notfound.png" width="64" height="64" alt="">
<?php endif; ?>
</div>
The code works great and generates square images.
BUT! When I try to add webp support
<a href="<?=$large->webp->url?>"><img src="<?=$thumb->webp->url?>" class="pt-2" alt="<?=$page->title?>" width="64" height="64"></a>
<?php endforeach; ?>
code nothing works.
There is a crop image function, but no function to position the image centered with the background added.
How to implement this as simple as possible, using core functions and adding webp support ?