PHP回应jpeg图像失败,但将相同的图像写入文件工作伟大。为什么? [英] PHP echoing jpeg image fails, but writing same image to file works great. Why?
问题描述
我有一个函数在PHP中调用curl来检索图像。当我打印到一个文件,并在浏览器中检查它,图像看起来不错。当我使用curl结果的echo作为我的PHP脚本的返回值时,浏览器显示破碎图像图标(参见该图标的示例: http://www.artifacting.com/blog/wp-content/uploads/2007/01/error_icon.gif )。
I have a function in PHP that calls curl to retrieve an image. When I print that to a file and examine it in the browser, the image looks great. When I use "echo" of the curl results as the return value from my PHP script, the browser shows the broken-image icon (see an example of that icon: http://www.artifacting.com/blog/wp-content/uploads/2007/01/error_icon.gif).
$ch = curl_init();
$options = array(
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_HEADER => 0,
CURLOPT_USERAGENT => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)",
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTPPROXYTUNNEL => 1,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_BINARYTRANSFER => 1,
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt_array($ch, $options);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param_list);
// The http response code is 200, and the body length is 50kb.
$body = curl_exec($curl_params);
// This produces a file containing an image that looks good when viewed in a browser.
$bodyFile = @fopen("img.jpg", "w");
fprintf($bodyFile, "%s", $body. "\n");
fclose($bodyFile);
// This does not render in the browser. Instead I see the broken image icon.
$contentType = "image/jpeg";
header('Content-type: ' . $contentType);
echo $body;
任何想法?帮助!
推荐答案
原来,我有另一个PHP文件,写出一个额外的换行符。在?>行后面的文件末尾有一个换行符。
It turned out that I had another PHP file that was writing out an extra newline character. There was a newline at the end of that file after the "?>" line.
这篇关于PHP回应jpeg图像失败,但将相同的图像写入文件工作伟大。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!