【问题标题】:How to convert image from SQL Server to string? [duplicate]如何将图像从 SQL Server 转换为字符串? [复制]
【发布时间】:2013-04-04 20:24:08
【问题描述】:

我在一个项目(Winforms 和 Web 服务项目)中有两个数据库,我有一个使用 Entity Framework 的查询,将数据从项目 1 发送到项目 2。我的问题是如何转换第一个数据库中的图像要字符串通过查询发送它?

这是我的网络服务代码:

// 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 ?!
}

为此,我需要一种将图像转换为字符串的方法,所以请如果有人有任何 对此我将不胜感激。

【问题讨论】:

  • 很明显GetData 期望picture 是一个字符串表示服务器上文件的路径。 (它被传递给FileInfo 的构造函数)所以你不是“将图像转换为字符串”,而是需要将它传递给服务器上已经存在的文件的路径。如果这不是你想要的,你应该实现你的服务器,这样它就不能基于本地路径工作。
  • 这似乎是一个很好的解决方案 Kirk 但我该如何编写代码

标签: c# sql-server winforms entity-framework


【解决方案1】:

您可能希望将图像编码为 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(); 
  }
}

【讨论】:

  • 非常感谢,但是第一种方法我应该把我的图片放在哪里?
猜你喜欢
  • 2013-04-19
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
  • 2016-07-29
  • 2013-02-15
  • 1970-01-01
相关资源
最近更新 更多