如何仅使用javascript将图像转换为字节数组以将图像存储在sql server上?

2021-11-18 00:00:00 image bytearray javascript sql-server

我正在努力使用客户端脚本将图像转换为字节数组.我必须将图像转换为字节数组,并将此数组传递给 web 服务,以便 web 服务可以将图像保存在 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.

推荐答案

我找到了一个解决方案.:)

i have found one solution. :)

在 html javascript 文件中,首先使用以下代码将上传的图像转换为 base64 图像格式.

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;
} 

所以我们在dataURL中得到了上传图片的base64代码.

so we got base64 code of uploaded image in dataURL.

现在将这个 BASE64 代码 (dataURL) 发送到 Web 服务并使用以下代码将 base64 字符串转换为字节数组并保存到 sql server

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# 代码--用于将 base64 转换为字节 arry 并存储在 sql 中

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 :) ......

相关文章