开发者

Fastest way to read PNG metadata in PHP

开发者 https://www.devze.com 2023-01-23 04:49 出处:网络
I would like to extract two fields from a PNG file. Namely, the geometry field and one of the fields from the metadata.

I would like to extract two fields from a PNG file. Namely, the geometry field and one of the fields from the metadata.

What is the fastest way I could go about doing this? I have benchmarked my script that currently performs this and by far the slowest action is executing the actual ImageMagick "identify" program on the PNG file. (.4 seconds vs .0001 seconds to parse the outputted array for the geometry and 8.39E-5 seconds to parse key phrases from the metadata)

Thanks in advance for any help,

J开发者_开发百科onathan


I'm not familiar with any ready-made libraries or classes to do it in PHP without a subprocess call, but if you can't find one, writing your own would definitely be the way to go.

PNG's a fairly simple block stream format, so seeking to a specific block and extracting some header fields is trivial.

All you'd need is something which reads and checks the 8-byte 89 50 4E 47 0D 0A 1A 0A PNG header and then alternates between reading 8 bytes (chunk length plus type) and seeking past the block using the length until you hit the chunk type you want.

For the geometry, assuming the PNG follows the spec, here's how it'd go:

  1. Read and verify PNG header (8 bytes)
  2. Read and check header of first block (8 bytes)
    1. Success. type = IHDR
    2. Read additional 8 bytes for geometry (width, height. 4 bytes each)
  3. If the other field you wanted isn't in IHDR, use the chunk size from step 2 to seek to the next block in search of the other field you wanted.

It'd probably take me 5 to 15 minutes to whip something like that up in Python. (I've done similar things with RAR and GIF) Maybe 15 to 25 in PHP since I've got less experience doing low-level file I/O in it.

0

精彩评论

暂无评论...
验证码 换一张
取 消