I have a need to read in the exact unaltered pixel data (ARGB) from a truecolour PNG file, preferably from PHP.
Unfortunately the GD library in PHP messes with the alpha channel (reducing it from 8-bit to 7-bit), making it unusable.
I'm currently assuming that my options are either:
I'd be interested to hear any other ideas, though, or recommendations for one way over the other...
: I think #1 is out.:我认为#1已经出局了。 I've tried passing the IDAT data stream to gzinflate(), but it just gives me a data error. (Doing the exact same thing, with the exact same data, outside of PHP produces the expected result.)
How about ImageMagick?
<?php
$im = new Imagick("foo.png");
$it = $im->getPixelIterator();
foreach($it as $row => $pixels) {
foreach ($pixels as $column => $pixel) {
// Do something with $pixel
}
$it->syncIterator();
}
?>
You can use the pngtopnm function of netpbm to convert the PNG to an easily parsed PNM. Here is a somewhat naive php script that should help you get what you need:
<?php
$pngFilePath = 'template.png';
// Get the raw results of the png to pnm conversion
$contents = shell_exec("pngtopnm $pngFilePath");
// Break the raw results into lines
// 0: P6
// 1: <WIDTH> <HEIGHT>
// 2: 255
// 3: <BINARY RGB DATA>
$lines = preg_split('/\n/', $contents);
// Ensure that there are exactly 4 lines of data
if(count($lines) != 4)
die("Unexpected results from pngtopnm.");
// Check that the first line is correct
$type = $lines[0];
if($type != 'P6')
die("Unexpected pnm file header.");
// Get the width and height (in an array)
$dimensions = preg_split('/ /', $lines[1]);
// Get the data and convert it to an array of RGB bytes
$data = $lines[3];
$bytes = unpack('C*', $data);
print_r($bytes);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.