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();
Author by
Jaime Oro
Industrial Engineer learning C# and using stackoverflow for that purpose.
Updated on July 09, 2022Comments
-
Jaime Oro almost 2 years
I need to parse the content of
Clipboard.GetImage()
(aBitmapSource
) to aBitmapImage
. Does anyone knows how can this be done? -
Elmo over 12 yearsIs it necessary to use
bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
instead ofbImg.StreamSource = memoryStream;
and removingmemoryStream.Close();
-
m1k4 almost 11 yearsYou should add bImg.Freeze() at the end to allow multithreaded calls, otherwise works perfect.
-
dotNET over 10 years@Don'tForgettoUpvote: For me
bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
was necessary, else it was throwing exception. -
Fabian Bigler over 9 yearsWhat if a PNG image is in the clipboard? Should you use the PngBitmapEncoder then?
-
Amir Mahdi Nassiri over 6 years@Elmo The changes were indeed required, without them, it was throwing exception for me too
-
EFraim over 3 yearsIs this even lossless?