Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 41 additions & 12 deletions Flow.Launcher.Infrastructure/Image/ImageHashGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using System.IO;
using System.Buffers;
using System.Security.Cryptography;
using System.Windows.Media;
using System.Windows.Media.Imaging;
Expand All @@ -10,27 +10,56 @@ public interface IImageHashGenerator
{
string GetHashFromImage(ImageSource image);
}

public class ImageHashGenerator : IImageHashGenerator
{
public string GetHashFromImage(ImageSource imageSource)
{
if (imageSource is not BitmapSource image)
if (imageSource is not BitmapSource { IsFrozen: true } image)
{
return null;
}

try
{
using var outStream = new MemoryStream();
var enc = new JpegBitmapEncoder();
var bitmapFrame = BitmapFrame.Create(image);
bitmapFrame.Freeze();
enc.Frames.Add(bitmapFrame);
enc.Save(outStream);
var byteArray = outStream.GetBuffer();
using var sha1 = SHA1.Create();
var hash = Convert.ToBase64String(sha1.ComputeHash(byteArray));
return hash;
// Normalize to a deterministic pixel format (32-bit premultiplied BGRA)
BitmapSource normalized = image;
if (normalized.Format != PixelFormats.Pbgra32)
{
var converted = new FormatConvertedBitmap();
converted.BeginInit();
converted.Source = normalized;
converted.DestinationFormat = PixelFormats.Pbgra32;
converted.EndInit();
converted.Freeze();

normalized = converted;
}

// Since we forced Pbgra32, we know it is exactly 4 bytes per pixel.
const int bytesPerPixel = 4;

var stride = normalized.PixelWidth * bytesPerPixel;
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
var bufferSize = stride * normalized.PixelHeight;

if (bufferSize <= 0)
return null;

// Use ArrayPool to prevent Large Object Heap (LOH) allocations for big images
var rentedPixelBuffer = ArrayPool<byte>.Shared.Rent(bufferSize);

try
{
normalized.CopyPixels(rentedPixelBuffer, stride, 0);

// Slice the rented array to the exact buffer size (Rented arrays are often larger than the requested size)
var hashBytes = SHA1.HashData(rentedPixelBuffer.AsSpan(0, bufferSize));
return Convert.ToBase64String(hashBytes);
}
finally
{
ArrayPool<byte>.Shared.Return(rentedPixelBuffer);
}
}
catch
{
Expand Down
Loading