-->

获取与透明文件缩略图(Get file Thumbnail image with transpare

2019-11-02 11:56发布

我想获得文件的透明度缩略图。
我有以下的代码来实现它:

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

我是混合性代码从这里:
有没有的BitmapSource和位图之间进行转换的好方法?

从System.Drawing.Bitmap加载WPF BitmapImage的

有了这种方式,我转换BitmapSource为位图,然后我隐蔽的位图BitmapImage 。 我敢肯定有办法隐蔽BitmapSource直接BitmapImage 同时节省了透明度

Answer 1:

您将需要编码BitmapSourceBitmapImage ,你可以选择你在这个例子想我使用任何编码器PngBitmapEncoder

例:

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


Answer 2:

你尝试:System.Drawing.Imaging.PixelFormat.Format32bppArgb( Format32-P-ARGB之间的P)

MSDN:

Format32bppArgb - >指定格式为每像素32位; 每8个比特被用于α,红色,绿色和蓝色分量。

Format32bppPArgb - >指定格式为每像素32位; 每8个比特被用于α,红色,绿色和蓝色分量。 红色,绿色和蓝色分量根据所述预乘 alpha分量。



文章来源: Get file Thumbnail image with transparency