You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP上传图片信息获取及GD库修改失败的问题咨询

问题解决:GD库处理上传图片的尺寸获取与缩放

报错原因

  • imagesx()/imagesy():要求参数是GD图像资源,你直接传了$_FILES数组,因此触发“不是资源”错误
  • getimagesize():要求参数是文件路径字符串(本地文件/临时文件路径),你传了数组,因此触发“不是字符串”错误

正确操作流程与代码

上传文件后,PHP会将文件暂存到临时目录,路径存在$_FILES['uploaded_file']['tmp_name']字段中,所有操作都要基于这个临时路径展开:

// 获取上传文件的临时存储路径
$tmpFilePath = $_FILES['uploaded_file']['tmp_name'];

// 1. 获取图片原始尺寸(传入临时路径给getimagesize)
$imageDetails = getimagesize($tmpFilePath);
$oldw = $imageDetails[0]; // 原始宽度
$oldh = $imageDetails[1]; // 原始高度

// 2. 根据图片类型创建GD图像资源(示例为PNG,JPG用imagecreatefromjpeg,GIF用imagecreatefromgif)
$sourceImage = imagecreatefrompng($tmpFilePath);

// 也可通过GD资源获取尺寸,和getimagesize结果一致
// $oldw = imagesx($sourceImage);
// $oldh = imagesy($sourceImage);

// 3. 创建目标画布并执行图片缩放
$neww = 512;
$newh = 512;
$tempImage = imagecreatetruecolor($neww, $newh);
// PNG图片需保留透明,添加以下两行
imagealphablending($tempImage, false);
imagesavealpha($tempImage, true);
imagecopyresampled($tempImage, $sourceImage, 0, 0, 0, 0, $neww, $newh, $oldw, $oldh);

// 4. 保存或输出处理后的图片
// 保存到服务器指定路径
imagepng($tempImage, './resized_image.png');
// 若要直接输出到浏览器,取消下方注释
// header('Content-Type: image/png');
// imagepng($tempImage);

// 5. 释放GD资源,避免内存占用
imagedestroy($sourceImage);
imagedestroy($tempImage);

关键函数的输入要求

  • getimagesize(string $filename):必须传入本地文件路径字符串(临时路径、服务器文件路径均可),不能传数组或GD资源
  • imagesx(resource $image)/imagesy(resource $image):必须传入GD库创建的图像资源(如imagecreatefrompng的返回值),不能传数组或文件路径
  • imagecopyresampled(resource $dst_image, resource $src_image, ...):目标画布和源图像都必须是GD图像资源

内容的提问来源于stack exchange,提问作者user6631314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 02:50:11