Metro APP - BitmapImage to Byte[] or Download Image from Web and convert it to a Byte[] Array - c#

Is there a way to convert a BitmapImage (Windows.UI.Xaml.Media.BitmapImage) to an Byte[] Array? Nothing I've tried work....
Another possible scenario (if BitmapImage cannot be converted to Byte array) is to download the image from web and then convert it to an array...
But I don't know how I can do that...
It would be really nice, if someone have an idea.
Current try:
HttpClient http = new HttpClient();
Stream resp = await http.GetStreamAsync("http://localhost/img/test.jpg");
var ras = new InMemoryRandomAccessStream();
await resp.CopyToAsync(ras.AsStreamForWrite());
BitmapImage bi = new BitmapImage();
bi.SetSource(ras);
byte[] pixeBuffer = null;
using (MemoryStream ms = new MemoryStream())
{
int i = bi.PixelHeight;
int i2 = bi.PixelWidth;
WriteableBitmap wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);
Stream s1 = wb.PixelBuffer.AsStream();
s1.CopyTo(ms);
pixeBuffer = ms.ToArray();
}
But it doesn't work... i & i2 are always set to 0. So ras doesn't work correctly.... What's going on?
Thanks

In your code you're never waiting for the BitmapImage to load the image from the web, so it does not know its PixelWidth/PixelHeight when you access them. You could wait for it to load - for example using the AsyncUI library by calling "await bi.WaitForLoadedAsync()". This would not really help you here if you want to access the decoded pixels since BitmapImage does not give you access to the pixels and there is currently no API to convert a BitmapImage into a WriteableBitmap.
You can check an earlier question about the topic. You would need to get the image file from the web with something like HttpClient.GetAsync(), then load it using something like BitmapDecoder.

Related

c# Load Image from ftp server directly into picture box without downloading

I have looked every where for my answer but couldn't find the right solution.Tried many solutions provided but still can't get it through.I uploaded an image in ftp server and i want it to get displayed into picture box in windows form without downloading it into local machine. Is it possible?
Please include complete code for the solution......
Here is a complete code: If any body needs.Make sure the image isn't large!!
public byte [] GetImgByte (string ftpFilePath)
{
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential(ftpUsername,ftpPassword);
byte[] imageByte = ftpClient.DownloadData(ftpFilePath);
return imageByte;
}
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
You can use DownloadData to get a byte array and load that into the picturebox - see Download file directly to memory and How to put image in a picture box from a byte[] in C#

Resize Image with PHP for using in .NET

i have images on a webserver and I convert they in Base64 to receive it on a .Net application. I use this code:
$imagedata = file_get_contents($local_uri);
$d = base64_encode($imagedata);
It works perfekt.
Now i had the idea to resize the images to save time for transmission.
So I resize the images with a simple PHP-Framework from http://deruwe.de/vorschaubilder-einfach-mit-php-realisieren-teil-2.html
On behind it use ImageJPEG to "return" or create the edited image.
On an other post here i read that if you want to use ImageJPEG and translate it on Base64 you have to use this code:
ob_start();
$thumbnail->output(false, false);
$p = ob_get_contents();
ob_end_clean();
$d = base64_encode($p);
The "new" Base64 code seems legit, because if I try to illustrate it with http://www.freeformatter.com/base64-encoder.html, I got a legit image.
BUT due an unknown reason my .Net application will throw an System.NotSupportedException (No imaging component suitable to complete this operation was found.) and don't like the "new" one.
This is my .Net function to convert Base64 String in BitmapImage:
public static BitmapImage getImage(String s)
{
byte[] binaryData = Convert.FromBase64String(s);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(binaryData);
bi.EndInit();
return bi;
}
Any idea whats gone wrong or how to fix it?

UnauthorizedAccessException using AsRandomAccessStream

I just upgraded my project from Win 8 to Win 8.1 and I'm trying to take advantage of some of the new features in the SDK. One of those is the new AsRandomAccessStream extension method. The problem I'm having is when I use it, I'm getting an Unauthorized Access Exception.
Exception:Caught: "MemoryStream's internal buffer cannot be accessed."
(System.UnauthorizedAccessException) A
System.UnauthorizedAccessException was caught: "MemoryStream's
internal buffer cannot be accessed." Time: 3/11/2014 10:23:11 AM
Thread:[4308]
BitmapImage image = new BitmapImage();
var imageStream = new MemoryStream(imageBytes as byte[]);
image.SetSource(imageStream.AsRandomAccessStream());
imageBytes is a valid byte[]
imageStream is a valid MemoryStream
imageStream.Position = 0
any thoughts?
I encountered this problem today and to me, it appears as an API bug/inconsistency.
In .NET 4, calls to MemoryStream.GetBuffer() require the usage of certain constructors (see https://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx). More specifically, the buffer of the MemoryStream must be marked as exposable.
Now, AsRandomAccessStream() calls MemoryStream.GetBuffer(). However, in Win8.1, the constructor for setting the expose-ability of a MemoryStream is missing. Therefore, when you create the MemoryStream, use the default empty constructor and then call Write().
Thus, I think this should work.
BitmapImage image = new BitmapImage();
var imageStream = new MemoryStream();
imageStream.Write(yourdata, 0, yourdata.Length);
image.SetSource(imageStream.AsRandomAccessStream());
A simple workaround is to combine some extension methods.
var image = new BitmapImage();
var imageSource = imageBytes.AsBuffer().AsStream().AsRandomAccessStream();
image.SetSource(imageSource);

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

Categories