This technique, we know the basic practice of GD library, uses fewer scenarios, but if you can do it, it will always make you stand out in more situations; Lay the foundation for our technology
/ / black and white
$image_path = "1.jpg";
// $image_path="2.png";
$im = imagecreatefromjpeg($image_path);
// ImagecreateFromgIf for Gif, imagecreatefrompng for PNG...
if (imageistruecolor($im)) {
imagetruecolortopalette($im.false.256);
// If it is a true color image, convert the true color image to a palette image
}
for ($i = 0; $i < imagecolorstotal($im);/* Get the number of colors in the palette */ $i{+ +)$rgb = imagecolorsforindex($im.$i);// Get the color value of the color I point
$gray = round(0.229 * $rgb['red'] + 0.587 * $rgb['green'] + 0.114 * $rgb['blue']);
// Get the gray value of the color
if ($gray< =128) $gray = 0; else $gray = 255;
imagecolorset($im.$i.$gray.$gray.$gray);// Set the I point color value
}
header('Content-Type: image/jpeg');
// Set the image type. Also, if you want to generate a GIF or PNG image, replace it with the corresponding header
imagejpeg($im);
// Use imagegIf for GIF and imagepng for PNG.
imagedestroy($im);
// Destroy images to release resources
Copy the code