How to Convert Image to Byte Array Using JavaScript Only to Store Image on SQL Server

How to convert image to byte array using javascript only to store image on sql server?

i have found one solution. :)

in html javascript file, first convert the uploaded image to base64 image format using following code.

var p;
var canvas = document.createElement("canvas");
var img1=document.createElement("img");

function getBase64Image(){
p=document.getElementById("fileUpload").value;
img1.setAttribute('src', p);
canvas.width = img1.width;
canvas.height = img1.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img1, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert("from getbase64 function"+dataURL );
return dataURL;
}

so we got base64 code of uploaded image in dataURL.

NOW SEND THIS BASE64 CODE (dataURL) to web service and convert the base64 string to byte array using following code and save to sql server too

c# code--for converting base64 to byte arry and to store on sql

private void Form1_Load(object sender, EventArgs e) {
int userid = 5;
string base64="";// load base 64 code to this variable from js
Byte[] bitmapData = new Byte[base64.Length];
bitmapData = Convert.FromBase64String(FixBase64ForImage(base64));
string connstr = @"user id=sa; password=*****";
database=ImageTest;
server="192.168.1.104";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
query = "insert into imagetable(userid,image) values(" + userid + "," + " @pic)";
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = bitmapData;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(picparameter);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
conn.Dispose();
}
public static string FixBase64ForImage(string image) {
StringBuilder sbText = new StringBuilder(image, image.Length);
sbText.Replace("\r\n", String.Empty);
sbText.Replace(" ", String.Empty);
return sbText.ToString();
}

hope u understand :) ......

Javascript: how to get image as bytes from a page (without redownloading)

The following js code will fetch an image from an existing <img..> element as base64 without re-downloading the image (assuming there is an image with the given selector on the page and that there is no canvas cors violation, which will be the case when you click the Run button below):

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = document.querySelector('img');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
var base64String = canvas.toDataURL();
console.log(base64String);
<img src="http://placekitten.com/40/40">

Storing images with LINQ to SQL: Converting byte array or stream to Binary

You can use the constructor:

public Binary(byte[] value)

like this:

yourObj.BinaryProperty = new Binary(bytes);

How to convert a byte array into an image?

I realize this is an old thread, but I managed to do this through an AJAX call on a web service and thought I'd share...

  • I have an image in my page already:

     <img id="ItemPreview" src="" />
  • AJAX:

    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    timeout: 10000,
    url: 'Common.asmx/GetItemPreview',
    data: '{"id":"' + document.getElementById("AwardDropDown").value + '"}',
    success: function (data) {
    if (data.d != null) {
    var results = jQuery.parseJSON(data.d);
    for (var key in results) {
    //the results is a base64 string. convert it to an image and assign as 'src'
    document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
    }
    }
    }
    });

My 'GetItemPreview' code queries a SQL server where I have an image stored as a base64 string and returns that field as the 'results':

     string itemPreview = DB.ExecuteScalar(String.Format("SELECT [avatarImage] FROM [avatar_item_template] WHERE [id] = {0}", DB.Sanitize(id)));
results.Add("Success", itemPreview);
return json.Serialize(results);

The magic is in the AJAX call at this line:

     document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];

Enjoy!

Load SQL DB Blob Image Into A Webpage

If you're looking for a function to convert data into base64, then use the btoa(..) function. It's globally available through the window object.

btoa('hello')
// => "aGVsbG8="

atob('aGVsbG8=')
// => "hello"

As this example illustrates, atob(..) does the reverse of btoa(..). Here's a link to the documentation on MDN.



Related Topics



Leave a reply



Submit