JD2022-TU1/main/tools/modules/JD.Quik/Helpers/ImageHelpers.cs

105 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
namespace JD.Quik.Helpers
{
public class ImageHelpers
{
private static readonly Dictionary<string, BitmapImage> _imageCache = new Dictionary<string, BitmapImage>();
public static BitmapImage GetImageForFilePath(string filePath)
{
var extension = Path.GetExtension(filePath) ?? "";
if (_imageCache.ContainsKey(extension))
{
return _imageCache[extension];
}
var image = ComputeIconFromWindows(filePath);
if (image != null)
{
var bitmapImage = ConvertImageToBitmapImage(image);
_imageCache.Add(extension, bitmapImage);
return bitmapImage;
}
return null;
}
private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0; // 'Large icon
private const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int DestroyIcon(IntPtr hIcon);
private static BitmapImage ConvertImageToBitmapImage(Image img)
{
using (var memory = new MemoryStream())
{
img.Save(memory, ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
return bitmapImage;
}
}
private static Image ComputeIconFromWindows(string fileName)
{
SHFILEINFO shinfo = new SHFILEINFO();
try
{
SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);
if (shinfo.hIcon == IntPtr.Zero)
return null;
using (Icon icon = Icon.FromHandle(shinfo.hIcon))
{
Bitmap bm = new Bitmap(icon.Size.Width, icon.Size.Height);
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawIcon(icon, 0, 0);
}
return bm;
}
}
finally
{
if (shinfo.hIcon != IntPtr.Zero)
DestroyIcon(shinfo.hIcon);
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct SHFILEINFO
{
public readonly IntPtr hIcon;
public readonly int iIcon;
public readonly uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public readonly string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public readonly string szTypeName;
};
}
}