DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

Question

I am new to PHP and I am trying to remove colour(s) from a JPEG image on my server. Ideally, I want to be able to remove every colour in the image other than black or grey. I have posted code below of what I have done so far but it is not working (or it is working but I am not displaying it right). When I run the code, I get nothing on my screen. This is all the code in my index.php file so far:

$my_image='Photo.jpg';
header('Content-Type: image/jpeg');

$img = imagecreatefromjpeg($my_image); 
$color = imagecolorallocate($img, 255, 255, 255);
imagecolortransparent($img, $color);
imagejpeg($my_image, null);

Can someone tell me how to fix my problem please? Thank you!

Solution

You have several problems:

  • imagecreatefromstring doesn't load images from a file, but takes a string that contains image data. imagecreatefromjpeg will load from a file.
  • To display a page as an image, you have to send the proper header. For example, header('Content-Type: image/jpeg');
  • imagejpeg outputs an image. The return value is just whether or not it succeeded. Take a look at the example in the documentation.

To delete every color that isn't black/gray/white, you probably have to check each pixel individually, like so:

<?php
header('Content-type: image/jpeg');
$image = imagecreatefromjpeg('file.jpg');

$white = imagecolorallocate($image, 255, 255, 255);

for($x = 0; $x < imagesx($image); $x++) {
   for($y = 0; $y < imagesy($image); $y++) {
      $pixel = imagecolorat($image, $x, $y);
      if(!isGray($pixel))
         imagesetpixel($image, $x, $y, $white);
   }
}

imagejpeg($image);

function isGray($pix) {
   $r = ($pix >> 16) & 0xFF;
   $g = ($pix >> 8) & 0xFF;
   $b = $pix & 0xFF;
   return ($r == $g) && ($g == $b);
}
?>

Since you're using JPGs, I can't think of an easier way. The artifacts the JPG compression process creates disrupt solid colors, so simply checking for, e.g., red or blue wouldn't work.

The code was adapted from https://stackoverflow.com/a/1607796/246847.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow