/* Step 1: Reduce the image size to 8x8, with a total of 64 pixels. this step removes the differences between different image sizes and image proportions, and only retains basic information such as the structure and brightness. ** the second step is to convert the image into a grayscale image, convert to 64-level grayscale image ** step 3 Calculate the gray average value of all pixels in the image ** Step 4 compare the gray scale of each pixel with the average value, if it is greater than or equal to the average value, it is recorded as 1, and if it is less than the average value, it is recorded as 0. ** in step 5, calculate the hash value and combine the comparison results in the previous step to form a 64-bit binary integer, which is the fingerprint of the image. ** after comparing the image fingerprints in step 6, you can compare the fingerprints of different images and calculate the number of different 64-bit images. if the number of different data digits does not exceed 5, the two images are very similar. If the number is greater than 10, they are two different images. */
Using system; using system. drawing; using system. io; namespace similarphoto {class imghash {image sourceimg; Public imghash (string filepath) {sourceimg = image. fromfile (filepath);} public imghash (Stream stream) {sourceimg = image. fromstream (Stream);} Public String gethash () {image = performancesize (); byte [] grayvalues = performancecolor (image); byte average = calcaverage (grayvalues); string reslut = Computebits (grayvalues, average); Return reslut;} // Step 1: reduce size to 8*8 private image performancesize (INT width = 8, int Height = 8) {image = sourceimg. getthumbnailimage (width, height, () =>{ return false ;}, intptr. zero); Return image;} // Step 2: Reduce color private byte [] reducecolor (image) {Bitmap bitmap = new Bitmap (image ); byte [] grayvalues = new byte [image. width * I Mage. height]; for (INT x = 0; x <image. width; X ++) for (INT y = 0; y <image. height; y ++) {color = bitmap. getpixel (x, y); byte grayvalue = (byte) (color. R * 30 + color. g * 59 + color. (B * 11)/100); grayvalues [x * image. width + Y] = grayvalue;} return grayvalues;} // Step 3: Average the colors private byte calcaverage (byte [] values) {int sum = 0; for (INT I = 0; I <values. length; I ++) Sum + = (INT) Values [I]; return convert. tobyte (sum/values. length);} // Step 4: Compute the bits private string computebits (byte [] values, byte averagevalue) {char [] result = new char [values. length]; for (INT I = 0; I <values. length; I ++) {If (Values [I] <averagevalue) result [I] = '0'; else result [I] = '1 ';} return new string (result);} // compare hash public static int32 calcsimilardegree (St Ring A, string B) {If (A. length! = B. length) throw new argumentexception (); int COUNT = 0; For (INT I = 0; I <. length; I ++) {if (a [I]! = B [I]) Count ++;} return count ;}}}