Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - New Imagick changes md5() of an image

I'm working on an Image Uploader that needs to check md5 of an image to prevent uploading a duplicate image. When an image is uploaded I create a new Imagick using the uploaded path and get the contents of the image. Calling md5() and passing the image contents returns a different value from PHP's md5_file and md5sum from the command line. The md5 is stored on the design image object in the database because I need to compare the md5 of an uploaded image to existing images. The issue is calling md5 on the new Imagick contents returns a different value each time the same image is uploaded.

$sUploadedImage = '/home/user/test-12x14.png';

md5(file_get_contents($sUploadedImage));
returns  2352513cde38cfb678cf46b6421f2f8b

md5_file($sUploadedImage);
returns  2352513cde38cfb678cf46b6421f2f8b

// md5sum on Linux 
md5sum /home/user/test-12x14.png 
returns 2352513cde38cfb678cf46b6421f2f8b 

$oImagick = new Imagick($sUploadedImage);
md5($oImagick->getImageBlob());
returns 0a8acb080aedf6245b56d39fb705705f
//returns different value on everytime same image is uploaded

$sNewPath = sfConfig::get('sf_root_dir') . '/design-images/' .$sMd5 .'.png';
$oNewImage->writeFileWithFormat($sNewPath, 'png');

md5(file_get_contents($sNewPath));
returns  2352513cde38cfb678cf46b6421f2f8b

md5_file($sNewPath);
returns  2352513cde38cfb678cf46b6421f2f8b

Why is the md5() result on the Imagick different? Thanks in advance.

like image 572
saturdayborn Avatar asked Jan 17 '17 20:01

saturdayborn


1 Answers

The issue is that PNG files, and some other formats, include a creation date and time in the file and that date will be different. ImageMagick has built-in functions that just check the image data itself rather than md5sum which checks the whole file including the metadata.

See here at the command line, I create two images with exactly the same gradient in them:

convert -size 256x256 gradient:red-yellow a.png
convert -size 256x256 gradient:red-yellow b.png

Now check them with md5sum and they differ:

md5 [ab].png
MD5 (a.png) = fbd2be1c89edad043b1d128aaf32a042
MD5 (b.png) = ab08909a80d347d573f5f0f68b2b342e

But check just the image data and not the metadata and they are the same:

identify -format "%#\n" [ab].png
47d48b4144f35ca431e7db577a2b6284ef90649c30ffe9c0b9234aa282297c61
47d48b4144f35ca431e7db577a2b6284ef90649c30ffe9c0b9234aa282297c61

In PHP, you probably want Imagick::getImageSignature(void)

like image 188
Mark Setchell Avatar answered Nov 14 '22 19:11

Mark Setchell