Binding Image in ASP.NET MVC4 from a byte array - asp.net

I am binding an image from a byte array in MVC4 view , The byte array is returned from a WEB API which I need to bind it to a view .
Below is the code
string str="JVBERi0xLjUNJeLjz9MNCjQgMCBvYmoNPDwvRSA0NDc1L0ggWyA3NjMgMTI1IF0vTCA1MTczL0xpbmVhcml6ZWQgMS9OIDEvTyA2L1QgNDcwMj4+DWVuZG9iag0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIA0xNCAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbNCAxMV0vSW5mbyAzIDAgUi9MZW5ndGggNTQvUHJldiA0NzAzL1Jvb3QgNSAwIFIvU2l6ZSAxNS9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiZBBgYGJg2gAkGHeAiLlAgiEHSPAUMTAxfhADcRkYmf4zffrPxCCQAuS+C2cAALmiCM4KZW5kc3RyZWFtDWVuZG9iag1zdGFydHhyZWYNIDANJSVFT0YNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0N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Lm4hRfl5CkDaL7VERyHMTM/YwMjEKCZP084OAIrZKrEKZW5kc3RyZWFtDWVuZG9iag0xMyAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbMCA0XS9JbmZvIDMgMCBSL0xlbmd0aCAyNC9Sb290IDUgMCBSL1NpemUgNC9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiAAImRsFqIPG+jYEJyGMEABJTAg0KZW5kc3RyZWFtDWVuZG9iag10cmFpbGVyDTw8L1NpemUgNA0vSUQgWyhuXDM2NFxmXDIzNlwzMjVcMjYyfVwyNjRcMjcwXDM1MCpcMTc3XDAzN1wzNjdcMDA3XDMxNikgKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KV0+Pg1zdGFydHhyZWYNMTgyDSUlRU9GDQ==";
Byte[] image = GetBytes(str);
{
Model.ImageData = image;
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
in view Bind it as
<img src="data:image;base64,#System.Convert.ToBase64String(Model.ImageData)" />
The image is not rendering , it is showing an image icon only in page .
Where it is going wrong .Please suggest .

Your str looks like it is already base64, so you don't need to dance to binary and back. You can just stick it in the view where it should be.
Decoding that string from base64 revealed that it is not an image, it's a pdf file.
So your api (3d party, I guess) serves you not an image.
And lastly to successfully use an image like that you probably need to specify mime type like this <img src="data:image/png;base64,some text representation of binary data" />
http://en.wikipedia.org/wiki/Data_URI_scheme

Related

Convert Bytes to Image ASP.NET c# and use it in Image1.Url

I have a WEB-APP that is a Web-Cam App that takes images and stores into a database as bytes, Now with that being said I also don't want to save the images those are taken and save it in any kind of folder right now the only way to show the image that is captured for me to save it and view it again to do that I have a input stream that's fired when the capture image is clicked.
using (StreamReader reader = new StreamReader(Request.InputStream))
{
hexString = Server.UrlEncode(reader.ReadLine());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/Pictures/{0}.png", imageName);
File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(hexString));
Session["Byte"] = hexString;
// Session["CapturedImage"] = ResolveUrl(imagePath);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(ConvertHexToBytes(hexString));
}
I have a method that converts that hex string to bytes:
private static byte[] ConvertHexToBytes(string hex)
{
// MemoryStream stream = new MemoryStream();
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
I want to Display that image using the bytes, I don't want to save the image in any folder. How do I take those bytes and put them into a image?
I have a slandered image tag Image1.imageUrl =? I tried the base64 version but it doesn't work.
How do I take those bytes and put them into a image?
Note: I am making the assumption as per your question that your question is not about converting hex to bytes.
Imagine you have this in your aspx page:
<asp:Image ID="Image1" runat="server" />
In the code below GetImageBytes returns a byte[]. Then, to serve the image (without saving it to a file), all we need to do is this:
using (MemoryStream ms = new MemoryStream(GetImageBytes()))
{
// Image1 is instance of System.Web.UI.WebControls
this.Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
private byte[] GetImageBytes()
{
return System.IO.File.ReadAllBytes(Server.MapPath("~/Content/someImage.jpg"));
}
Try that out by placing an image in your Content folder to test it out. Now that you know it works, you need to make sure it can work with your ConvertHexToBytes method. If it does not, then clearly something is wrong with ConvertHexToBytes method.

How to save image from rich text editor

I have a form including rich text editor in it.
While with only content in richtext editor I don't get any problem in saving it in database.
But when I attach an image in it, It always pokes me with this error-
Invalid URI: The Uri string is too long.
Yes the URI is absolutely so long, But why don't this form saves it even if I had given datatype to nvarchar(MAX) to be saved.
See in pictures-
and URI of this image -
While model type has nvarchar(MAX) datatype for this rich text editor.
I am performing simple save function and rendering rich text editor's values by
#Html.Raw() helper.
For this editor's rendering I am doing this on client side-
#Html.Raw(Model.businessDetails)
Model-
public string businessDetails{get;set;}
Why SQL SERVER doesn't save this long uri? What went wrong in my form submission?
first thing first,
you should be doing this as a POST request not as a GET!
after that you have two options
1)
set an attribute so it will allow HTML in the string and it will store the image as base64 in the html and you won't have to worry about storing it anywhere.
[AllowHtml]
public string businessDetails{ get; set; }
2)
grab the src of the image
remove the data:image/png;base64, from it
decode the result with base64 converter , the resulting is binary result
byte[] imageArr ;
//set your imageArr here---
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CreateOptions = BitmapCreateOptions.None;
bi.CacheOption = BitmapCacheOption.Default;
bi.StreamSource = new MemoryStream(imageArr);
bi.EndInit();
Image img = new Image(); //Image control of wpf
img.Source = bi;
save image to destination. img.Save("path",ImageFormat.Jpeg)
replace the src of that image with an actual URL

