In PHP, a simple read and write file can be done by using fread() and fwrite(). The unpack() and pack() operator are used to extract binary information.
The question is, how can I read and write PGM (P5) image in PHP without using any additional PHP extension / library?
According to the spec: Portable Gray Map
This looks pretty simple.
You don't even need pack/unpack as
sscanf()
should cope with most of the ASCII to integer translation.This C program which converts PGM to BMP may give you a few pointers.
Depending on maximum value for gray you will have to use
C*
for values up to 255 andn*
for greater values.Sample class to read / write all pixel from array:
Test case for your file:
I wrote a simple function to convert an image resource to PGM (portable graymap) in order to feed it to an OCR program. It works just like the rest of the image output functions, and will convert to grayscale for you: