如何从Imagick对象中获取sha1哈希


How to get sha1 hash from Imagick object?

网站有点像画廊。但为了防止重复条目。我想匹配他们。它不会是100%防弹的图像匹配,但对于我的需求,它绝对是完美的解决方案。

唯一的问题是,我不知道从Imagick$image对象中获取sha1的正确方法。

这就是我现在所拥有的,它确实会产生混乱。但它与我在服务器上的不匹配。在服务器中,将图像优化到最小缩略图的过程也是一样的。除此之外,在每个图像操作块的末尾都有file_put_contents($root, $image);。但我认为问题不存在,我认为问题可能是,我在sha1()函数内的$image对象中缺少了一些东西。就像sha1($image->rendercurrentimage())一样。。

<?
$img_url = 'someimgfile.jpg';
# Step 1 = Original file hash - This is all ok
$source_hash = sha1_file($img_url);
$image = new Imagick($img_url);
# file_put_contents($source_root, $image);
$image->gaussianBlurImage(0, 0.05);
$image->setCompression(Imagick::COMPRESSION_JPEG);
$image->setCompressionQuality(90);
$image->setImageFormat('jpeg');
$image->scaleImage(215, 0);
# file_put_contents($thumbnail_root, $image);
# Step 2 = Get the thumbnail hash - results in a non matching hash vs. DB hash
$thumbnail_hash = sha1($image);
$image->setCompressionQuality(75); 
$image->cropThumbnailImage(102, 102);
# file_put_contents($smallthumbnail_root, $image);
# Step 3 = Get the even smaller thumbnail hash - results in a non matching hash vs. DB hash
$smallthumbnail_hash = sha1($image);
# now query to DB to check against all 3 hashes: $source_hash | $thumbnail_hash | $smallthumbnail_hash
# DB has lets say 1000 images, with source hash, thumbnail hash and small thumbnail hash saved in them
# NOTE: The process of scaling images as they enter the DB, is exactly the same, expect there are file_put_contents($root, $image); in between them.. I put them in and commented out, to show you the locations

正如我上面所说的。我有三种方式与服务器中的哈希匹配。所以原创,缩略图,甚至更小的缩略图。并用CCD_ 6函数创建。我想基本上模仿hole过程,但不想将文件保存在$root中,以防它是重复的,那里的for将被拒绝并重定向到匹配的条目。

如果你想知道,我为什么要匹配缩略图。这是因为,我的测试表明,如果原始文件的大小等可能不同,那么创建的缩略图会匹配得很好。还是我错了?如果我有相同的图像,在3个不同的尺寸。我将它们缩小到100px宽度。他们的散列会是一样的吗?

结论我不得不稍微重写一下原始的图像处理程序。但基本上,我认为我的代码中仍然缺少一个部分,比如$image->stripImage();。或者什么的。当它开始得到更好的结果。在服务器中保存哈希的最佳方式似乎是:

$hash = sha1(base64_encode($image->getImageBlob()));

我的测试还证实,file_put_contents($thumbnail_root, $image);然后通过sha1_file($image_root);获取哈希不会更改哈希值。

我还从缩小到拇指大小的较大图像中得到了更多的匹配结果。

由于您的问题是,您不想在文件系统上为正在执行的每个步骤创建一个文件,因此我建议您获取这些步骤的blob内容并创建其哈希。例如:

<?php
//quick and dirty image creation to demonstrate my point
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');
//base64 encode our blob and then generate a sha1 hash
$thumbnail = base64_encode( $image->getImageBlob() );
echo sha1($thumbnail);

如果你试图将两个不同(原始)大小的图像相互匹配,那么你可能会遇到重新采样的问题。例如,我有一张猴子的照片,它是200像素的正方形,另一张看起来一模一样,是400像素的正方形。如果我重新采样到200像素,图像就不总是匹配的。

只需使用此:

$sha1 = sha1_file($img_url);

但是在处理图像之前要小心获取sha1!你的所有哈希都应该根据用户上传的图像生成,这样你就可以将它们与未来图像的哈希进行比较,而无需首先处理它们。

注意!即使在保持比例的情况下重新缩放图像,哈希也会发生变化。即使在文本编辑器中打开文件并添加空白,哈希也会发生变化。

将图像缩放到相同宽度的想法可能会奏效,但前提是使用相同的函数或参数进行缩放。它不是100%可信的。