【问题标题】:Unable to cast System.string to System.Byte[]无法将 System.string 转换为 System.Byte[]
【发布时间】:2018-12-14 05:08:02
【问题描述】:

出于某种原因,从昨天开始,我一直在为此苦苦挣扎,以从 Base64 字符串生成图像,它只是不会,它从测试框中显示正常,但不会创建图像文件,无论是 PNG 还是 JPG,因此我决定在这里粘贴也许我错了。

代码是这样的

public void generateImageFromBase64(int idnumber)
{
    string connectionString = @"Data Source=DESKTOP-FJBB72F\SQLEXPRESS;Initial Catalog=ImageControl;Integrated Security=True";
    SqlConnection con = new SqlConnection(connectionString);
    con.Open();

    string query = "select img from PDFImgTableB where id =@id";
    SqlCommand cmd = new SqlCommand(query, con);

    cmd.Parameters.AddWithValue("@id", idnumber);
    SqlDataReader rd = cmd.ExecuteReader();

    while (rd.Read())
    {
        //byte[] imgData = (byte[])rd[0];
        **byte[] fileData = (byte[])rd.GetValue(0);
        string img = Convert.ToString(fileData);**
        var bytes = Convert.FromBase64String(img);
        using (var imageFile = new FileStream(@"C:\Users\*****\Desktop\output\test.png", FileMode.Create))
        {
            imageFile.Write(bytes, 0, bytes.Length);
            imageFile.Flush();
        }
    }
}

现在我用来调用它来生成图像文件的winform,看起来像这样

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        ReadAndConverttoJPG.ReadFileDB drd = new ReadAndConverttoJPG.ReadFileDB();
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                drd.generateImageFromBase64(2);
                MessageBox.Show("OK!");
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error: "+ex.ToString());
            }
        }
    }
}

我在这里可能缺少什么?

编辑

现在,Klaus,它似乎没有将 PNG 图像输出到我的桌面文件夹,这与之前的 PDF 不同

代码现在看起来像这样

public void generateImageFromBase64(int idnumber)
{
    string connectionString = @"Data Source=DESKTOP-FJBB72F\SQLEXPRESS;Initial Catalog=ImageControl;Integrated Security=True";
    SqlConnection con = new SqlConnection(connectionString);
    con.Open();

    string query = "select img from PDFImgTableB2 where id =@id";
    SqlCommand cmd = new SqlCommand(query, con);

    cmd.Parameters.AddWithValue("@id", idnumber);
    SqlDataReader rd = cmd.ExecuteReader();

    while (rd.Read())
    {
        string imgBase64 = rd.GetString(0);
        var bytes = Convert.FromBase64String(imgBase64);
        FileStream fs = new FileStream(@"C:\Users\*****\Desktop\output\test.png", FileMode.Create);
        fs.Write(bytes, 0, bytes.Length);
        fs.Close();
    }
}

【问题讨论】:

  • DbDataReader 有许多其他方法可以返回类型化(!)数据,例如您可能会发现有用的 GetBytes()。但似乎 Base64 字符串会保存为字符串...
  • 尝试删除ImageFile.Flush()并添加ImageFile.Save();
  • 数据库中的img是什么类型的?它是存储为 base64 字符串还是二进制数据?
  • 首先向我们展示如何将 img 保存在数据库中,这里似乎不需要将字节数组转换为字符串。
  • @KlausGütter base64 字符串

标签: c# sql-server winforms


【解决方案1】:

由于数据库字段包含base64字符串,只需将其作为字符串获取并转换为二进制:

string imgBase64 = rd.GetString(0);
var bytes = Convert.FromBase64String(imgBase64);

【讨论】:

  • 这项工作特别是在 mssql 上保存为 nvarchar(max) 时会起作用
  • 我已经更新了问题,因为它似乎没有将文件输出到目录@Klaus
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 2020-10-28
相关资源
最近更新 更多