在PHP中调整图像大小
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在PHP中调整图像大小相关的知识,希望对你有一定的参考价值。
我想写一些php代码,自动调整通过表单上传到147x147px的任何图像,但我不知道如何去做(我是一个相对的PHP新手)。
到目前为止,我已成功上传图片,识别文件类型并清理名称,但我想将调整大小功能添加到代码中。例如,我有一个2.3MB的测试图像,尺寸为1331x1331,我希望代码可以缩小尺寸,我猜测它也会大大压缩图像的文件大小。
到目前为止,我有以下内容:
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的图像重新采样确实大大减少了文件大小,特别是在重新采样原始数码相机图像时。
我建议您使用piio.co,一旦您将图像上传到存储空间,只需使用<img />
标签中的原始图像网址,图书馆就会自动为您调整大小。
您的图片代码如下所示:
<img data-piio="/image/gallery/p/image1.jpg" />
然后,一旦初始化Piio的脚本,它将自动调整图像大小并从CDN服务。
这是docs的链接
如果你想手动完成,那么我建议你使用原生的php函数,这将使用GD库。例如,如果要调整JPEG大小,可以从以下开始:
list($width, $height) = getimagesize($filepath);
$original = imagecreatefromjpeg($filepath);
$thumb = imagecreatetruecolor($new_width, $new_height);
imagecopyresized($thumb, $original, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
要直接输出图像:
imagejpeg($thumb);
要将图像保存到文件:
imagejpeg($thumb, 'filepath/image.jpg');
我找到了一种完成这项工作的数学方法
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
实例 - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width)
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG')
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
elseif ($extension == 'png' || $extension == 'PNG')
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
else
//show an error message if the file extension is not available
echo 'image extension is not supporting';
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
?>
This resource也值得考虑 - 一些使用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以上是关于在PHP中调整图像大小的主要内容,如果未能解决你的问题,请参考以下文章