Similar Image Search (php)

This is more or less a tutorial of how to compare images as strings and find the most similar image using php similar_text();

Here is my whole tiny source with the explanation in the comments.
<?php
function image_square($url){
    
//get a string of any image
    
$ch curl_init();
    
curl_setopt($chCURLOPT_URL$url);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1); 
    
curl_setopt($chCURLOPT_FOLLOWLOCATION1);
    
$image_soure curl_exec($ch);
    
curl_close($ch);
    
//basic booleans to tell image type
    
if(preg_match("/png/i"$image_soure$m)) {
        
$image imagecreatefrompng($url);
    }elseif(
preg_match("/gif/i"$image_soure$m)){
        
$image imagecreatefromgif($url);
    }elseif(
preg_match("/(jf|Ex)if/i"$image_soure$m)){
        
$image imagecreatefromjpeg($url);
    }
    
//create 16*16 image and mash together
    
$width imagesx($image);
    
$height imagesy($image);
    
imagealphablending($imagefalse);
    
imagesavealpha($imagetrue);
    
$image_p imagecreatetruecolor(1616);
    
imagecopyresampled($image_p$image00001616$width$height);
    
//save output to return, then delete output
    
$m md5(rand(-999,999));
    
imagepng($image_p"temp$m.png");
    
$output file_get_contents("temp$m.png");
    
unlink("temp$m.png");
    return 
$output;
}
$a image_square('http://localhost:8888/image1.jpg');
$b image_square('http://localhost:8888/image2.jpg');
$c image_square('http://localhost:8888/image3.jpg');
//compare the PNG binary strings
$sim1 similar_text($a$b);
$sim2 similar_text($a$c);
die(
"a similarity to b: ".$sim1."\n<br>".
    
"a similarity to c: ".$sim2);
// returns
// a similarity to b: 60
// a similarity to c: 78
?>

Leave a Reply

Your email address will not be published. Required fields are marked *