2010-09-24 83 views
3

我正在WordPress中开发一个自定义图片上传字段,但是在上传图片后我遇到了很多困难。除了上传之外,我还需要调整图片大小以使用缩略图。每次尝试使用上传的图像时,我都会遇到无法找到该文件的错误(即使我可以在浏览器中查看它,并且很清楚地显示在目录中)。上传时图像默认为666,但我也尝试在777处操作,结果相同。图像上传后,调整大小功能会自行调用。下面是我所做的尝试之一:WordPress中的自定义图片上传字段

function resize_author_picture($filename) { 
    $filename = $_POST['file']; 
    $file = fopen($filename, 'r'); 
    $data = fread($file); 
    fclose($file); 
    $dimensions = getimagesize($filename); 
    $dir = dirname($filename); 
    $crop = wp_crop_image($data, $dimensions[0], $dimensions[1], 0, 0, 250, 280, null, $dir."/image.jpg"); 

    die("crop: ".var_dump($crop)." file: ".$filename." path: ".$dir."/image.jpg"); 
} 

这里我用fopen()函数,因为一旦只提供图像的路径没有工作,第二次尝试。这里是以前的尝试:

function resize_author_picture($file) { 
$file = $_POST['file']; 
$dimensions = getimagesize($file); 
$dir = dirname($file); 
$crop = wp_crop_image($file, $dimensions[0], $dimensions[1], 0, 0, 250, 280, null, $dir."/image.jpg"); 
die("crop: ".var_dump($crop)." file: ".$file." path: ".$dir."/image.jpg"); 
} 

两个沿着这些线路返回一个错误WP对象:

string(123) "File <http://site.local/wp-content/uploads/2010/09/squares-wide.jpeg> doesn't exist?" 

运行的想法,任何输入的感谢!

+0

即使编辑我的答案仍然成立。我已经用一个具体的例子更新了它。 – 2011-05-24 22:03:17

回答

0

如果您使用内联上传功能,您的图片将位于/ wp-content/uploads文件夹中,除非您在其他管理面板上指定了另一个文件夹。

请确保您没有更改上传目录位置。

尝试使用WP Post工具上传,以确保您的设置是正确的。然后继续调试代码 - 一旦排除了最基本的代码。

+0

不是问题 - 在wp-content/images中图像正确上传并存在于我期望的位置。看来wp_upload_bits()后面的任何脚本都无法访问这些图像。 – Gavin 2010-09-24 20:09:26

2

疑问,你仍然需要一个答案,因为这个问题是很老,但在这里它是供将来参考:

你得到的错误是wp_load_image返回其使用wp_crop_imagewp_load_image使用php函数file_exists,这需要在没有域的情况下提供文件的路径。

所以

$crop = wp_crop_image($file, $dimensions[0], $dimensions[1], 0, 0, 250, 280, 
     null, "wp-content/uploads/2010/09/squares-wide.jpeg"); 

会工作。

另外wp_upload_bits不仅会为您上传文件,还会返回上传文件的网址。

如果你打电话wp_upload_bits像这样(其中,“文件”的形式输入的名称):

if ($_FILES["file"]["name"]!="") { 
    $uploaded_file = wp_upload_bits($_FILES["file"]["name"], null, 
     file_get_contents($_FILES["file"]["tmp_name"])); 
} 

因此$uploaded_file['url']相当于$dir."/image.jpg"。在上述作物中,您可以使用$uploaded_file['url']的子字符串。

具体的例子:

随着http://site.local/wp-content/uploads/2010/09/squares-wide.jpeg这将工作:

$dir = dirname($file); 
$dir_substr = substr($dir, 18) 
$crop = wp_crop_image($file, $dimensions[0], $dimensions[1], 0, 0, 250, 280, 
     null, $dir."/squares-wide.jpeg"); 

当然你也想要的文件名是动态的,所以我会打电话wp_uload_bits如上建议(如果不是来自一个表单域,但是一个WP Custom字段像现在这样调用它,重要的部分是$uploaded_file = wp_upload_bits(...)wp_upload_bits的回报保存在一个变量中供以后使用),然后执行

$file_uri = substr($uploaded_file['url'], 18); 
$crop = wp_crop_image($file, $dimensions[0], $dimensions[1], 0, 0, 250, 280, 
     null, $file_uri);