DEV Community

Eric COURTIAL
Eric COURTIAL

Posted on

Parse and edit a BMP file with PHP

I did not find any easy solution to open and parse a BMP file. For a personal project I had to perform this kind of operation, so I created a basic library, aggregating some tutorials and sources.

Let's start with the installation, classic:

composer require ecourtial/php-bmp-parser

Now we can easily open and parse the file. In the below example, I get the Red, Green, Blue and Hex value of the pixel located at x = 2, y = 0:

$service = new BmpService();
$image = $service->getImage('myBmpFile.bmp');
echo $image->getPixel(2, 0)->getR();
echo $image->getPixel(2, 0)->getG();
echo $image->getPixel(2, 0)->getB();
echo $image->getPixel(2, 0)->getHex();

This operation is quite simple, and does not require any third party library or PHP extension.

The library also allows basic editing, with some limitations though, and you will need this time the gd PHP extension.

In the below example, I want to edit the file previously opened and save it with another name. I change the color of one pixel, extends the size of the image (new pixels are white by default) and finally edit some of the newly added pixels.

$image->setPath('myNewBmpFile.bmp);
$image->getPixel(0, 1)->setR(0)->setG(0)->setB(126);
$image->setDimensions(3, 4);
$image->getPixel(0, 3)->setR(200)->setG(0)->setB(200);
$image->getPixel(1, 3)->setR(0)->setG(0)->setB(255);
$image = $service->update($image);

Very basic, but does the job.

Top comments (0)