在PHP中调整图像大小

我想写一些PHP代码,自动调整任何形式上传到一个窗体147x147px的图像,但我不知道该怎么去(我是一个相对的PHP新手)。

到目前为止,我已经成功地上传了图片,识别了文件类型并清除了名称,但是我想在代码中添加调整大小的功能。 例如,我有一个测试图像,尺寸为2.3MB,尺寸为1331×1331,我希望代码将其缩小,我猜测它也会大大压缩图像的文件大小。

到目前为止,我有以下几点:

if ($_FILES) { //Put file properties into variables $file_name = $_FILES['profile-image']['name']; $file_size = $_FILES['profile-image']['size']; $file_tmp_name = $_FILES['profile-image']['tmp_name']; //Determine filetype switch ($_FILES['profile-image']['type']) { case 'image/jpeg': $ext = "jpg"; break; case 'image/png': $ext = "png"; break; default: $ext = ''; break; } if ($ext) { //Check filesize if ($file_size < 500000) { //Process file - clean up filename and move to safe location $n = "$file_name"; $n = ereg_replace("[^A-Za-z0-9.]", "", $n); $n = strtolower($n); $n = "avatars/$n"; move_uploaded_file($file_tmp_name, $n); } else { $bad_message = "Please ensure your chosen file is less than 5MB."; } } else { $bad_message = "Please ensure your image is of filetype .jpg or.png."; } } $query = "INSERT INTO users (image) VALUES ('$n')"; mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query); 

您需要使用PHP的ImageMagick或GD功能来处理图像。

以GD为例,它就像…

 function resize_image($file, $w, $h, $crop=FALSE) { list($width, $height) = getimagesize($file); $r = $width / $height; if ($crop) { if ($width > $height) { $width = ceil($width-($width*abs($r-$w/$h))); } else { $height = ceil($height-($height*abs($r-$w/$h))); } $newwidth = $w; $newheight = $h; } else { if ($w/$h > $r) { $newwidth = $h*$r; $newheight = $h; } else { $newheight = $w/$r; $newwidth = $w; } } $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); return $dst; } 

你可以调用这个函数,像这样…

 $img = resize_image('/path/to/some/image.jpg', 200, 200); 

从个人经验来看,GD的图像重采样技术确实可以大大减少文件大小,特别是对原始数码相机图像进行重采样时。

对于所有图像类型,有一个非常简单的图像重新调整大小功能,保持透明度,非常容易使用

查看 :

http://www.nimrodstech.com/php-image-resize/

https://github.com/Nimrod007/PHP_image_resize

希望这可以帮助

这个资源也值得考虑 – 一些使用GD的非常整齐的代码。 不过,我修改了他们的最终代码片段来创建符合OP要求的函数。

 function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) { $target_dir = "your-uploaded-images-folder/"; $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]); $image = new SimpleImage(); $image->load($_FILES[$html_element_name]['tmp_name']); $image->resize($new_img_width, $new_img_height); $image->save($target_file); return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user } 

你还需要包含这个PHP文件…

 <?php /* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */ class SimpleImage { var $image; var $image_type; function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return imagesx($this->image); } function getHeight() { return imagesy($this->image); } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } } ?> 

如果你不关心纵横比(即你想强制图像到一个特定的维度),这里是一个简单的答案

 // for jpg function resize_imagejpg($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst; } // for png function resize_imagepng($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefrompng($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst; } // for gif function resize_imagegif($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefromgif($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst; } 

现在我们来处理上传部分。 第一步,将文件上传到您想要的目录。 然后根据文件类型(jpg,png或gif)调用上述函数之一,并传递上传文件的绝对路径如下:

  // jpg change the dimension 750, 450 to your desired values $img = resize_imagejpg('path/image.jpg', 750, 450); 

返回值$img是一个资源对象。 我们可以保存到一个新的位置或覆盖原来的如下:

  // again for jpg imagejpeg($img, 'path/newimage.jpg'); 

希望这有助于某人。 查看更多关于调整Imagick :: resizeImage和imagejpeg()的链接

