2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | using System; using System.IO; using System.Drawing; namespace SimilarPhoto { class SimilarPhoto { Image SourceImg; public SimilarPhoto(string filePath) { SourceImg = Image.FromFile(filePath); } public SimilarPhoto(Stream stream) { SourceImg = Image.FromStream(stream); } public String GetHash() { Image image = ReduceSize(); Byte[] grayValues = ReduceColor(image); Byte average = CalcAverage(grayValues); String reslut = ComputeBits(grayValues, average); return reslut; } // Step 1 : Reduce size to 8*8 private Image ReduceSize(int width = 8, int height = 8) { Image image = SourceImg.GetThumbnailImage(width, height, () = >{ return false; }, IntPtr.Zero); return image; } // Step 2 : Reduce Color private Byte[] ReduceColor(Image image) { Bitmap bitMap = new Bitmap(image); Byte[] grayValues = new Byte[image.Width * image.Height]; for (int x = 0; x < image.Width; x++) for (int y = 0; y < image.Height; y++) { Color 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(string a, string b) { if (a.Length != b.Length) throw new ArgumentException(); int count = 0; for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) count++; } return count; } } } |
©Copyright 2015-2021, 新雨网 [service@newrain.cn]。京ICP备15047473号-1
[页面更新时间:2024/10/5 2:40:52 ,构建时间:0.0625016 "秒]