使用imagejpeg保存&服务图像文件 [英] Using imagejpeg to save & serve image file

查看:294
本文介绍了使用imagejpeg保存&服务图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些PHP +图像处理的实验。我正在尝试将一些图像转换为黑白版本。我大部分时间都认为它有一个小问题。

I'm doing a bit of an experiment with PHP + Image manipulation. I'm trying to convert some images into black and white versions. I'm mostly figured it out but have one slight issue.

为了减轻服务器的压力,我想保存B& W版本并且只运行对之前未通过脚本运行的图像进行图像过滤。所以,我有这样的事情:

In order to reduce the strain on the server, I wanted to save the B&W versions and only run the image filtering on images that haven't been run through the script before. So, I have something like this:

<?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语句也有效 - 如果图像已经存在,它会正确地提供图像。

This does create the B&W versions of the file and save them to the server. The initial "if" statement is also working - it correctly serves the image if it already exists.

问题是对于运行的新图像,这会保存它们但不会将它们输出到浏览器。为了做到这一点,我可以使用/更改什么?

The issue is that for new images that are run through, this saves them but doesn't output them to the browser. What can I use/change in order to do that?

此外,这是我第一次做这样的事情。任何有关上述操作的一般提示都将受到赞赏。

Also, this is my first time doing anything like this. Any general tips you have about doing the above would be appreciated.

推荐答案

上述功能的紧凑且正确的形式可以是:

A compact and correct form for above function can be:

<?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);

?> 

这篇关于使用imagejpeg保存&amp;服务图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