Php 使用imagejpeg保存&;服务图像文件
我正在做一个PHP+图像处理的实验。我正在尝试将一些图像转换成黑白版本。我基本上明白了,但有一个小问题 为了减少服务器上的压力,我想保存B&W版本,只对以前没有通过脚本运行过的图像运行图像过滤。所以,我有这样的想法:Php 使用imagejpeg保存&;服务图像文件,php,image-processing,Php,Image Processing,我正在做一个PHP+图像处理的实验。我正在尝试将一些图像转换成黑白版本。我基本上明白了,但有一个小问题 为了减少服务器上的压力,我想保存B&W版本,只对以前没有通过脚本运行过的图像运行图像过滤。所以,我有这样的想法: <?php header("Content-type: image/jpeg"); $file = $_GET['img']; $name = md5($file).".jpg"; if(file_exists("/path/to/file" . $name)) {
<?php
header("Content-type: image/jpeg");
$file = $_GET['img'];
$name = md5($file).".jpg";
if(file_exists("/path/to/file" . $name)) {
ob_clean();
flush();
readfile("path/to/file" . $name);
exit;
}
else {
$image = imagecreatefromjpeg($file);
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagejpeg($image, "/path/to/file" . $name);
imagedestroy($image);
};
?>
这将创建文件的B&W版本并将其保存到服务器。初始的“if”语句也在工作——如果图像已经存在,它将正确地服务于图像
问题是,对于运行的新图像,这会保存它们,但不会将它们输出到浏览器。为了做到这一点,我可以使用/更改什么
而且,这是我第一次做这样的事情。如果您有任何关于执行上述操作的一般提示,我们将不胜感激。因为您使用
imagejpeg()
在其他部分保存图像,您的图像将不会显示。
所以你必须加上
readfile("/path/to/file". $name);
在imagedestroy()之后(
;) 上述功能的紧凑正确形式可以是:
<?php
header("Content-type: image/jpeg");
$file = $_GET['img'];
$name = md5($file).".jpg";
if(!file_exists("/path/to/file" . $name)) {
imagefilter($image, IMG_FILTER_GRAYSCALE);
imagejpeg($image, "/path/to/file" . $name);
} else {
$image = imagecreatefromjpeg("/path/to/file" . $name);
}
imagejpeg($image);
imagedestroy($image);
?>
您可以将图像输出代码包装在函数中-类似于以下内容(未测试):
为什么要投反对票?一个解释会很有帮助,这样我就可以纠正任何错误。
function output_image ( $image_file ) {
header("Content-type: image/jpeg");
header('Content-Length: ' . filesize($image_file));
ob_clean();
flush();
readfile($image_file);
}
$file = $_GET['img'];
$name = md5( $file ) . ".jpg";
$image_file = "/path/to/file/" . $name;
if(!file_exists( $image_file )) {
$image = imagecreatefromjpeg( $file );
imagefilter( $image, IMG_FILTER_GRAYSCALE );
imagejpeg( $image, $image_file );
imagedestroy( $image );
}
output_image( $image_file );