Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an Image Greyscale with GD Library

Tags:

php

image

gd

My mission is to create a little app where you can upload a picture, and the app will turn it into ASCII art. I'm sure these exist already but I want to prove that I can do it myself.

This would involve taking an image, making it greyscale and then matching each pixel with a character depending on how dark the picture is and how full the character is.

So my question is, Using the GD Library (or i guess some other means if necessary) how do I make an image black and white?

like image 372
The.Anti.9 Avatar asked Nov 27 '22 00:11

The.Anti.9


2 Answers

As pointed out by nickf in his comment, the simple formula (pixel.r + pixel.g + pixel.b) / 3 is not correct. Use the GD-included function imagefilter() (no need to iterate over all pixels in an image using PHP loops) instead:

$im = imagecreatefrompng('dave.png');
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagepng($im, 'dave.png');
like image 88
Stefan Gehrig Avatar answered Dec 06 '22 00:12

Stefan Gehrig


To make it purely black and white (as you wrote) use this

imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -1000);
like image 30
Mark Lalor Avatar answered Dec 05 '22 22:12

Mark Lalor