[英]How to resize image using Gd library ? PHP
从客户端收到图像后,我想调整大小然后存储。 我正在使用此功能:
function PIPHP_ImageResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagecopyresampled($temp, $image, 0, 0, 0, 0,
$w, $h, $oldw, $oldh);
return $temp;
}
$image = PIPHP_ImageResize($_FILES['file']['tmp_name'],10,10);
move_uploaded_file($image, $newname);
不幸的是,我得到了这些警告:
我该如何解决这个问题!
imagesx
期望将图像资源作为第一个参数。 您必须使用适当的函数(例如imagecreatefromjpeg或imagecreatefrompng)创建一个。
function PIPHP_ImageResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagecopyresampled($temp, $image, 0, 0, 0, 0, $w, $h, $oldw, $oldh);
return $temp;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $newname)) {
$uploadedImage = imagecreatefromjpeg($newname);
if (!$uploadedImage) {
throw new Exception('The uploaded file is corrupted (or wrong format)');
} else {
$resizedImage = PIPHP_ImageResize($uploadedImage,10,10);
// save your image on disk
if (!imagejpeg ($resizedImage, "new/filename/path")) {
throw new Exception('failed to save resized image');
}
}
} else {
throw new Exception('failed Upload');
}
我添加了最少且不足的错误处理,例如,您应该检查上载文件的格式并使用适当的图像创建器功能,或者检查上载的文件是否为图像。
附录
您可以使用getimagesize函数确定假定上传的图像的类型。
getimagesize返回一个数组。 如果支持图像类型,则array [2]值返回图像的类型。 如果文件不是图像,或者不支持其格式,则array [0]的值为零。 一旦知道了图像的文件格式,就可以使用imagecreatefromxxx函数之一来创建适当的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.