我一直在尝试使用 GD 库编写一个脚本来创建图像并使用他们的 API 将其直接上传到 ImageShack。我正在使用 Elliott C. Back 编写的 ImageShack 类,它可以通过从文件上传图像而完美地工作。但是当我尝试修改一行简单的 CURL 选项代码时,它会中断并且不会上传。
我编写了一个示例代码,它只是创建黑色图像,将其存储到变量中(以及尝试将其保存在本地文件中 - 以验证它是否不会通过将其存储在变量或任何东西中而损坏),最后尝试上传到 ImageShack。代码被注释了,所以它应该很容易阅读。我希望你能帮我解决这个问题,因为我已经尝试了我能想到的一切。甚至可以使用 CURL 从变量上传文件吗?
当我运行这个脚本时,我得到了一堆错误,但都是:
PHP Notice: Undefined offset: 1 in test.php on line 82
或者
PHP Notice: Undefined offset: 2 in test.php on line 82
#!/usr/bin/php -q
<?php
// Create some basic image using PHP manual example for GD library
$img = imagecreatetruecolor(200, 200);
// Create new object from class ImageShack
$imageshack = new ImageShack;
// Store image to variable $image
ob_start();
ImagePNG($img);
$image = ob_get_clean();
// Upload image to ImageShack and print the url
$imageshack->upload($image);
$url = $imageshack->get_image_url();
print $url;
// And now let's try to save image from $image variable to local file to see if it's not corruped or anything
$tmpFile = "tmpFile.png";
$fh = fopen($tmpFile, 'w') or die("Can't open file");
fwrite($fh, $image);
fclose($fh);
// And finally destroy the image to free memory.
imagedestroy($img);
// Follows the slightly modified version of ImageShack class by Elliott C. Back
// only modified part is CURLOPT_POSTFIELDS part of upload() function and removed not required functions
// Class works flawlessly if you use it unmodified and upload from file, instead of variable.
class ImageShack
{
var $is_url = "http://www.imageshack.us/index.php";
var $is_result = false;
var $is_result_parsed = false;
public function upload( $file )
{
// send the image to ImageShack
$ch = curl_init($this->is_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 240);
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'xml'=>'yes', 'fileupload'=>$file ));
// curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'xml'=>'yes', 'fileupload'=>'@'.$file )); <== This is original line
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect: ' ));
$this->is_result = curl_exec($ch);
curl_close($ch);
// Parse the result
$this->parse();
}
public function get_image_url()
{
return $this->get( "image_link" );
}
private function get( $key )
{
if( !$this->is_result_parsed )
return false;
return( $this->is_result_parsed[ $key ] );
}
private function parse()
{
if (strpos($this->is_result, '<'.'?xml version=”1.0? encoding="iso-8859-1??>') === false)
$this->is_result_parsed = false;
$xmlData = explode("\n",$this->is_result);
$xmlr = array();
foreach($xmlData as $xmlDatum){
$xmlDatum = trim($xmlDatum);
if($xmlDatum != "" && !eregi("links",$xmlDatum) && !eregi("xml",$xmlDatum)){
$xmlDatum = str_replace(">","<",$xmlDatum);
list($xmlNull,$xmlName,$xmlValue) = explode("<",$xmlDatum);
$xmlr[$xmlName] = $xmlValue;
}
}
$this->is_result_parsed = $xmlr;
}
}
?>