0

I'm trying to resize images with imagemagick in PHP. When the source image is bigger than the resize size everything works fine, but it doesn't work correct when the source image is smaller than the resize size. Then the image needs to get some padding

For example: If the source image is 200px x 200px, the scripts enlarges the image in '$smallphoto' to 300px x 300px, but I want the source image to stay 200px x 200px and add padding to make it 300px x 300px. The source image can never be larger than it's original size, but '$smallphoto' always need to be 300px x 300px.

Does anyone know the best way to solve my problem?

$imageSource = 'test.jpg';
$newImage = new Imagick($imageSource);

// Remove whitespace around image
$newImage->trimImage(0.04 * \Imagick::getQuantum());

// Get width/height
$newImageWidth = $newImage->getImageWidth();
$newImageHeight = $newImage->getImageHeight();

// Check for longest side
$newImageSize = ($newImageWidth > $newImageHeight) ? $newImageWidth : $newImageHeight;

// Set quality for image
$newImage->setImageCompressionQuality(80);

// Set white background
$newImage->setImageBackgroundColor('#ffffff');

// Make the square and set the image in the center
$newImage->extentImage($newImageSize, $newImageSize, ($newImageWidth - $newImageSize) / 2, ($newImageHeight - $newImageSize) / 2);

// Save image
$newImage->writeImage('test-new.jpg');

// Create smaller image
$smallPhoto = new Imagick('test-new.jpg');
$smallPhoto->resizeImage(300, 300, imagick::FILTER_LANCZOS, 0.9, true);
$smallPhoto->writeImage('s-test-news.jpg');
Roger
  • 82
  • 1
  • 8
  • I think your question needs some rewording. I misread it as trying to enlarge an image without losing image quality (which is essentially impossible for bitmapped images), but what I think you actually mean is you want to pad an image with white space. – GordonM Dec 16 '16 at 14:02
  • Yes, that's correct. :-) – Roger Dec 16 '16 at 14:19
  • I think I have the solution. First I check if the source image is smaller than the size of '$smallphoto.' If that's the case I do extent image instead of resize. – Roger Dec 16 '16 at 14:23
  • 2
    I think I have the solution. First I check if the source image is smaller than the size of '$smallphoto.' If that's the case I do extent image instead of resize. Is this the best solution or is there a better one? $largePhoto->extentImage(300, 300, ($newImageSize - 300) / 2, ($newImageSize - 300) / 2); – Roger Dec 16 '16 at 14:25
  • 1
    Yes, the `-extent` commandline option or equivalent API was made for this situation, so you're on the right track. – Glenn Randers-Pehrson Dec 16 '16 at 15:48

0 Answers0