【问题标题】:BitmapSource to BitmapImageBitmapSource 到 BitmapImage
【发布时间】:2011-03-17 11:16:38
【问题描述】:

我需要将Clipboard.GetImage()BitmapSource)的内容解析为BitmapImage。 有谁知道如何做到这一点?

【问题讨论】:

    标签: c# .net wpf bitmapimage bitmapsource


    【解决方案1】:

    我找到了一个有效的干净解决方案:

    BitmapSource bitmapSource = Clipboard.GetImage();
    
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    MemoryStream memoryStream = new MemoryStream();
    BitmapImage bImg = new BitmapImage();
    
    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
    encoder.Save(memoryStream);
    
    memoryStream.Position = 0;
    bImg.BeginInit();
    bImg.StreamSource = memoryStream;
    bImg.EndInit();
    
    memoryStream.Close();
    
    return bImg;
    

    【讨论】:

    • 是否需要使用bImg.StreamSource = new MemoryStream(memoryStream.ToArray());而不是bImg.StreamSource = memoryStream;并去掉memoryStream.Close();
    • 您应该在末尾添加 bImg.Freeze() 以允许多线程调用,否则可以完美运行。
    • @Don'tForgettoUpvote:对我来说bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); 是必要的,否则它会抛出异常。
    • 如果剪贴板中有PNG图像怎么办?那你应该使用 PngBitmapEncoder 吗?
    • @Elmo 确实需要更改,没有它们,我也会抛出异常
    【解决方案2】:
    using System.IO; // namespace for  using MemoryStream
    
    private static byte[] ReadImageMemory()
    {
        BitmapSource bitmapSource = BitmapConversion.ToBitmapSource(Clipboard.GetImage());
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        MemoryStream memoryStream = new MemoryStream();
        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
        encoder.Save(memoryStream);
        return memoryStream.GetBuffer();
    }
    
    // and calling by this example........
    byte[] buffer = ReadImageMemory();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      相关资源
      最近更新 更多