Skip to content

Commit

Permalink
Merge pull request #489 from vcsjones/hash-memory
Browse files Browse the repository at this point in the history
Improve performance of hashing and reduce memory
  • Loading branch information
Webreaper authored Aug 24, 2023
2 parents 18e2180 + 564757f commit cdd2e12
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
11 changes: 7 additions & 4 deletions Damselfly.Core.ImageProcessing/ImageSharpProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using CoenM.ImageHash;
using CoenM.ImageHash.HashAlgorithms;
Expand Down Expand Up @@ -238,20 +238,23 @@ public static string GetHash(Image<Rgba32> image)
try
{
var hashWatch = new Stopwatch("CalcImageHash");
var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1);
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1);

image.ProcessPixelRows(pixelAccessor =>
{
for ( var y = 0; y < pixelAccessor.Height; y++ )
{
var pixelRowSpan = pixelAccessor.GetRowSpan(y);

var rgbaBytes = MemoryMarshal.AsBytes(pixelRowSpan).ToArray();
var rgbaBytes = MemoryMarshal.AsBytes(pixelRowSpan);
hash.AppendData(rgbaBytes);
}
});

result = hash.GetHashAndReset().ToHex(true);
Span<byte> buffer = stackalloc byte[SHA1.HashSizeInBytes];
hash.GetHashAndReset(buffer);
result = Convert.ToHexString(buffer);

hashWatch.Stop();
Logging.LogVerbose($"Hashed image ({result}) in {hashWatch.HumanElapsedTime}");
}
Expand Down
11 changes: 7 additions & 4 deletions Damselfly.Core.ImageProcessing/SkiaSharpProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Damselfly.Core.Constants;
using Damselfly.Core.DbModels.Images;
Expand Down Expand Up @@ -187,17 +187,20 @@ public async Task TransformDownloadImage(string input, Stream output, IExportSet

var pixels = sourceBitmap.GetPixelSpan();

var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1);
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1);

for ( var row = 0; row < sourceBitmap.Height; row++ )
{
var rowPixels = pixels.Slice(row * sourceBitmap.RowBytes, sourceBitmap.RowBytes);

var rgbaBytes = MemoryMarshal.AsBytes(rowPixels).ToArray();
var rgbaBytes = MemoryMarshal.AsBytes(rowPixels);
hash.AppendData(rgbaBytes);
}

result = hash.GetHashAndReset().ToHex(true);
Span<byte> buffer = stackalloc byte[SHA1.HashSizeInBytes];
hash.GetHashAndReset(buffer);
result = Convert.ToHexString(buffer);

hashWatch.Stop();
Logging.LogVerbose($"Hashed image ({result}) in {hashWatch.HumanElapsedTime}");
}
Expand Down

0 comments on commit cdd2e12

Please sign in to comment.