Convert Image To Bytes and Read It Via JQuery
Today, I got a requirement to work on a task on how to convert an image (can be in any format i.e. png, jpg etc.) to array of bytes and then read that image via JQuery.
After some mind exercise, I finally found the solution and wanted to share with you so that you can save much of your precious time in case you don't know how to achieve it.
Note: There can be lots of ways to achieve it but I found this way as the easiest.
Here is the pre-requisite:
1) You would need "NewtonsoftJson" dll file. You can get it from here - http://james.newtonking.com/json. After downloading it, just add the "dll" and it's reference to your Visual Studio solution as "
using Newtonsoft.Json;".
2) You would need JQuery library reference.
3) Knowledge of C# and JQuery.
4) Have an image tag in your HTML and don't set its "src" i.e.
<img id="img1" src="" alt="image" />
Once, you have all the pre-requisites, add the below line of code in your ".cs" file:
[WebMethod]
public static string ConvertingToBytes()
{ try
{ System.Drawing.Image img = System.Drawing.Image.FromFile(@"D:\Projects\pics\SampleImage.jpg");
byte[] byteArray;
using (MemoryStream memoryStream = new MemoryStream())
{ img.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byteArray = memoryStream.ToArray(); string json = JsonConvert.SerializeObject(byteArray);
return json;
}
} catch
{ return null;
}
}
And the below line of code in your ".aspx" file:
function ConvertToImage() {
$.ajax({ type: "POST",
url: "default.aspx/ConvertingToBytes",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
if (msg.d != null) {
msg.d = jQuery.parseJSON(msg.d); var imageSrc = "data:image/jpg;base64," + msg.d;
$('#img1').attr('src', imageSrc);
}
}, error: function (msg, status, errorthrown) {
alert(msg.toString() + "-" + status + "-" + errorthrown);
}
});
}
Call this JQuery method in your button click event or whatever way which will suit your requirement.
$("#Btn1").on("click", function (event) {
event.preventDefault();
ConvertToImage();
});
You will be good to go.
Note: You can now see the source code of your page, it will show your image's src in a byte format.
Thanks! It helped :)
ReplyDeleteMy pleasure! :)
Delete