Fastest way to read PNG metadata in PHP

坚强是说给别人听的谎言 提交于 2019-12-08 01:39:15

问题


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,

Jonathan


回答1:


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.



来源:https://stackoverflow.com/questions/4093393/fastest-way-to-read-png-metadata-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!