Silverlight 4 : Converting image into byte[] - c#

I have found how to do this in .NET 4.0, but I think JpegBitmapEncoder doesn't exist in Silverlight:
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
var bytes = memStream.GetBuffer();
How can I convert an image to bytes[] in silverlight?
UPDATE:
I have a Contact model, which has a Photo property. Whenever I add a new Contact, I would like to load a local default Image and convert it and set the Photo property to it.
var bitmapImage = new BitmapImage
{
UriSource = new Uri("pack://application:,,,/xxx;component/Images/default.JPG")
};
var image = new Image{Source = bitmapImage};
Is this the correct way to load an image in first place?

Use
myImage.Save(memStream, ImageFormat.Jpeg);
return memStream.ToArray();
UPDATE
OK it turns out that the image is a BitmapImage.
It seems that BitmapImage does not expose the functionality to save the image. The solution is to get the image from the embedded resource:
Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, buffer.Length);

Have a look at this library: Imagetools
It contains some nice utilities and jpg and png encoders,

Related

How to display Bitmap object in WinUI 3 application

I want to display QR code generated by QRCoder library ( https://github.com/codebude/QRCoder/ ) in my WinUI 3 desktop app.
From QRCoder I get System.Drawing.Bitmap object:
QRCodeGenerator qrCodeGenerator = new();
QRCodeData qrCodeData = qrCodeGenerator.CreateQrCode(associateSoftwareTokenResponse.SecretCode, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new(qrCodeData);
Bitmap qrCodeBitmap = qrCode.GetGraphic(20);
Then assigning it to XAML Image control: qrCodeImage.Source = qrCodeBitmap gives an error:
Error CS0029 Cannot implicitly convert type 'System.Drawing.Bitmap' to
'Microsoft.UI.Xaml.Media.ImageSource'
So apparently there is still some conversion needed.
All documentation and examples I managed to find explain how to print an image from file but not Bitmap object.
How can I display this code generated Bitmap in my WinUI 3 app?
You should be able to create a BitmapImage from a stream something like this:
Bitmap qrCodeBitmap = ...;
BitmapImage bitmapImage = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
qrCodeBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
bitmapImage.SetSource(stream.AsRandomAccessStream());
}
image.Source = bitmapImage;

How to convert BitmapImage to StdPicture

I have a BitmapImage object loaded with an icon, I need to convert that to StdPicture. How do I do that ?
I found tons of examples on how to convert System.Drawing.Image to StdPicture but nothing for System.Windows.Media.Imaging.BitmapImage to StdPicture.
Do I have to first convert it to Winforms Image and then to StdPicture ? Sounds a bit silly to me.
I am assuming stdPicture you mean Bitmap.. So here we go.
private Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
using (MemoryStream os = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(os);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(os);
return new Bitmap(bitmap);
}
}

How to convert type 'system.windows.media.imagesource' to 'system.drawing.image' or byte[] in C#?

I am doing a project in which a built in class for DICOM giving me the ImageSource,I want to use that ImageSource in My silverlight Image control. This conversion I am doing through WCF services. I found WCF does not support ImageSource, so I need to convert the output of built in class into Image or else in byte[]. So that I can send that output to Silverlight and in Silverlight client I'll reconvert it to ImageSource and can assign it to Image Control easily.
I googled for this but I did not find any help in there. Can anybody help me to fix this problem or provide me any alternate solution for this. Any help will be appreciated, Thanks in advance.
Note:- I do not have any permission for code modification on the built in class. As its a third party library.
UPDATE:-
Brief Description:
I have a class let say GetImageSource and in that I have a method say giveImgSource(). Now my questions is:
In WCF I have to call this method and after getting ImageSource from this method I need to pass it to my silverlight Client. As WCF doesn't know about ImageSource, so I need to convert the output of this method to some one out of the following or any alternate if you knows:
byte[]
Image
FileStream
MemoryStream etc
Is it a png image? Then use this to convert to byte[]:
var image = (BitmapSource)value;
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (var ms = new MemoryStream())
{
encoder.Save(ms);
return ms.ToArray();
}
UPDATE:
Decoding:
var bytes = (byte[])value;
var image = new BitmapImage();
image.BeginInit();
if (bytes == null)
{
// Processing null case
}
else
{
using (var ms = new MemoryStream(bytes))
{
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
}
}
return image;
Please refer to the below links for converting ImageSource to byte[]. They use the BitmapSource and WriteableBitmap classes which are available under PresentationCore library.
(1) How to Convert ImageSource to byte[]?
(2) How to Convert ImageSource to byte[] and back to ImageSource?
Hope that it will solve your problem.
The following two helper methods should be able to do the trick:
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
return image;
}
public Byte[] BufferFromImage(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}

