I have a function in my class file that converts an image to grayscale. What I need is a way to store that converted image in a variable so it can be displayed on my page with rest if the users info instead of just a white page with the converted image. I would appreciate any suggestions. here is the code:
function GoBlackWhite($pic){
$file = "pictures/$pic";
$im = imagecreatefromjpeg($file);
$imgw = imagesx($im);
$imgh = imagesy($im);
for ($i=0; $i<$imgw; $i++){
for ($j=0; $j<$imgh; $j++){
// get the rgb value for current pixel
$rgb = @imagecolorat($im, $i, $j);
// extract each value for r, g, b
$rr = ($rgb >> 16) & 0xFF;
$gg = ($rgb >> 8) & 0xFF;
$bb = $rgb & 0xFF;
// get the V开发者_开发问答alue from the RGB value
$g = round(($rr + $gg + $bb) / 3);
// grayscale values have r=g=b=g
$val = imagecolorallocate($im, $g, $g, $g);
// set the gray value
imagesetpixel ($im, $i, $j, $val);
}
}
header('Content-type: image/jpeg');
imagejpeg($im);
}
You can send either a html page, or an image, but not both at once. Thats a "limitation" of the http-protocol. If you want to include an image in your website, use the <img>
-element
<img src="/path/to/image.jpg" />
Typically, you need either two scripts (one for the HTML and one for the Image data) or one script that changes its behavior based on a query parameter. For example (this is a script that changes based on a query parameter):
<?php
if( isset($_REQUEST['pic']) )
{
// Call your function and return bytes with content type header as above
exit;
}
?>
<html>
<body>
The converted image:<br/>
<img src='<?php echo $PHP_SELF . "?pic=myimagefile.jpg";?>'/>
</body>
</html>
Create a php page which streams back the image's bytes, setting the MIME type as you did in your example. Then <img src="/path/to/image.php" />
Alternatively, see if the Data URI scheme fits your scenarios. This will only be applicable, if you have very small images, and if you're not likely to serve them more than once.
精彩评论