Load Image Src from Byte[] Asp.Net MVC 3 - c#

I have an ASP.net MVC 3 application where I want to store an image as bytes in the model and then load it from the model into the src attribute of an html image tag.
e.g.
//Property in Model
public byte[] Image { get; set; }
But when I try this it errors:
<img src = "#Model.Image" alt=""/>
How can I load the image from bytes? I want to avoid calling the Controller again to get the image as a FileResult.
Is it possible?

The easiest way is something like this:
<img src="data:image/png;base64,#System.Convert.ToBase64String(Model.Image)" alt=""/>
This assumes a PNG payload and is not very well supported by legacy browsers.
I would actually recommend saving it to disk and letting your web server host it up separately.

You can directly embed the image as a base64 encoded string.
Example:
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"
width="16" height="14" alt="embedded folder icon">
The size of the data is limited to 32 KiB in Internet Explorer 8. Additionally base64 results in an overhead of 33%.
More information: http://en.wikipedia.org/wiki/Data_URI_scheme

Related

Displaying image from the database in MVC

I have a field (the type is varbinary) in my database that respresent an image. I would to read this image and display it in my view. i read from database using ADO.
in my data service i have (this is part of private web api project):
img= (byte []) reader["Image"];
i convert varbinary to array of byte
the my view is basically :
<img src="data:image/tiff;base64, #Model.ImageSource" />
but in my controller im not able to create a base64 string to assign in view to img tag.
Another problem can be that image is stored as tiff format.
I have tried in controller to do (this is in another mvc project that recall web api):
// call my service that return me image
var result = await client.GetAsync("ImagesController/GetImageBytes/" + id);
// ImageSource is a property of my viewmodel
ImageSource=Convert.ToBase64String(result.Content.ReadAsStreamAsync().Result)
// or
ImageSource= Convert.ToBase64String(JsonConvert.DeserializeObject<Byte[]>(result.Content.ReadAsStringAsync().Result))
// or
ImageSource= Convert.ToBase64String(result.Content.ReadAsByteArrayAsync().Result)
but despite hundreds of attempts (really) Im not able to visualize anything. My view show image placeholder only.
Someone can help me?

base64 string image data is not completly displaying in ie8

I have to display an image,which is in base64 string format. It's working fine in ie9,chrome and mozilla.But when using ie8 image is not completly displaying.Due to security purpose i am not able save image on server and user url for displaying image.Is there any other way to display image on ie8.
As per the answer from Ryan McGrath at Internet Explorer and Base64 image display: IE8 can only show Base64 images up to 32KB in size.
Most likely your image is too large to be handled by IE8.
I don't have the time to write an extensive example right now, but a possible workaround would be to serve the image through another webpage. Read the image into a stream and send it back. For example, you might do something like this:
void GetImage(int imageId) {
byte[] imageData = GetDataFromDatabase(imageId);
using (MemoryStream ms = new MemoryStream(imageData)) {
Response.ContentType = "image/png";
ms.WriteTo(Response.OutputStream);
}
}
And then in your webpage you could do something like this:
<img src="Image.aspx?GetImage&imageId=1"/>
Note: All of the this is non-working code and possibly contains typos and non-existing methods. But it's just an idea to get you started. If you perform a Google search for "C# + asp.net output image" you get a whole bunch of results with working code samples, such as http://www.codeproject.com/Articles/33310/C-Save-and-Load-Image-from-Database.

How to load image from binary data in Asp.Net?

I am a beginner in .net Technology. I am using VS2008, C# ,Asp.Net 3.5 Framework, SQL SERVER 2005. In a database table 'Cust_M_Tbl', there is a field of varchar(500) type viz Cust_Image. The value in the Cust_Image is
mspZVnmQlz1GgRRpQEqBFGTHeUELiUhxQQ2GQU9BF3DCUYEeaiJJAQQLKGCBDYcySMENDi9qgQWJv0xBEe8sWkEEDr19QQWMxVoBE20odAEGFDtZAQeBtUtBDn7NUkEd0ytIAQl/r4WBBooWTAEHiCSGAQiMyjEBCFG+KYELYSoowQzluisBBt1NTwEYSM4hgQ5LTTpBD0e5KUEGYa0ugQxqoCLBCWgZKcEKcJJZQQ2DM1nBBAszVoEHiQMSZGhtcwEGCgwPExQUExMUFAMSYmVqcHUECQsOEBMTEhITFAISZWVobnUDCA0PERMVFRQUFRUDEWBjaG5yAQYLDg8REREREQISamlqb3UFCQ0PEhMUFRUWFhYDEV9hZmxxdQMJDQ4PEBEREQIRa2xucXcGCg0PEhMVFhgZGQQRY2ZpbXIBBgsNDxASExQDEHJzdgMHDA0PEBMVFxgZBBFiY2ZpbnMDCQsNDxIVFwMPc3YDBgkNDQ4PExQWGAQRXl9hY2ZqcwQIDBATFxgEDgQHCgwPDQ8PEhMVAxFXWFlcXV9hbXYFCxIWGRoGDA0ODwsODxMDEFVXV1dVVltkcwYOFhodAAD/Aw1PUVFQTk5RV2YKEQAA/wQMR0VFR0ZJQz0xAAD/BQdCQkMY8B0ZtKlQFCF/MssEMp7YkXe5scQP8fmd96ZVrvO8oGFXhoDAjEe5o+U/XAnxKOTp9vDgoSTOH22Eg2rytkcs9uqvFV7GSeUaetGWD0jVWeSqCuD6Sb6l/KxsWXbH1iDoY8LJhgKhkvVBei3Xmp4gx74bl58QiXckdX0KgxJhDWSa/zDvZvGfSVKVLvXzhv8/A+3tV1M36hSdkpPukozfqJj4O9ELUHNNUj8SRvFr0do7bU6tXqEbVubYYiVnalpHbCb07QoVPsO402Lwu3d9vnk6+bnZ/zbgpmAm4zfCLQrlOseeQ4XOarfqeCA14qS2EWZxATfilss++PYY+xymdxgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGA==
I want to display this customer image in my web page. How can I do it? Should I decrypt it? or it is in any other format? Any help will be appreciated. Regards,
After decoding as #Christophe Geers suggested
use
string encodedString = "your image data encoded as base 64 char array";
byte[] data = Convert.FromBase64String(encodedString);
Response.BinaryWrite(data);
maybe this can help more:
http://odetocode.com/articles/172.aspx
This looks like Base64 encoding. You can find an online decoder here:
http://en.wikipedia.org/wiki/Base64
It validates your input as a valid Base-64 char array.
You can decode a base64 string in C# in the following way:
string encodedString = "your image data encoded as base 64 char array";
byte[] data = Convert.FromBase64String(encodedString);
Take a look at the FromBase64String article on MSDN for more information.
Now you want to display the image on an ASP.NET web page (*.ASPX).
E.g.:
<img src="myimage.jpg" />
Instead of referencing an actual image file (eg: myimage.jpg), you want to reference an ASP.NET handler (*.ASHX) that serves the bytes of the image (the byte[] array named data in the previous code sample).
E.g.:
<img src="ImageHandler.ashx" />
The code for the image handler looks something like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Load the image (see previous code sample)
byte[] data = ...;
// Display the image
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.ContentType = "image/JPEG";
}
}
Read more about implementing an IHttpHandler on MSDN.
You need to pass an identifier to the imagehandler.ashx page so that you know which image to retrieved.
E.g.:
<img src="ImageHandler.ashx?id=<%=id%>" />
Put this instead of your img-tag or your ASP.NET image control.

