Home Backend Development PHP Tutorial PHP image similarity code example

PHP image similarity code example

Jul 25, 2016 am 08:52 AM

  1. /**

  2. * Image similarity comparison
  3. *
  4. * @version $Id: ImageHash.php 4429 2012-04-17 13:20:31Z jax $
  5. * @authorjax.hu
  6. * www.osxue.com
  7. *//Sample_1
  8. *$aHash = ImageHash::hashImageFile('wsz.11.jpg');
  9. *$bHash = ImageHash::hashImageFile('wsz.12.jpg');
  10. *var_dump(ImageHash::isHashSimilar($aHash, $bHash));
  11. *
  12. *//Sample_2
  13. *var_dump(ImageHash::isImageFileSimilar('wsz.11.jpg', 'wsz.12.jpg'));
  14. *
  15. */

  16. class ImageHash {

  17. /**Sampling rate 1~10
  18. * @access public
  19. * @staticvar int
  20. **/
  21. public static $rate = 2;

  22. /**Similarity allowed value 0~64

  23. * @access public
  24. * @staticvar int
  25. **/
  26. public static $similarity = 80;

  27. /**The opening function corresponding to the image type

  28. * @access private
  29. * @staticvar string
  30. **/
  31. private static $_createFunc = array(
  32. IMAGETYPE_GIF =>'imageCreateFromGIF',
  33. IMAGETYPE_JPEG=>'imageCreateFromJPEG',
  34. IMAGETYPE_PNG =>'imageCreateFromPNG',
  35. IMAGETYPE_BMP =>'imageCreateFromBMP',
  36. IMAGETYPE_WBMP=>'imageCreateFromWBMP',
  37. IMAGETYPE_XBM =>'imageCreateFromXBM',
  38. );

  39. /**Create an image from a file

  40. * @param string $filePath file address path
  41. * @return resource When the image is successfully opened, the image resource ID is passed, and if it fails, it is false
  42. **/
  43. public static function createImage($filePath){
  44. if(!file_exists($filePath)){ return false; }

  45. /*判断文件类型是否可以开启*/

  46. $type = exif_imagetype($filePath);
  47. if(!array_key_exists($type,self::$_createFunc)){ return false; }

  48. $func = self::$_createFunc[$type];

  49. if(!function_exists($func)){ return false; }

  50. return $func($filePath);

  51. }

  52. /**hash image

  53. * @param resource $src image resource ID
  54. * @return string image hash value, false on failure
  55. **/
  56. public static function hashImage($src){
  57. if(!$src){ return false; }

  58. /*缩小图片尺寸*/

  59. $delta = 8 * self::$rate;
  60. $img = imageCreateTrueColor($delta,$delta);
  61. imageCopyResized($img,$src, 0,0,0,0, $delta,$delta,imagesX($src),imagesY($src));

  62. /*计算图片灰阶值*/

  63. $grayArray = array();
  64. for ($y=0; $y<$delta; $y++){
  65. for ($x=0; $x<$delta; $x++){
  66. $rgb = imagecolorat($img,$x,$y);
  67. $col = imagecolorsforindex($img, $rgb);
  68. $gray = intval(($col['red']+$col['green']+$col['blue'])/3)& 0xFF;

  69. $grayArray[] = $gray;

  70. }
  71. }
  72. imagedestroy($img);

  73. /*计算所有像素的灰阶平均值*/

  74. $average = array_sum($grayArray)/count($grayArray);

  75. /*计算 hash 值*/

  76. $hashStr = '';
  77. foreach ($grayArray as $gray){
  78. $hashStr .= ($gray>=$average) ? '1' : '0';
  79. }
  80. return $hashStr;
  81. }

  82. /**hash image file

  83. * @param string $filePath file address path
  84. * @return string image hash value, false on failure
  85. **/
  86. public static function hashImageFile($filePath){
  87. $src = self::createImage($filePath);
  88. $hashStr = self::hashImage($src);
  89. imagedestroy($src);

  90. return $hashStr;

  91. }

  92. /**Compare two hash values ​​to see if they are similar

  93. * @param string $aHash The hash value of picture A
  94. * @param string $bHash The hash value of picture B
  95. * @return bool If the pictures are similar, true will be passed, otherwise false
  96. **/
  97. public static function isHashSimilar($aHash, $bHash){
  98. $aL = strlen($aHash); $bL = strlen($bHash);
  99. if ($aL !== $bL){ return false; }

  100. /*计算容许落差的数量*/

  101. $allowGap = $aL*(100-self::$similarity)/100;

  102. /*计算两个 hash 值的汉明距离*/

  103. $distance = 0;
  104. for($i=0; $i<$aL; $i++){
  105. if ($aHash{$i} !== $bHash{$i}){ $distance++; }
  106. }

  107. return ($distance<=$allowGap) ? true : false;

  108. }

  109. /**Compare two image files to see if they are similar

  110. * @param string $aHash The path of image A
  111. * @param string $bHash The path of image B
  112. * @return bool When the images are similar, true is passed, otherwise false
  113. **/
  114. public static function isImageFileSimilar($aPath, $bPath){
  115. $aHash = ImageHash::hashImageFile($aPath);
  116. $bHash = ImageHash: :hashImageFile($bPath);
  117. return ImageHash::isHashSimilar($aHash, $bHash);
  118. }
  119. }>
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles