如何将图像从SQL Server转换为字符串

本文关键字:Server 转换 字符串 SQL 图像 | 更新日期: 2023-09-27 18:07:31

我有两个数据库,每一个在一个项目(Winforms和web服务项目),我有一个查询实体框架发送数据从项目1到项目2。我的问题是如何将图像从第一个数据库转换为字符串,通过查询发送它?

这是我的web服务代码:

// Entity Framework
Person sd = new Person(); 
// Method to get data from winforms app
public void GetData(string name,string picture)
{
    sd.name= name;
    sd.picture= ImageToByteArray(picture);
    context.AddToPerson(sd);
    context.SaveChanges();
}
//Method to save the image into database
private Byte[] ImageToByteArray(string source)
{
    FileInfo fInfo = new FileInfo(source);
    long sizeByte = fInfo.Length;
    FileStream fs = new FileStream(source, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    byte[] data = br.ReadBytes((int)sizeByte);
    return data;
}
这是我的Winforms代码:
WebService3SD.Service1SoapClient oService = new WebService3SD.Service1SoapClient();
private void SendData()
{
    Driver dr = context.Drivers.FirstOrDefault(d => d.name == "name1");
    oService.GetData(dr.name,????);//here i have no idea what i have to do ?!
}

为此,我需要一个方法将图像转换为字符串,所以请如果有人有任何如果你有什么想法,我将非常感激。

如何将图像从SQL Server转换为字符串

您可能希望将图像编码为Base64以便传输。现在,您的代码正在尝试读取服务器文件系统。查看如下代码:

在发出请求的应用程序中:

private void btnEncode_Click(object sender, EventArgs e)
{
  if (!string.IsNullOrEmpty(txtInFile.Text))
  {
    FileStream fs = new FileStream(txtInFile.Text, 
                                   FileMode.Open, 
                                   FileAccess.Read);
    byte[] filebytes = new byte[fs.Length];
    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
    string encodedData = 
        Convert.ToBase64String(filebytes,                 
                               Base64FormattingOptions.InsertLineBreaks);
    txtEncoded.Text = encodedData; 
  }
}

接收端:

private void btnDecode_Click(object sender, EventArgs e)
{
  if (!string.IsNullOrEmpty(txtOutFile.Text))
  {
    byte[] filebytes = Convert.FromBase64String(txtEncoded.Text);
    FileStream fs = new FileStream(txtOutFile.Text, 
                                   FileMode.CreateNew, 
                                   FileAccess.Write, 
                                   FileShare.None);
    fs.Write(filebytes, 0, filebytes.Length);
    fs.Close(); 
  }
}