2020-08-05 14:06:42 -07:00
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System ;
2020-06-01 12:35:37 -07:00
using System.IO ;
2020-10-29 17:52:35 -07:00
using System.Reflection ;
2020-06-01 12:35:37 -07:00
using System.Security.Cryptography ;
using System.Windows.Media ;
using System.Windows.Media.Imaging ;
2020-10-29 17:52:35 -07:00
using Wox.Plugin.Logger ;
2020-06-01 12:35:37 -07:00
namespace Wox.Infrastructure.Image
{
public class ImageHashGenerator : IImageHashGenerator
{
2020-10-29 17:52:35 -07:00
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Suppressing this to enable FxCop. We are logging the exception, and going forward general exceptions should not be caught")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "Level of protection needed for the image data does not require a security guarantee")]
2020-06-01 12:35:37 -07:00
public string GetHashFromImage ( ImageSource imageSource )
{
if ( ! ( imageSource is BitmapSource image ) )
{
return null ;
}
try
{
using ( var outStream = new MemoryStream ( ) )
{
// PngBitmapEncoder enc2 = new PngBitmapEncoder();
// enc2.Frames.Add(BitmapFrame.Create(tt));
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 = new SHA1CryptoServiceProvider ( ) )
{
var hash = Convert . ToBase64String ( sha1 . ComputeHash ( byteArray ) ) ;
return hash ;
}
}
}
2020-10-29 17:52:35 -07:00
catch ( System . Exception e )
2020-06-01 12:35:37 -07:00
{
2020-10-29 17:52:35 -07:00
Log . Exception ( $"Failed to get hash from image" , e , MethodBase . GetCurrentMethod ( ) . DeclaringType ) ;
2020-06-01 12:35:37 -07:00
return null ;
}
}
}
2020-08-05 14:06:42 -07:00
}