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;
}

其他提示

Did you try: System.Drawing.Imaging.PixelFormat.Format32bppArgb (without the P between Format32-P-Argb)

MSDN:

Format32bppArgb -> Specifies that the format is 32 bits per pixel; 8 bits each are used for the alpha, red, green, and blue components.

Format32bppPArgb -> Specifies that the format is 32 bits per pixel; 8 bits each are used for the alpha, red, green, and blue components. The red, green, and blue components are premultiplied, according to the alpha component.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top