Silverlight 4: How can I convert bmp byte array to png byte array?

I have a wcf service which returns a bmp in byte[]. However Silverlight's Image control doesnt support displaying bmp's so i need to convert the bmp byte[] to png or jpg byte[]. Is there a library out there which does this conversion? Or any other way of displaying the bmp byte[] on the silverlight client?
Thanks!
Update1
In order to achieve the conversion I would have done something like this in .NET
private byte[] ConvertBmpToJpeg(byte[] bmp)
{
using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(bmp)))
{
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
return ms.ToArray();
}
}
Since System.Drawing is not available in Silverlight, how do I achieve what the code does above in Silverlight?
Answer
using the library mentioned by dj kraze below-
ExtendedImage img = new ExtendedImage();
var bd = new BmpDecoder();
var je = new JpegEncoder();
bd.Decode(img, new MemoryStream(bitmapBytes));
MemoryStream ms = new MemoryStream();
je.Encode(img, ms);
BitmapImage bi = new BitmapImage();
bi.SetSource(new MemoryStream(ms.ToArray()));
display_ScreenShot.Source = bi;
Here is an even easier way of doing it..
This site may help out a lot
Image Converting

“Unspecified error” when converting a byte array into a BitmapImage

My goal is to upload and download images using a web service. I understand that in order to do that the images need to be converted to a byte array. However, I’m getting “Unspecified error” when converting a byte array into a BitmapImage.
I’ve create a test rig that converts an image (from a PhotoChooserTask) into a byte array and back again that recreates my problem. The code that does the conversion is listed below with the problem line highlighted.
Any help would be appreciated!
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto);
Photo.Source = PhotoBitmap;
//Convert the photo to bytes
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
//Convert the bytes back to a bitmap
BitmapImage RestoredBitmap = new BitmapImage();
MemoryStream stream = new MemoryStream(PhotoBytes);
BitmapImage image = new BitmapImage();
RestoredBitmap.SetSource(stream); //<------ I get "Unspecified error" on this line
//Display the restored photo
RestoredPhoto.Source = RestoredBitmap;
}
}
The first time you use e.ChosePhoto as source, the stream is read and the Position property is advanced to the end. You can inspect the PhotoBytes array in the debugger to see that after your read operation it actually does not have any content (or check the return value of the Read method to confirm zero bytes are read).
What you need to do is reset that Position to zero before you read from it again:
//Convert the photo to bytes
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
// rewind first
e.ChosenPhoto.Position = 0;
// now succeeds
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
I would bet that this is what's happening (comments inline):
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto); // This is reading from the stream
Photo.Source = PhotoBitmap;
//Convert the photo to bytes
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length); // Fails to read the full stream
// because you already read from it
//Convert the bytes back to a bitmap
BitmapImage RestoredBitmap = new BitmapImage();
MemoryStream stream = new MemoryStream(PhotoBytes); // You're creating a stream that
// doesn't contain the image
BitmapImage image = new BitmapImage();
RestoredBitmap.SetSource(stream); // Fails because your stream is incomplete
Seek to 0 in the stream before you attempt to read from it. And check the return value from the Read call to make sure it matches PhotoBytes.Length.
This:
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto);
Photo.Source = PhotoBitmap;
uses the Stream of the e.ChosenPhoto and might not rewind the Position of the Stream.
So when you do this:
Byte[] PhotoBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(PhotoBytes, 0, PhotoBytes.Length);
you are starting at the end of the stream reading nothing.
Use Seek to reset the Position of the stream.
Did you check out my other post where I already did this?
I had receive a pretty good rating from it.
BitmapImage to byte[] and byte[] to BitmapImage

Categories