用途:
研究从PhoneView中拿出来的iPhone/iPad应用程序中的png文件。
[转]
修正iPhone里的png文件为标准格式
2010年05月03日 星期一 23:13
本想“借”用一下iphone里漂亮的天气图标,没想到在pc上无法使用。google了
一下才知道iphone里的png文件并不是标准格式,不知道什么原因,apple在png文件头之后加了一个非标准的CgBI数据段,IDAT段图像数
据也没有传统的压缩数据头和尾,并且红色和蓝色是反的。国外已经有了把iphone上的png文件转换为标准格式的,
我不太会编译,所以自己用php照猫画虎写了个转换函数。
转换后的效果:
使用方法:
运行后,修正后的图片会放到fixed文件夹内。
如果要修正一个目录下的所有png文件,可以这样做:
foreach (glob($path .
'/*.png') as $image)
{
iphone_fix_png($image);
}
iphone_fix_png函数代码如下:
下载:
- /**
- * fix iPhone PNGs to
PNG-compatible format
- *
- * @author: legend <legendsky@hotmail.com>
- * @copyright UGiA.CN
- * @link:
- *
- * usage:
- *
- *
include('iphone_fix_png.php');
- *
- * iphone_fix_png($path);
- */
- function iphone_fix_png($file)
- {
- $png_header = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"; // PNG
- $data_chunk = "\x49\x44\x41\x54"; // IDAT
- $end_chunk = "\x49\x45\x4e\x44"; // IEND
- $cgbi_chunk = "\x43\x67\x42\x49"; // CgBI
-
- // read chunks
- $size = filesize($file);
- $fp = fopen($file, "r");
-
- // check png header
- $header = fread($fp, 8);
- if
($header != $png_header)
- {
- trigger_error("Not a PNG file!", E_USER_ERROR);
- return false;
- }
-
- // generate output path
- $base = dirname($file);
- preg_match("/(.+?)(\.png)$/i", basename($file), $m);
- $filename = $m[1];
- $suffix = $m[2];
-
- if
(is_dir($base . "/fixed") || false != @mkdir($base .
"/fixed", 0700))
- {
- $path = $base . "/fixed/" . basename($file);
- }
- else
- {
- $path = $base . "/" . $filename . "_fixed" . $suffix;
- }
-
- // output stream
- $fd = fopen($path, "w");
- fwrite($fd, $png_header);
-
- $offset = 8;
-
- // do
- while ($offset < $size)
- {
- $length = current(unpack('N', fread($fp, 4)));
- $chunk = array (
- 'length' => pack('N', $length),
- 'name' => fread($fp, 4),
- 'data' => $length > 0 ? fread($fp, $length) : '',
- 'crc' => fread($fp, 4)
- );
-
- $offset += 4 + 4 + $length + 4;
-
- // fix IDAT chunk
- if
($chunk['name'] == $data_chunk)
- {
- $inflated = gzinflate($chunk['data']);
- $deflated = gzcompress($inflated);
-
- $chunk['data'] = $deflated;
- $chunk['length'] = pack('N', strlen($deflated));
- $chunk['crc'] = pack('N', crc32($data_chunk . $deflated));
- }
-
- // drop cgbi chunk
- if
($chunk['name'] != $cgbi_chunk)
- {
- fwrite($fd, join("", $chunk));
- }
- }
-
- fclose($fp);
- fclose($fd);
-
- // flip the red/blue
channels
- $im = imagecreatefrompng($path);
- imagesavealpha($im, true); // save alpha
-
- for
($i = 0; $i
< imagesx($im); $i++)
- {
- for
($j = 0; $j
< imagesy($im); $j++)
- {
- $rgba = imagecolorat($im, $i, $j);
-
- $a = ($rgba
& 0x7F000000) >> 24;
- $r = ($rgba
& 0xFF0000) >> 16;
- $g = ($rgba
& 0x00FF00) >> 8;
- $b = ($rgba
& 0x0000FF);
-
- $color = imagecolorallocatealpha($im, $b, $g, $r, $a);
-
- imagesetpixel($im, $i, $j, $color);
- }
- }
-
- imagepng($im, $path);
- }
参考:
阅读(1449) | 评论(0) | 转发(0) |