自动在浏览器中裁剪图像
如何通过上传过程自动裁剪图像? 有没有PHPfunction呢?
我希望我的网页通过裁剪来显示原始图像的各个维度具有相同尺寸的图像。
或者任何想法?
把它称为max_size.php
在您有图像的页面中
如果不知道主题在哪里,自动裁剪将很困难。 也许你可以尝试获得一个内部居中的矩形,如图所示:
首先要做的是找到原始图像尺寸和文件类型 。 你不应该相信图像扩展,而是使用getimagesize
。 尽管名称getimagesize
不仅返回大小,还返回文件类型。
//width is at index 0, height at index 1, mime type at ['mime'] key $original = getimagesize($filename);
然后你应该构建一个内部PHP数据结构来将源图像保存在内存中,这样你就可以使用imagecreatefromjpeg
或imagecreatefrompng
或imagecreatefromgif
来操作它,具体取决于图像类型。 例如:
$srcImage = imagecreatefromjpeg($filename);
接下来,您应该分配另一个数据结构来保存目标图像 。 在这种情况下,我们没有图像开头,所以我分配一个空图像。
$dstImage = imagecreatetruecolor($newWidth, $newHeight);
接下来,您应该将原始图像的一部分复制到目标图像 。 如果您不想resize,请使用imagecopy
,否则如果您想裁剪并resize,可以考虑使用imagecopyresampled
。
imagecopy(dstImage, $srcImage, 0, 0, $srcX, $srcY, $srcW, $srcH);
其中$ srcX是源图像中的起始X点,$ srcY是起始Y点,$ srcW是从起始X点复制的宽度,$ srcH是要复制的区域的高度。
最后,您可以使用以下方式保存图像 :
imagejpeg($this->dstImage, $filename, 90);
或者您可以将其输出到浏览器 :
imagejpeg($this->dstImage);
如果您保存图像,您需要考虑在哪个目录中保存它,如果您有大量图像(数千或更多),请考虑将它们分割到多个子目录中。
如果保存原始图像,则永远不要保存扩展名不在允许扩展名列表中的图像,否则将成为攻击者可以向您的站点发送和执行任何PHP代码的巨大安全漏洞 。
根据描述的概念,我写了一个小class:
class ImageCrop { //Image resources private $srcImage, $dstImage; //original width and height private $width, $height; /** * Read an image from disk. * @return true in case of success, false otherwise. */ public function openImage($filename) { if (!file_exists($filename)) { return false; } $original = getimagesize($filename); switch ($original['mime']) { case 'image/jpeg': $this->srcImage = imagecreatefromjpeg($filename); break; case 'image/png': $this->srcImage = imagecreatefrompng($filename); break; case 'image/gif': $this->srcImage = imagecreatefromgif($filename); break; default: return false; } $this->width = $original[0]; $this->height = $original[1]; return true; } /** * Crop an image to the new specified dimension trying to get an * internal rectangle of the original image. No crop is done if the * original dimension is already smaller than $newWidth or $newHeight. */ public function crop($newWidth, $newHeight) { $this->dstImage = imagecreatetruecolor($newWidth, $newHeight); $srcX = $srcY; $srcW = $this->width; $srcH = $this->height; $extraWidth = $this->width - $newWidth; if ($extraWidth > 0) { $srcX = $extraWidth / 2; } $extraHeight = $this->height - $newHeight; if ($extraHeight > 0) { $srcY = $extraHeight / 2; } imagecopy($this->dstImage, $this->srcImage, 0, 0, $srcX, $srcY, $srcW, $srcH); } /** * Save the destination image, the crop function should have been * called already. */ public function save($filename) { imagejpeg($this->dstImage, $filename, 90); } /** * Output the destination image to the browser. */ public function output() { imagejpeg($this->dstImage); } }
在ImageCrop.php中保存类,示例用法:
require_once 'ImageCrop.php'; $imageCrop = new ImageCrop(); if ($imageCrop->openImage('big.jpg')) { $imageCrop->crop(200, 300); //newWidth, newHeight $imageCrop->save('small.jpg'); }
或者,要将输出直接发送到浏览器,请使用$imageCrop->output();
。