writing new image data to a file after converting to grayscale php
<p>Im using the following code to take an image, convert it to grayscale, and then save the grayscale image:</p>

<pre><code>$imagename = "$imagename"; // path to previously uploaded color jpeg

        $im = ImageCreateFromJpeg($imagename);

    $imgw = imagesx($im);
    $imgh = imagesy($im);

    for ($i=0; $i&lt;$imgw; $i++)
    {
            for ($j=0; $j&lt;$imgh; $j++)
            {

                    $rgb = ImageColorAt($im, $i, $j);

                    $rr = ($rgb &gt;&gt; 16) &amp; 0xFF;
                    $gg = ($rgb &gt;&gt; 8) &amp; 0xFF;
                    $bb = $rgb &amp; 0xFF;

                    $g = round(($rr + $gg + $bb) / 3);

                    $val = imagecolorallocate($im, $g, $g, $g);

                    imagesetpixel ($im, $i, $j, $val);
            }
    }

    $grayimgpath = "step2cache/".$saltname."_gray.jpg"; //$saltname is a randomly generated image name



$fh = fopen($grayimgpath, 'w') or die("can't open file");
fwrite($fh, $im);
fclose($fh);
</code></pre>

<p>The problem is, when i access this file, its blank, 15 bytes.</p>

<p>What am i missing here?</p>
