covert from base64 to image using c# in windows 8.1 - c#

Any executable funtion to convert from base64 to an image using c# windows 8.1************* .
I tried :
public Image byteArrayToImage(byte[] byteArrayIn)
{
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
returnImage = Image.FromStream(ms);
}
return returnImage;
}
FromStream not suitable for windows 8.1

First of all, the Windows.UI.Xaml.Controls.Image class is a control object, not an actual bitmap-type object. What you actually want is a BitmapImage. Of course, given this misunderstanding, you're likely to run into other problems with your code; you don't show the caller of this method, but if you've confused the type here, you've probably confused it elsewhere. So that will have to be fixed.
Secondly, as is the case with many things in WinRT, doing what you want is somewhat more complicated than if you were using the desktop API. :(
That said, something like this should work:
public Windows.UI.Xaml.Media.Imaging.BitmapImage byteArrayToImage(byte[] byteArrayIn)
{
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(byteArrayIn.AsBuffer(0, byteArrayIn.Length));
stream.Seek(0);
BitmapImage image = new BitmapImage();
await image.SetSourceAsync(stream);
return image;
}
}
Then you can set that object to the Source property of an Image control object.
Some notes:
In your original example, disposing the source stream is at the very least unconventional. My recollection is that in at least some cases, doing so isn't legal, as the Bitmap object returned requires the Stream instance to remain undisposed. For WinRT, AFAIK disposing the stream after the bitmap has been initialized is fine.
The AsBuffer() method is an extension method. You'll need to include a using System.Runtime.InteropServices.WindowsRuntime; in your code if it's not already there for it to work.
See also:
BitmapSource class
InMemoryRandomAccessStream class
WindowsRuntimeBufferExtensions Class

Related

Conversion from byte[] to image using image.FromStream method

I try converting image data from the database which is already in byte[] back to the image and I'm getting "invalid parameter error" using Image.FileStream.
Please, can anyone help me out with this?
I've tried working around the code using various methods and the last one is below in my code.
byte[] data = validaccount.FingerPrint;
try
{
using (MemoryStream strm = new MemoryStream())
{
strm.Write(data, 0, data.Length);
strm.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
The code is supposed to convert the byte[] into an image.
According to the docs, Image.FromStream(stream) will throw an argument exception if "The stream does not have a valid image format". Have you verified the data is actually correct? If so, what type of image is it?
You're misusing your streams. You only need 1 memory stream and it has a constructor that takes a byte array (no need to write the bytes yourself). Be sure to wrap it in a using block (like you did for your first stream).
You may not want to use BitmapImage - that's for xaml/wpf apps. You probably want System.Drawing.Bitmap which inherits/extends System.Drawing.Image. Additionally, Bitmap has a constructor which takes a stream - no need to use FromStream.
Finally, Image (and hence Bitmap since Bitmap inherits Image) implements IDisposable, so you should also wrap it in a using block.
P.S. This is a duplicate question.
Though its not memory stream, this method has worked for me and if you browse SO for your question, some times MS does not work.
using System.Drawing;
var converterdImage = (Bitmap)((new ImageConverter()).ConvertFrom(byteArray));
Byte Array to Image Conversion

How to convert UWP SoftwareBitmap to WPF Bitmap?

I'm trying to get a SoftwareBitmap to be usable by stuff in WPF as a Bitmap.
Approaches like this question shows look promising, but they seem to be using objects from different namespaces that don't quite work in my case. For context, I'm using MediaCapture from UWP land for webcam streaming in my app which is WPF.
public static WriteableBitmap WriteableBitmapFromSoftwareBitmap(SoftwareBitmap soft)
{
WriteableBitmap writeable = new
WriteableBitmap(soft.PixelWidth, soft.PixelHeight);
soft.CopyToBuffer(writeable.PixelBuffer);
return writeable;
}
public static Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)
{
Bitmap bmp;
using (MemoryStream outStream = new MemoryStream())
{
System.Windows.Media.Imaging.BitmapEncoder enc = new
BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(writeBmp)); // Error here
enc.Save(outStream);
bmp = new Bitmap(outStream);
}
return bmp;
}
Unfortunately, in BitmapFromWriteableBitmap, the call to BitmapFrame.Create is complaining that it can't create a URI from that kind of WriteableBitmap.
Note that the WriteableBitmap is a Windows.UI.Xaml.Media.Imaging.WriteableBitmap,
the SoftwareBitmap is a Windows.Graphics.Imaging.SoftwareBitmap,
and the desired Bitmap is a System.Drawing.Bitmap.
There is no direct conversion. You'll need to extract the image data from the SoftwareBitmap and then create the new Bitmap from that data.
This is essentially what the linked question does: it encodes the data from the WriteableBitmap into a .BMP stream and then loads the System.Drawing.Bitmap from that stream.
You can do the same from the SoftwareBitmap by using Windows.Graphics.Imaging.BitmapEncoder.SetSoftwareBitmap to convert its contents to an image stream and then create a new System.Drawing.Bitmap from that stream.
See Save a SoftwareBitmap to a file with BitmapEncoder for sample code. You can render to an InMemoryRandomAccessStream instead of a StorageFile's stream to avoid saving to disk, and can use AsStream to convert it to a .Net System.IO.Stream to read into the System.Drawing.Bitmap something like the following (untested) snippet:
using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetSoftwareBitmap(softwareBitmap);
await encoder.FlushAsync();
bmp = new System.Drawing.Bitmap(stream.AsStream());
}

