PHP save raw RGBA as PNG/GIF
I have an image file, with a 128 byte header, followed by raw RGBA data and the width and height are stored at offset 72 and 74 as short ints (big endian). I have successfully been able to read the header, however, I need a way to save the raw RGBA as PNG format and/or GIF. How can I do that in PHP?
开发者_开发百科cheers
If you have the gd lib installed (check with phpinfo(); ) it's something like
//create image
$img = imagecreatetruecolor($width, $height);
//fill by iterating through your raw pixel data
imagesetpixel($img, $x, $y, $color);
//output
header("Content-Type: image/png");
imagepng($img);
//cleanup
imagedestroy($img);
EDIT
You said it was RGBA data. Assuming standard 4 bytes per channel and that your raw data is an integer array, it should be:
$pos = ($y * $width + $x) * 4 + ($headerLengthInBytes / 4);
$red = $rawImageData[$pos];
$green = $rawImageData[$pos + 1];
$blue = $rawImageData[$pos + 2];
$alpha = $rawImageData[$pos + 3];
While you could generate an uncompressed PNG from your source stream yourself, that takes a lot of effort. (Need to handicraft the png32 header, and write out uncompressed deflate chunks because PNG itself supports no uncompressed payloads).
It's easier with imagemagick. Simply write out your raw RGBA stream to a temporary file and use:
file_put_contents("tmp.rgba", susbstr($data, 128));
exec("convert -size 640x300 -depth 8 tmp.rgba output.png");
I would look at gd or imagemagick one or both of these should do the trick
精彩评论