【问题标题】:Get file Thumbnail image with transparency获取具有透明度的文件缩略图图像
【发布时间】:2013-09-19 23:58:05
【问题描述】:

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

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

我从这里混合了代码:
Is there a good way to convert between BitmapSource and Bitmap?

Load a WPF BitmapImage from a System.Drawing.Bitmap

通过这种方式,我将BitmapSource 转换为Bitmap,然后将Bitmap 转换为BitmapImage。 我很确定有办法将BitmapSource 直接转换为BitmapImage 同时保存透明度

【问题讨论】:

    标签: c# wpf bitmap bitmapimage bitmapsource


    【解决方案1】:

    您需要将BitmapSource 编码为BitmapImage,您可以在此示例中选择您想要的任何编码器,我使用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;
    }
    

    【讨论】:

    • 它有效,但只有当我从 memoryStream 中删除“使用”时它才有效,知道为什么吗?
    • 哦,我的错,这是因为使用处理流,我没有测试该代码:(,我会更新
    【解决方案2】:

    您尝试了吗:System.Drawing.Imaging.PixelFormat.Format32bppArgb没有 Format32-P-Argb 之间的 P)

    MSDN:

    Format32bppArgb -> 指定格式为每像素 32 位; Alpha、红色、绿色和蓝色分量各使用 8 位。

    Format32bppPArgb -> 指定格式为每像素 32 位;每个 8 位用于 alpha、红色、绿色和蓝色分量。 根据 alpha 分量对红色、绿色和蓝色分量进行预乘

    【讨论】:

    • 工作方式相同,但它与我的问题有什么关系?我的函数确实给了我透明的缩略图,但我分两步完成(正如我所说),我很确定我可以一步完成
    猜你喜欢
    • 2011-01-10
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2013-05-17
    相关资源
    最近更新 更多