Imagecrop without saving the image

做~自己de王妃 提交于 2019-12-12 11:03:21

问题


I have a bunch of product preview images, but they are not the same dimensions.

So i wonder, is it possible to crop an image on the go, without saving it?

These two links should show what i mean:

http://xn--nstvedhandel-6cb.dk/alpha_1/?side=vis_annonce&id=12

http://xn--nstvedhandel-6cb.dk/alpha_1/?side=vis_annonce&id=13


回答1:


Yes it's possible here's how i do it:

//Your Image
$imgSrc = "image.jpg";
list($width, $height) = getimagesize($imgSrc);
$myImage = imagecreatefromjpeg($imgSrc);

// calculating the part of the image thumbnail
if ($width > $height)
{
    $y = 0;
    $x = ($width - $height) / 2;
    $smallestSide = $height;
 } 
 else
 {
    $x = 0;
    $y = ($height - $width) / 2;
    $smallestSide = $width;
 }

 // copying the part into thumbnail
 $thumbSize = 100;
 $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
 imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

 //final output
 header('Content-type: image/jpeg');
 imagejpeg($thumb);

This is not a verry light operation, like the others i also reccomend you to save the thumbnail after creating it to your file system.

You might wanna check out PHP's GD library.




回答2:


You might wanna try this simple script: https://github.com/wes/phpimageresize

It also allows for caching, which should help with performance issues.

But I also prefer resizing images and saving them as thumbnails.




回答3:


It certainly is possible, but what you are wanting to do probably isn't a good idea - here's why.

If you crop an image, save it, you (or rather your server) never needs to do it again. It's not a light operation.

However, if you keep cropping on the fly, your server will have to do that work each and every single time - which is quite inefficient.

As a worst case scenario, why not automatically crop them once to the dimensions you want (rather than doing it manually) and simply save those results?

Lastly, given that it is a store, wouldn't manually cropping them give your products the best possible images - and thereby the best chance of selling them?



来源:https://stackoverflow.com/questions/12211984/imagecrop-without-saving-the-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!