任何人都知道如何上传图像,调整大小以设置维度,然后将图像路径存储在MySQL中的PHP教程?
答案 0 :(得分:2)
您可能需要查看PHP文档:Handling file uploads,GD and Image Functions。
通常,你必须:
is_uploaded_file
的上传文件)getimagesize
检测图像类型,然后使用适当的imagecreatefrom*
函数创建图像资源($img
)使用以下内容调整图像大小:
$thumb = imagecreatetruecolor($width, $height);
imagecopyresampled($thumb, $img, 0, 0, 0, 0, $width, $height, imagexs($img), imagesy($img));
保存缩略图:
imagejpeg($thumb, 'file.jpg', 85);
imagedestroy($thumb); // free memory
imagedestroy($img); // free memory
将您需要的信息保存到MySQL数据库
答案 1 :(得分:0)
我使用此功能来执行此操作,非常简单易用。 首先将此功能放在您可以调用的地方。
public function Resize_image($width = 0, $height = 0, $quality = 90, $filename_in = null, $filename_out = null)
{
$this->Filename = $filename_in;
$this->Extension = strtolower($this->Get_file_extension($this->Filename));
$size = getimagesize($this->Filename);
$ratio = $size[0] / $size[1];
if ($ratio >= 1){
$scale = $width / $size[0];
} else {
$scale = $height / $size[1];
}
// make sure its not smaller to begin with!
if ($width >= $size[0] && $height >= $size[1]){
$scale = 1;
}
// echo $fileext;
switch ($this->Extension)
{
case "jpg":
$im_in = imagecreatefromjpeg($this->Filename);
$im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale);
imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]);
imagejpeg($im_out, $filename_out, $quality);
break;
case "gif":
$im_in = imagecreatefromgif($this->Filename);
$im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale);
imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]);
imagegif($im_out, $filename_out, $quality);
break;
case "png":
$im_in = imagecreatefrompng($this->Filename);
$im_out = imagecreatetruecolor($size[0] * $scale, $size[1] * $scale);
imagealphablending($im_in, true); // setting alpha blending on
imagesavealpha($im_in, true); // save alphablending setting (important)
imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $size[0] * $scale, $size[1] * $scale, $size[0], $size[1]);
imagepng($im_out, $filename_out, 9);
break;
}
imagedestroy($im_out);
imagedestroy($im_in);
}
现在您可以像这样使用此功能来调整图像大小并将其复制到所需目录。
Resize_image($width, $height, $quality=90, $filename_in, $filename_out)
Example..
Resize_image(150, 150, 90, "Directory".$image, "Directory".$image_without_extension."_thumb.".$image_ext); //makes file_thumb.ext