Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

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

I am struggling converting image to byte array using client side script. I have to convert image to byte array, and pass this array to web service , so that the web services can save the image in sql server. Any one please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
", String.Empty);
    sbText.Replace(" ", String.Empty);
    return sbText.ToString();
}

hope u understand :) ......


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...