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.
Related
I have C# code for fetching images from URLs like http://i.imgur.com/QvkaduU.jpg but how would I fetch the image from Web pages like this:http://imgur.com/gallery/QvkaduU?
Is there any "easy" way to do this or I will have to fetch the HTML and construct a C# parser that looks in HTML for images that are bigger than all the others?
Let me clear this up. If you paste http://imgur.com/gallery/QvkaduU (HTML version) into for example Facebook's status update field it will find the main image and make a thumbnail out of it, this is exactly the behavior I'm looking for. The question is, how is this done? Do I have to write my own HTML parser or is there an easy way to get this?
There is no easy way to get a "good" thumbnail image for an arbitrary URL.
Facebook's algorithm for doing so is fairly complex. Page developers are able to give it a hint by adding various meta tags to the <head>, including:
<meta property="og:image" content="http://url_to_your_image_here" />
or
<link rel="image_src" href="http://www.code-digital.co.uk/preview.jpg" />
(more on this)
... so if you wanted to replicate Facebook's algorithm, you would need to fetch the page source, parse it for any "hints" like the one above (you'd better check that I haven't missed any other "hint" formats), and come up with a fallback algorithm if the page doesn't include one of those.
A more realistic solution would be to use someone else's URL -> thumbnail system.
If you like Facebook's version, I think you should be able to request Facebook's thumbnail for a given URL via their API.
Other services which offer this sort of thing are:
http://webthumb.bluga.net/home (not free)
http://immediatenet.com/thumbnail_api.html (free, may have restrictive TOS)
https://www.google.com/search?q=get+thumbnail+for+url
If the QvkaduU part is always the same between the html page and the image, could you just do a string replacement?
"http://imgur.com/gallery/QvkaduU".Replace("imgur.com/gallery","i.imgur.com") + ".jpg";
I would fetch the whole HTML source and put all <img ... src="..."> parameters as well as < ... style="... background-image: ...;"> css inline properties using regex and try to download all files behind the links temporary. Then I would (try to convert it to Bitmap and) check the pixel size, the largest picture should be the picture you want.
Google might help you how to check pixel size and convert any images.
The regex to get all image links from a HTML source should be
<img[^>]+src=\"([^"]+)\".*?>|<[^>]+style=\"[^"]*background-image:\s*url\(\s*'?([^')])\s*'?)\s*;.*?> (not tested, but pretty sure)
The result will be in the 2nd or 3rd group index, also don't forget to prefix the current url on relative links.
You're already on the right track, yes the most reliable way would be to fetch the HTML, parse it and look for images, you would then rank the images based on position and size. For instance, if the first image you find is big enough to make the thumbnail, then cool, if however it is small, you go to the next image, etc. It would be most advisable to use an image plugin like Timthumb (I think I've seen an ASP.NET version sometime) and cache the images such that once you've looked up the thumbnail to represent a website, you can call the image(s) from the catch instead.
Can you try to do something like this?
public void ProcessRequest(HttpContext context)
{
{
// load here the image
....
// and send it to browser
ctx.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
}
You can also try what they are talking about here. I tried it and it worked like a charm.
http://www.dotnetspider.com/resources/42565-Download-images-from-URL-using-C.aspx
can you try this
public Bitmap getImageFromURL(String sURL)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(sURL);
myRequest.Method = "GET";
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
myResponse.Close();
return bmp;
}
gotten from
How to get an image to a pictureBox from an URL? (Windows Mobile)
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
My current project has a .js file with hard coded data in it. So I am referencing this file and on clientside. I am using this file to get the data when ever I require on client side. But my task is to generate this .js file dynamically. I am getting my values in json format from database. SO I need a way to write this json formatted data into .js file, so I can use that written data on client side.
Needed Format in JS:
var list = new Array();
list["1000"] = "TestEvent1";
Actual Json Format:
{
"__metadata": {
"type": "event_Result"
}, "event_id": 1000, "event_GROUPId": 17, "event_name": "TestEvent1",
}
Please help me.
Thanks
You can have a generic handler ashx that outputs javascript content. Set your output content type to "text-javascript".
It doesn't have to have a file extension of .js, the content type and how it's reference is what matters
<script type="text/javascript" src="myJavascript.ashx"></script>
Why don't you simply use the json encoded data by saving it into a variable or by overriding the variable that holds the initial data?
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.
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.