Read a web page with all images in Base64-Embedded format

In my scenario I want to download the HTML of a page (any page on the Internet) programaticaly but also I want all of the images in the HTML to be in base64 embedded format (not referenced)
In other words, instead of :
<img src='/images/delete.gif' />
I want the downloaded html to look like this:
<img src="data:image/gif;base64,R0lGODl..." />
This way I don't need to go through the process of storing all images in directories, etc, etc.
Does any of you have any idea how this can be done? Or any plugin to do this efficiently?
Well, you'd need to:
Download the original HTML
Find each img element in the HTML (for instance using the HTML agility pack) and for each one:
If it's already using a data URL, ignore it
Otherwise:
Download the image
Encoded it in Base64 using Convert.ToBase64String
Replace the original img tag with one using the base64 version (either in the original string, or via a DOM representation)
Save the final HTML to disk
Is any of these steps causing you a particular problem? You could potentially make it quicker by downloading the images in parallel, but I'd get a serial version working first.
Instead of using a html page with images as base64 encoded strings in the src attribute you might consider using the MHTML format instead. Most browsers supports the format and it embeds all external resources (including images).
var msg = new CDO.MessageClass();
msg.MimeFormatted = true;
msg.CreateMHTMLBody("http://www.google.com", CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
var stream = msg.GetStream();
var mhtml = stream.ReadText(stream.Size);
Use a regular expression (regex) to extract URLs from img tags, translate them to absolute URLs using the Uri class, then use WebClient to download the target images. After that it's just a case of using Convert.ToBase64String to produce the Base64.

Render byte[] to image using jQuery

I am currently reading an image from an SQL Server database as byte[]. I would like to pass the image either as a byte[] or a real image to jQuery and dynamically load it.
How and what would be the best approach to do this?
Thanks in advance. :)
Edit: Here's the solution:
Server-side / C#:
string json = JsonConvert.SerializeObject(employee);
Client-side / Ajax:
$('#image').attr('src', "data:image/jpg;base64,"+employee.Image);
Return the byte[] from the webserver with the correct content-type set, that way you should be able to set it as a source for a image tag. Should be the simplest solution.
If you must do it this way, you can insert image data directly into the src attribute using the following syntax:
data:image/<type>;base64,<data>
Replace with the image type (jpg, png, gif) and with your data, encoded in base 64.
However, as decyclone says, the best way to do this would be to create a separate page that only outputs your image data, and sends the appropriate content-type header. Then set the image src to point to that page.
I don't think using jQuery is the right thing to do here. It's a client side thing. JavaScript, to be specific.
Usually, you create a page that writes all these bytes in array using Response.Write() and setting the content-type to jpeg, bmp, etc. depending on image type.
I am currently reading an image from a JSON Response. I would like to pass this encoded string into the image control on Jquery template and load it dynamically, How and what would be the best approach to do this? Template is as follows:
<script id="ImageDiv" type="image/png">
<div style="width:200px;height:150px;>
<img src="${ImageView}" alt="" />
</div>
</script>
Js file is as follows:
var demo = new Object();
$.each(msg.images, function (key, value)
{
if (this.IsImage)
{
demo["ImageView"]="data:image/png;base64,"+this.Image;
$('#ImageDiv').tmpl(demo).appendTo("#Demo-Image");
}
});
JSON Response is as follows:
msg = {"Images":[ "Description": "Image1", "Image": "encoded string of image", "IsImage": true, "MimeType": "image/png", } ]
less space to copy encoded string of image.

Categories

Resources