decode Base64 byte Array to Image in C#

I am making a small application in android that browse image from the gallery or take a picture from the camera. Then the selected image is compressed and uploaded to the server. I had compressed the image using Base64 String in android and for uploading image i am making a web service in ASP.NET. But i'm not sure how to decode the string(converted using Base64 in android) into image(the web service should be able to convert it). Please help me.
Thanks in advance
You can convert base64string to image by Image.FromStream. You will need to convert the base64string to stream first.
byte[] imageBytes = Convert.FromBase64String(imgBase64String);
Image img = null;
using (MemoryStream ms1 = new MemoryStream(imageBytes))
{
img = Image.FromStream(ms1);
}
if (img != null)
{
// ...
}

How do I generate an Image in a ASP.NET ASMX web service and load it via AJAX?

I am currently using a function inside an ASP.Net ASMX web service to generate a System.Drawing.Image. I would like to have this image (after converting to a png or something) passed to the browser as the reply to an AJAX call. (using jQuery's $.ajax). I've been Googling but can't seem to find out how, although I'm pretty sure it's possible. Do I convert it to a Data URI somehow first, or what?
I don't think you can do that. In order to return the image, you should have a method which returns bytearray which I don't think is of any use in javascript.
My workaround is to save the image in a certain location and return the address of the image to clientside.
Update: based on the comments, you can encode the image's data to Base64 string and handle the DATA URI on your ajax callback.
You can use JSON to represent the base64Encoded data, and on the ajax calklback, you can write something like:
$("#myImage").attr("src", "data:image/png;base64,RETURNED_DATA_FROM_ASMX");
Here's a sample code to convert your image to base64 in c#:
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
To find out how to format a DATA URI, you can visit http://en.wikipedia.org/wiki/Data_URI_scheme#Format.

An image from byte to optimized web page presentation

I get the data of the stored image on database as byte[] array;
then I convert it to System.Drawing.Image like the code shown below;
public System.Drawing.Image CreateImage(byte[] bytes)
{
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes);
System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream);
return image;
}
(*) On the other hand I am planning to show a list of images on asp.net pages as the client scrolls downs the page. The more user gets down and down on the page he/she does see the more photos. So it means fast page loads and rich user experience. (you may see what I mean on www.mashable.com, just take care the new loads of the photos as you scroll down.)
Moreover, the returned imgae object from the method above, how can i show it in a loop dynamically using the (*) conditions above.
Regards
bk
Well, I think the main bottleneck is actually hitting the database each time you need an image. (Especially considering many users accessing the site.)
I would go with the following solution:
Database will store images with the original quality;
.ashx handler will cache images on the file system in various needed resolutions (like 32x32 pixels for icons, 48x48 for thumbnails, etc.) returning them on request and accessing database only once; (in this example is shown how to return an image via ashx handler)
The actual pages will point to .ashx page to get an image. (like <img scr="GetImage.ashx?ID=324453&Size=48" />)
UPDATE:
So the actual workflow in the handler will be like:
public void ProcessRequest (HttpContext context)
{
// Create path of cached file based on the context passed
int size = Int32.Parse(context.Request["Size"]);
// For ID Guids are possibly better
// but it can be anything, even parameter you need to pass
// to the web service in order to get those bytes
int id = Int32.Parse(context.Request["Id"]);
string imagePath = String.Format(#"images/cache/{0}/{1}.png", size, id);
// Check whether cache image exists and created less than an hour ago
// (create it if necessary)
if (!File.Exists(imagePath)
|| File.GetLastWriteTime(imagePath) < DateTime.Now.AddHours(-1))
{
// Get the file from the web service here
byte[] imageBytes = ...
// Save as a file
using (var memoryStream = new MemoryStream(imageBytes))
using (var outputStream = File.OpenWrite(imagePath))
Image.FromStream(memoryStream).Save(outputStream);
}
context.Response.ContentType = "image/png";
context.Response.WriteFile(imagePath);
}

Resources