We have supplier sheet for import products in Magento.
problem :
in supplier sheet the images are in a different folder but with the same image
like :
folder1/image.jpg
folder2/image.jpg
Now when we import in Magento all image goes in the same folder. And each product has the same image.
How can we I solve this?
If the names of the images are always going to be the same (as in your example), then you can simply store all of the image names that you process (excluding directories), and just check if it is in that array.
Otherwise, you're going to have to compare the images, as shown below. This code assumes you have an array of filenames for each image called $filenames
.
$imageHashes = []; //Define an array where hash of each image will be stored
$uniqueFiles = []; //The array which will contain only image files that are unique.
for ($i=0;$i<count($filenames);$i++) { //Loop through the filenames
$hash = md5_file($filenames[$i]); //Get the hash of the image
if (!in_array($hash,$imageHashes)) { //If the imageHashes array does not contain the hash, then this is a new image
$imageHashes[] = $hash; //Add the hash to the imageHashes array
$uniqueFiles[] = $filenames[$i]; //Add the filename to the list of filenames for unique images.
}
}
This works because a hashing algorithm should generate a different hash for anything put into it. While md5
has been insecure for storing passwords for a long time, it is still perfectly fine to use it in this context.
Thus, every time the loop runs, it gets the hash of the file for the current file name, and then checks if that hash already exists in the array. If it does, then nothing happens (remember that the same file should always have the same hash, and thus identical clones of an image should share the same hash as well) as the image has already been found and processed. Otherwise, we add the hash to the $imageHashes
table (so that we can compare against it in the next pass), and add the filename to the $uniqueFiles
array, so that we can use it later.
By the end of this process, we should have an array which contains only the file names of the first occurrence of each image.
You can find more info about the md5_file
in the PHP Manual;
There's a great StackOverflow post here that discusses other ways to compare two image files using PHP.