BitmapSource to BitmapImage
Asked Answered
R

2

21

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

Russianize answered 17/3, 2011 at 11:16 Comment(0)
R
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;
Russianize answered 17/3, 2011 at 11:42 Comment(6)
Is it necessary to use bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); instead of bImg.StreamSource = memoryStream; and removing memoryStream.Close(); Pusey
You should add bImg.Freeze() at the end to allow multithreaded calls, otherwise works perfect.Flip
@Don'tForgettoUpvote: For me bImg.StreamSource = new MemoryStream(memoryStream.ToArray()); was necessary, else it was throwing exception.Zeigler
What if a PNG image is in the clipboard? Should you use the PngBitmapEncoder then?Vanish
@Pusey The changes were indeed required, without them, it was throwing exception for me tooWhereas
Is this even lossless?Pietrek
D
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();
Doubleripper answered 25/8, 2011 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.