Load Image from Stream

Is there any way of converting Stream to Image?
I tried Bitmap, but it states that I don't have System.Drawing... so I tried this:
var bitMap = new BitmapImage();
bitMap.SetSourceAsync(stream);
image.Source = bitMap;
EDIT:
I am trying to build UWP app + using VS 2015.
2 - It just states that System.Drawing does not exist in the namespace.
EDIT2:
Ok, I might have explained it wrong. The idea is: I have an Image, and I want to change its source to something different and then for it to reload, so I can see the image.
The image is effectively a "Stream", so I assume I need to convert it to Bitmap and then load somehow.
EDIT3:
Ok, so I think it will be easier to describe and then use the code above:
There is a picture box and I am using:
var stream = new InMemoryRandomAccessStream();
await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
Now I would like this Captured Photo to be displayed as an Image. ( Image "box" is created at the start, so the idea is to change source).
Right, so I managed to fix it:
var bitMap = new BitmapImage();
stream.seek(0); // LINE ADDED
bitMap.SetSourceAsync(stream);
image.Source = bitMap;
I turned out that the error that was being produced was : "The component cannot be found.", so I managed to fix it by using this trick.
I am not sure if this is what you are looking for but if you would like to use stream with BitMapImage you should use:
var image = new BitmapImage();
await image.SetSourceAsync(stream);
For instance when you have your photo stored as a byte[] array you can use the stream to convert it to image:
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0))
writer.WriteBytes(<<here your byte[] array>>);
await writer.StoreAsync();
var image = new BitmapImage();
await image.SetSourceAsync(stream);
}
Is that what you need?

Returning Image using Image.FromStream

I know there are similar posts but I haven't got any answer for my problem and hence posting this.
I have a method that retrieves and returns image from a image path. Below is the code snippet I used. This fails in some cases as the image is lost after returning.
public static Image GetImageFromPicPath(string strUrl)
{
WebResponse wrFileResponse;
wrFileResponse = WebRequest.Create(strUrl).GetResponse();
using (Stream objWebStream = wrFileResponse.GetResponseStream())
{
return Image.FromStream(objWebStream);
}
}
If I use Bitmap class and return the image, metadata is lost.
If I use MemoryStream (as shown below) and I don't dispose MemoryStream it works . But there is possible memory leak here. If I use using block, the image is lost.
MemoryStream ms = new MemoryStream();
objWebStream.CopyTo(ms, 8192);
return System.Drawing.Image.FromStream(ms);
Can someone suggest me best approach to solve this issue.
Thanks in advance!!
This is why it's not working for you (from https://msdn.microsoft.com/en-us/library/93z9ee4x(v=vs.110).aspx) :
Here's a post that covers the issue a bit more: Loading an image from a stream without keeping the stream open
Try this:
public static Image GetImageFromPicPath(string strUrl)
{
using (WebResponse wrFileResponse = WebRequest.Create(strUrl).GetResponse())
using (Stream objWebStream = wrFileResponse.GetResponseStream())
{
MemoryStream ms = new MemoryStream();
objWebStream.CopyTo(ms, 8192);
return System.Drawing.Image.FromStream(ms);
}
}
In your consuming code do something like this:
using (var image = GetImageFromPicPath("http://imgur.com/123456.png"))
{
//use image
}
By wrapping "var image" in a using statement, Dispose() will be called on image which will also Dispose() and release the underlying MemoryStream in use by the Image.
Use the MemoryStream and don't explicitly close it. The Bitmap will close it in its Dispose method. There's no memory leak, as long as you remember to Dispose() the Bitmap when you're done with it. (And even if you didn't, the MemoryStream would eventually get garbage collected provided you let go of the Bitmap at some point and the Bitmap's the only thing holding a reference to it.)
https://support.microsoft.com/en-us/kb/814675

Load a byte[] into an Image at Runtime

I have a byte[] that is represented by an Image. I am downloading this Image via a WebClient. When the WebClient has downloaded the picture and I reference it using its URL, I get a byte[]. My question is, how do I load a byte[] into an Image element in WPF? Thank you.
Note: This is complementary to the question I asked here: Generate Image at Runtime. I cannot seem to get that approach to work, so I am trying a different approach.
Create a BitmapImage from the MemoryStream as below:
MemoryStream byteStream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = byteStream;
image.EndInit();
And in XAML you can create an Image control and set the above image as the Source property.
You can use a BitmapImage, and sets its StreamSource to a stream containing the binary data. If you want to make a stream from a byte[], use a MemoryStream:
MemoryStream stream = new MemoryStream(bytes);
In .Net framework 4.0
using System.Drawing;
using System.Web;
private Image GetImageFile(HttpPostedFileBase postedFile)
{
if (postedFile == null) return null;
return Image.FromStream(postedFile.InputStream);
}
One way that I figured out how to do it so that it was both fast and thread safe was the following:
var imgBytes = value as byte[];
if (imgBytes == null)
return null;
using (var stream = new MemoryStream(imgBytes))
return BitmapFrame.Create(stream,BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
I threw that into a converter for my WPF application after running the images as Varbinary from the DB.

Categories

Resources