I want to get file's thumbnail with transparency.
I have the following code to achieve it:
BitmapImage GetThumbnail(string filePath)
{
ShellFile shellFile = ShellFile.FromFilePath(filePath);
BitmapSource shellThumb = shellFile.Thumbnail.ExtraLargeBitmapSource;
Bitmap bmp = new Bitmap(shellThumb.PixelWidth, shellThumb.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
shellThumb.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.CacheOption = BitmapCacheOption.None;
bi.EndInit();
return bi;
}
I mixed the codes from here:
Is there a good way to convert between BitmapSource and Bitmap?
and
Load a WPF BitmapImage from a System.Drawing.Bitmap
With this way, I convert BitmapSource
to Bitmap, then I covert the Bitmap to BitmapImage
.
I am pretty sure there's a way to covert BitmapSource
directly to BitmapImage
while saving the transparency.
You will need to encode the BitmapSource
to a BitmapImage
, you can choose any encoder you want in this example I use PngBitmapEncoder
Example:
private BitmapImage GetThumbnail(string filePath)
{
ShellFile shellFile = ShellFile.FromFilePath(filePath);
BitmapSource shellThumb = shellFile.Thumbnail.ExtraLargeBitmapSource;
BitmapImage bImg = new BitmapImage();
PngBitmapEncoder encoder = new PngBitmapEncoder();
var memoryStream = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(shellThumb));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
return bImg;
}