Converting Windows.UI.Xaml.Controls.Image to byte[] Windows phone8.1 - c#

So to make it simple, I have a Windows.UI.Xaml.Controls.Image in my C# class that is named MyImage. I would like to convert it to byte[] so that I can store it to my database.I have no idea how to do this since the image is Windows.UI.Xaml.Controls.Image and not System.Drawing.Image so I can't do something like this:
...
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
I would appreciate if someone could write down a simple "how to" code to do this because I just can't figure it out.

I believe that you are using a bitmap image then
myImage = new BitmapImage(new Uri("YourImagePath", UriKind.Absolute));
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myImage);
wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
byte[] imageBytes = ms.ToArray();
This works for Windows Phone But if you are writing code for Windows Store App would suggest you to modify it.
myImage = new BitmapImage(new Uri("YourImagePath"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);

Related

Convert ImageBrush to byte[]

The Goal:
I want to convert an ImageBrush to a byte[].
Why?:
Because I want to print out the image, but I can't create any UI elements besides something like a MessageBox. SO I found an online tool that takes in a byte array and produces an image.
How do I do this in C# (WPF)?
What I've tried so far:
I have already converted the ImageBrush to a BitmapSource as so:
BitmapSource src = (BitmapSource)imageBrush.ImageSource;
and have converted the BitmapSource to a Bitmap Image as so:
private BitmapImage BitmapSourceToBitmapImage(BitmapSource bmpSrc)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bmpSrc));
encoder.Save(memoryStream);
memoryStream.Position = 0;
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
memoryStream.Close();
return bImg;
}
But for the life of me I cannot get this BitmapImage to a byte array! I have tried this:
private byte[] BitmapImagetoByteArray(BitmapImage bitmapImage) {
byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
using(MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
data = ms.ToArray();
}
return data;
}
The Problem/Error:
But when the encoder tries to save the memory stream, it says a frame has been disposed... see error message below:
Void SaveFrame(System.Windows.Media.SafeMILHandle, System.Windows.Media.SafeMILHandle, System.Windows.Media.Imaging.BitmapFrame)
Cannot access a disposed object.
System.ObjectDisposedException: Cannot access a disposed object.
at System.Windows.Media.Imaging.BitmapEncoder.SaveFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions, BitmapFrame frame)
at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)
Any help? How can I display the ImageBrush without creating UI elements!
The error was not to set BitmapCacheOption.OnLoad, which is necessary when the source stream is to be closed right after EndInit:
bImg.BeginInit();
bImg.CacheOption = BitmapCacheOption.OnLoad;
bImg.StreamSource = memoryStream;
bImg.EndInit();
memoryStream.Close();
However, creating the intermediate BitmapImage wasn't necessary at all. The code should simply look like this:
private byte[] BitmapSourceToByteArray(BitmapSource bmpSrc)
{
var encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
encoder.Frames.Add(BitmapFrame.Create(bmpSrc));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}

UWP - load WritableBitmap from byte array returns weird image

I have an InkCanvas drawing, which i convert to WriteableBitmap and set is as an ImageSource as follows:
MemoryStream ms = new MemoryStream();
await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(ms.AsOutputStream());
ms.Position = 0;
WriteableBitmap wb = new WriteableBitmap((int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight);
wb.SetSource(ms.AsRandomAccessStream());
image.Source = wb;
That works fine.
Now i need to store the WriteableBitmap as a byte array in database in order to use it as image source of a GridView item. This is the method i use to convert the bitmap to byte[]:
using (Stream stream = ((WriteableBitmap)image.Source).PixelBuffer.AsStream())
{
data = new byte[(uint)stream.Length];
await stream.ReadAsync(data, 0, data.Length);
}
and this one to restore the bitmap form byte[]:
WriteableBitmap wb = new WriteableBitmap(200,200);
using (Stream stream = wb.PixelBuffer.AsStream())
{
await stream.WriteAsync(data, 0, data.Length);
}
Now here are the screenshots describes how the image looks after retrieving from InkCanvas and after retrieving from byte[]:
Will be grateful if someone faced that issue and has a solution.

how to convert an image into base64 in xamarin.android?

I have this code, it works very well in android studio but not in xamarin
bitmap.Compress() has different arguments in xamarin and i am confused how to convert image into base64 or binary in xamarin.android?
I am receving an error in the 3rd line:
( bitmap.Compress() has some invalid arguments).
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100,bao);
byte[] ba = bao.ToByteArray();
string bal = Base64.EncodeToString(ba, Base64.Default);
If you look at the documentation for Bitmap.Compress in Xamarin, you'll see that the last parameter is a Stream.
The equivalent of ByteArrayOutputStream in .NET is MemoryStream, so your code would be:
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] ba = stream.ToArray();
string bal = Base64.EncodeToString(ba, Base64Flags.Default);
(You could use Convert.ToBase64String instead of Base64.EncodeToString if you wanted, too.)
This is how I'm getting a Byte[] for my Bitmap object:
Byte[] imageArray = null;
Bitmap selectedProfilePic = this.GetProfilePicBitmap ();
if (selectedProfilePic != null) {
using (var ms = new System.IO.MemoryStream ()) {
selectedProfilePic.Compress (Bitmap.CompressFormat.Png, 0, ms);
imageArray = ms.ToArray ();
}
}
Hope this helps.

How to convert Bitmap image to byte array in wp7?

using (MemoryStream ms = new MemoryStream())
{
image.CreateOptions = BitmapCreateOptions.None;
image.UriSource = new Uri("/Images/chef.png", UriKind.Relative);
WriteableBitmap LoadedPhoto = new WriteableBitmap(image);
LoadedPhoto.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight,0,95);
ms.Seek(0, 0);
byte[] data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
ms.Close();
}
I am getting NullReferenceException at image, but my path is also correct and image also exists.
WriteableBitmap LoadedPhoto = new WriteableBitmap(image);
Is anything goes wrong.
Please Refer the solution.
which shows the solution to converting the bitmapimages to byte array.
I hope you will understand..
conversion of bitmapimage to byte array
Refer this link..

Convert resource to byte[]

I am having trouble converting an image resource into byte[].
For example, I have the following resource:
pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg
in my program. How do I convert this into a byte[].
I've tried using a BitMapImage, but it's ImageSource ends up being null after initialised.
This seems to work:
var info = Application.GetResourceStream(uri);
var memoryStream = new MemoryStream();
info.Stream.CopyTo(memoryStream);
return memoryStream.ToArray();
A general solution to convert a BitmapSource into a byte[] would look like this:
public byte[] GetImageBuffer(BitmapSource bitmap, BitmapEncoder encoder)
{
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}
You would use it like shown below, with any of the BitmapEncoders that are available in WPF.
var uri = new Uri("pack://application:,,,/AppName;component/Assets/Images/sampleimage.jpg");
var bitmap = new BitmapImage(uri);
var buffer = GetImageBuffer(bitmap, new JpegBitmapEncoder());

Categories