如何不将图像输出到浏览器


How not to output an image to the browser?

我的代码:

ob_start();
imagejpeg($resource, NULL, 75);  break; // best quality
$resource = ob_get_contents();
ob_end_flush();

我使用imagejpeg()只是为了输出缓冲,我不需要输出到浏览器。什么好主意吗?

让我们试着分析一下你在那里做了什么:

// start output buffering
ob_start();
// output the image - since ob is on: buffer it
imagejpeg($resource, NULL, 75);
// this break could be a problem - if this is in a control structure, remove it
break;
// save the ob in $resouce
$resource = ob_get_contents();
// here is the image now in $resource AND in the output buffer since you didn't clean it (the ob)
// end ob and flush (= send the ob)
ob_end_flush();

所以你做错的是,你1)没有清理输出缓冲区和/或2)刷新了ob.

我的建议是使用ob_get_clean(参考)(简单示例):

$im = imagecreatetruecolor(120, 20);
ob_start();
imagejpeg($im);
$var = ob_get_clean();

如果是循环,则中断该进程。因此,OB将不会关闭,输出将位于解析过程的末尾。此外,你不必冲水,但要清洁。用途:

ob_start();
imagejpeg($resource, NULL, 75); // best quality
$resource = ob_get_contents();
ob_end_clean();
break;

或:

ob_start();
imagejpeg($resource, NULL, 75); // best quality
$resource = ob_get_contents();
ob_clean();
// Some other code
ob_end_flush(); // Output the rest
break;