Get file Thumbnail image with transparency

空扰寡人 提交于 2019-12-13 04:32:14

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18906849/get-file-thumbnail-image-with-transparency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!