Home >Backend Development >PHP Tutorial >Write a PHP script to filter images uploaded by users, _PHP tutorial
Example Download
I accidentally discovered a very useful class file on phpclasses.org, developed by Bakr Alsharif, which can help developers detect nude photos based on skin pixels.
It analyzes the colors used in different parts of an image and decides if they match the hue of human skin color.
As a result of the analysis, it returns a score that reflects the likelihood that the image contains nudity.
In addition, it can output the analyzed image, with pixels marked using a given color skin tone.
Currently it can analyze PNG, GIF and JPEG images.
The following shows how to use this PHP class.
Let’s start with the nf.php file that contains the nudity filter.
include ('nf.php');
Next, create a new class called ImageFilter and put it in a variable called $filter.
$filter = new ImageFilter;
Get the score of the image and put it into a $score variable.
$score = $filter -> GetScore($_FILES['img']['tmp_name']);
If the image score is greater than or equal to 60%, then display a (alert) message.
if($score >= 60){ /*Message*/ }
Here are all the PHP codes:
<?php /*Include the Nudity Filter file*/ include ('nf.php'); /*Create a new class called $filter*/ $filter = new ImageFilter; /*Get the score of the image*/ $score = $filter -> GetScore($_FILES['img']['tmp_name']); /*If the $score variable is set*/ if (isset($score)) { /*If the image contains nudity, display image score and message. Score value if more than 60%, it is considered an adult image.*/ if ($score >= 60) { echo "Image scored " . $score . "%, It seems that you have uploaded a nude picture."; /*If the image doesn't contain nudity*/ } else if ($score < 0) { echo "Congratulations, you have uploaded an non-nude image."; } } ?>
Markup language
We can upload images using a basic HTML form.
<form method="post" enctype="multipart/form-data" action="<?php echo $SERVER['PHP_SELF'];?> "> Upload image: <input type="file" name="img" id="img" /> <input type="submit" value="Sumit Image" /> </form>