BitmapSource to BitmapImage

43,794

Solution 1

I've found a clean solution that works:

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;

Solution 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();
Share:
43,794
Jaime Oro
Author by

Jaime Oro

Industrial Engineer learning C# and using stackoverflow for that purpose.

Updated on July 09, 2022

Comments

  • Jaime Oro
    Jaime Oro almost 2 years

    I need to parse the content of Clipboard.GetImage() (a BitmapSource) to a BitmapImage. Does anyone knows how can this be done?

  • Elmo
    Elmo over 12 years
    Is it necessary to use bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); instead of bImg.StreamSource = memoryStream; and removing memoryStream.Close();
  • m1k4
    m1k4 almost 11 years
    You should add bImg.Freeze() at the end to allow multithreaded calls, otherwise works perfect.
  • dotNET
    dotNET over 10 years
    @Don'tForgettoUpvote: For me bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); was necessary, else it was throwing exception.
  • Fabian Bigler
    Fabian Bigler over 9 years
    What if a PNG image is in the clipboard? Should you use the PngBitmapEncoder then?
  • Amir Mahdi Nassiri
    Amir Mahdi Nassiri over 6 years
    @Elmo The changes were indeed required, without them, it was throwing exception for me too
  • EFraim
    EFraim over 3 years
    Is this even lossless?