2010-06-23 102 views
2

我想从磁盘上传图片,调整大小,,然后将其上传到Amazon S3。imagejpeg()不能正确输出php

但是,我不能从imagejpeg()得到正确的图像输出。

继承人我的代码:

$sourceUrl = $_FILES['path']['tmp_name'];  
$thumbWidth = '100'; 
$thumbid = uniqid(); 
$img = imagecreatefromjpeg($sourceUrl); 
$width = imagesx($img); 
$height = imagesy($img); 

// calculate thumbnail size 
$new_width = $thumbWidth; 
$new_height = floor($height * ($thumbWidth/$width)); 

// create a new temporary image 
$tmp_img = imagecreatetruecolor($new_width, $new_height); 

// copy and resize old image into new image 
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

// output the image 
imagejpeg($tmp_img); 

// upload thumbnail to s3 
$s3->putObjectFile($tmp_img, "mybucket", $thumbid, S3::ACL_PUBLIC_READ); 

萤火虫给我这个错误:

illegal character 
[Break on this error] (�����JFIF���������>CREATOR: g...(using IJG JPEG v62), default quality\n 

如果我修改imagejpeg这样,

imagejpeg($tmp_img, 'abc.jpg'); 

然后我得到了同样的错误。 :(

我能得到一些帮助,在这里请

+0

您描述的第二种方法应该工作,JPG代码不应该输出。你100%确定它不?你在其他地方回应内容吗? – 2010-06-23 10:20:20

回答

3

如果选中的imagejpeg的文档,你可以看到它输出的图像,它意味着你叫它它被发送给浏览器的方式,你可以把它保存到一个文件,你把它叫做第二种方式 - 可以通过传递一个文件名中的第二个参数

而且,$tmp_img是一个图像资源,而不是一个随时可用的图像文件。

我不知道你的上传功能是如何工作的,但是:如果你需要文件内容上传,像这样做:

ob_start(); 
imagejpeg($tmp_image); 
$image_contents = ob_get_clean(); 
$s3->putObjectFile($image_contents, "mybucket", $thumbid, S3::ACL_PUBLIC_READ); 

如果你需要一个上传:

$filename = tempnam(sys_get_temp_dir(), "foo"); 
imagejpeg($tmp_image, $filename); 
$s3->putObjectFile($filename, "mybucket", $thumbid, S3::ACL_PUBLIC_READ); 
+0

+1这是正确的答案。 – 2010-06-23 10:24:43

0

你必须定义标题:?

header('Content-type: image/jpeg'); 
+0

如果他试图输出图像,这将是正确的答案,但他试图将它存储到亚马逊。 – 2010-06-23 10:21:03

+0

但也输出它:imagejpeg($ tmp_img); << imagejpeg - 将图像输出到浏览器或文件。如果没有指定文件名,那么它会直接显示 – 2010-06-23 10:25:55

+0

是的,但这就是他做错了(除其他事项外)。 – 2010-06-23 10:27:16

0

1)$tmp_img是资源而非文件。你可能需要将图像保存到光盘上,并用这些putObjectFile

2)您可能需要告诉S3,你要上传的文件类型是一个image/jpeg

0

好球员再次感谢您,我拧了一下,并与您的回应相结合,我得到这个工作如下:)

$thumbid .= ".jpg"; 
$img = imagecreatefromgif($sourceUrl); 
$width = imagesx($img); 
$height = imagesy($img); 

// calculate thumbnail size 
$new_width = $thumbWidth; 
$new_height = floor($height * ($thumbWidth/$width)); 

// create a new temporary image 
$tmp_img = imagecreatetruecolor($new_width, $new_height); 

// copy and resize old image into new image 
imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

$path = '/var/www/1.4/wwwroot/cdn/'.$thumbid; 
// output the image 
if(imagegif($tmp_img, $path)){     
    $thumblink = ""; 
    // upload thumbnail to s3 
    if($s3->putObjectFile($path, "mybucket", $thumbid, S3::ACL_PUBLIC_READ)){ 
     $thumblink = "http://dtzhqabcdscm.cloudfront.net/".$thumbid; 
     imagedestroy($tmp_img); 
    } 
    return $thumblink; 
}