我希望是会为你工作的。

 /** * Image re-size * @param int $width * @param int $height */ function ImageResize($width, $height, $img_name) { /* Get original file size */ list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']); /*$ratio = $w / $h; $size = $width; $width = $height = min($size, max($w, $h)); if ($ratio < 1) { $width = $height * $ratio; } else { $height = $width / $ratio; }*/ /* Calculate new image size */ $ratio = max($width/$w, $height/$h); $h = ceil($height / $ratio); $x = ($w - $width / $ratio) / 2; $w = ceil($width / $ratio); /* set new file name */ $path = $img_name; /* Save image */ if($_FILES['logo_image']['type']=='image/jpeg') { /* Get binary data from image */ $imgString = file_get_contents($_FILES['logo_image']['tmp_name']); /* create image from string */ $image = imagecreatefromstring($imgString); $tmp = imagecreatetruecolor($width, $height); imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); imagejpeg($tmp, $path, 100); } else if($_FILES['logo_image']['type']=='image/png') { $image = imagecreatefrompng($_FILES['logo_image']['tmp_name']); $tmp = imagecreatetruecolor($width,$height); imagealphablending($tmp, false); imagesavealpha($tmp, true); imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h); imagepng($tmp, $path, 0); } else if($_FILES['logo_image']['type']=='image/gif') { $image = imagecreatefromgif($_FILES['logo_image']['tmp_name']); $tmp = imagecreatetruecolor($width,$height); $transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127); imagefill($tmp, 0, 0, $transparent); imagealphablending($tmp, true); imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h); imagegif($tmp, $path); } else { return false; } return true; imagedestroy($image); imagedestroy($tmp); } 

ZF蛋糕:

 <?php class FkuController extends Zend_Controller_Action { var $image; var $image_type; public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) { $target_dir = APPLICATION_PATH . "/../public/1/"; $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]); //$image = new SimpleImage(); $this->load($_FILES[$html_element_name]['tmp_name']); $this->resize($new_img_width, $new_img_height); $this->save($target_file); return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user public function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } public function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } public function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } public function getWidth() { return imagesx($this->image); } public function getHeight() { return imagesy($this->image); } public function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } public function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } public function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } public function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } public function savepicAction() { ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $this->_response->setHeader('Access-Control-Allow-Origin', '*'); $this->db = Application_Model_Db::db_load(); $ouser = $_POST['ousername']; $fdata = 'empty'; if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) { $file_size = $_FILES['picture']['size']; $tmpName = $_FILES['picture']['tmp_name']; //Determine filetype switch ($_FILES['picture']['type']) { case 'image/jpeg': $ext = "jpg"; break; case 'image/png': $ext = "png"; break; case 'image/jpg': $ext = "jpg"; break; case 'image/bmp': $ext = "bmp"; break; case 'image/gif': $ext = "gif"; break; default: $ext = ''; break; } if($ext) { //if($file_size<400000) { $img = $this->store_uploaded_image('picture', 90,82); //$fp = fopen($tmpName, 'r'); $fp = fopen($img, 'r'); $fdata = fread($fp, filesize($tmpName)); $fdata = base64_encode($fdata); fclose($fp); //} } } if($fdata=='empty'){ } else { $this->db->update('users', array( 'picture' => $fdata, ), array('username=?' => $ouser )); } } 

您可以尝试一下TinyPNG PHP库。 使用这个库,您的图像在调整大小的过程中会自动优化。 您只需从https://tinypng.com/developers安装库并获取API密钥即可。; 要安装库,请运行以下命令。

 composer require tinify/tinify 

之后,你的代码如下。

 require_once("vendor/autoload.php"); \Tinify\setKey("YOUR_API_KEY"); $source = \Tinify\fromFile("large.jpg"); //image to be resize $resized = $source->resize(array( "method" => "fit", "width" => 150, "height" => 100 )); $resized->toFile("thumbnail.jpg"); //resized image 

我有一个关于同一主题的博客http://artisansweb.net/resize-image-php-using-tinypng