I need to parse the content of Clipboard.GetImage()
(a BitmapSource
) to a BitmapImage
.
Does anyone knows how can this be done?
Asked
Active
Viewed 4.7k times
21

Jaime Oro
- 9,899
- 8
- 31
- 39
2 Answers
38
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;
-
5Is it necessary to use `bImg.StreamSource = new MemoryStream(memoryStream.ToArray());` instead of `bImg.StreamSource = memoryStream;` and removing `memoryStream.Close(); ` – Elmo Jan 07 '12 at 15:28
-
2You should add bImg.Freeze() at the end to allow multithreaded calls, otherwise works perfect. – m1k4 Aug 08 '13 at 13:00
-
2@Don'tForgettoUpvote: For me `bImg.StreamSource = new MemoryStream(memoryStream.ToArray());` was necessary, else it was throwing exception. – dotNET Jan 11 '14 at 16:22
-
2What if a PNG image is in the clipboard? Should you use the PngBitmapEncoder then? – Fabian Bigler Dec 16 '14 at 12:15
-
1@Elmo The changes were indeed required, without them, it was throwing exception for me too – Amir Mahdi Nassiri Nov 09 '17 at 15:31
-
1Is this even lossless? – EFraim Aug 30 '20 at 04:41
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();