相关文章推荐
魁梧的排球  ·  python typeerror ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm tying together two libraries. One only gives output of type System.Windows.Media.Imaging.BitmapSource , the other only accepts input of type System.Drawing.Image .

How can this conversion be performed?

private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)
  System.Drawing.Bitmap bitmap;
  using (MemoryStream outStream = new MemoryStream())
    BitmapEncoder enc = new BmpBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create(bitmapsource));
    enc.Save(outStream);
    bitmap = new System.Drawing.Bitmap(outStream);
  return bitmap;

This is an alternate technique that does the same thing. The accepted answer works, but I ran into problems with images that had alpha channels (even after switching to PngBitmapEncoder). This technique may also be faster since it just does a raw copy of pixels after converting to compatible pixel format.

public Bitmap BitmapFromSource(System.Windows.Media.Imaging.BitmapSource bitmapsource)
        //convert image format
        var src = new System.Windows.Media.Imaging.FormatConvertedBitmap();
        src.BeginInit();
        src.Source = bitmapsource;
        src.DestinationFormat = System.Windows.Media.PixelFormats.Bgra32;
        src.EndInit();
        //copy to bitmap
        Bitmap bitmap = new Bitmap(src.PixelWidth, src.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        src.CopyPixels(System.Windows.Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
        bitmap.UnlockBits(data);
        return bitmap;
                @aholmes why people should worry about the bitmap object to be disposed? it is the responsibility of the caller, not the implementer
– Earth Engine
                Apr 20, 2016 at 5:12
                I forgot why I wrote that comment. I think I intended to write using(Bitmap bitmap = BitmapFromSource(...)) {...}
– aholmes
                Apr 20, 2016 at 20:04
                very good! can you say when it is required to convert the image format (first part of code)?
– S.Serpooshan
                Dec 2, 2017 at 12:03
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.