I have some image. I need to use imagick to create a square preview for it, but the fact is that the image can be of any width and any height. The preview should be a white square 150x150 with the image in the center.
Suppose the image size is 200x400. Then you need to change the image function thumbnailImage(-1, 150) . now its size is 75x150. Is it possible to stretch the canvas somehow so that its dimensions become 150x150, and the new space is filled with white. Like in Pain.NET. Below is an example of the image itself and its preview.
- imagine.readthedocs.io/en/latest most likely avalanche123 / imagine has everything you need - etki
|
2 answers
Create two objects: one square with the desired side, the second - a tambes from the target image with a width equal to the side of the first square. And put the tambes on the square.
$bg = new Imagick(); $bg->newImage(100, 100, new ImagickPixel('white')); $bg->setImageFormat('jpg'); $image = new Imagick('path_to.jpg'); $image->thumbnailImage(100, 0); $bg->compositeImage($image, Imagick::ALIGN_CENTER,0,(100-$image->getImageHeight())/2); header('Content-type: image/png'); echo $bg; Checked works.
- Well, it already looks easier. I understand that Imagick still can't change the size of the canvas? - Puro
- I did not find a class method that would respond to the task. - Kirill Korushkin
- Thank you, the question is closed. Mark this answer as the best solution. - Puro
- Always happy to help. - Kirill Korushkin
|
Now I use the following algorithm:
$ image = new Imagick ($ source); // create an object with my picture
$ d = $ image-> getImageGeometry (); // I get its dimensions and depending on them I scroll the image width or height
$ w = $ d ['width'];
$ h = $ d ['height'];
if ($ w> $ h) $ image-> thumbnailImage (150, -1);
else $ image-> thumbnailImage (-1, 150);
$ prew = new Imagick (); // create an object for the preview and create on it a new image 150x150 in white
$ prew-> newImage (150, 150, new ImagickPixel ('white'));
$ d = $ image-> getImageGeometry (); // I receive new image sizes and consider indents for the room in the center
$ w = $ d ['width'];
$ h = $ d ['height'];
$ ox = (150 - $ w) / 2;
$ oy = (150 - $ h) / 2;
$ prew-> compositeImage ($ image, Imagick :: COMPOSITE_DEFAULT, $ ox, $ oy); // I put my picture on the preview, observing the pre-calculated indents
$ prew-> writeImage ($ dest);
If someone doesn’t understand, I’m interested in a more simplified to a couple of lines algorithm, if possible.
|

