无法将System.string强制转换为System.Byte []

时间:2018-12-14 05:08:02

标签: c# sql-server winforms

由于某种原因,我从昨天开始就一直在努力从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,现在是这里了,与以前的PDF不同,似乎没有将PNG图像输出到我的桌面文件夹中

代码现在看起来像这样

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

1 个答案:

答案 0 :(得分:0)

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

string imgBase64 = rd.GetString(0);
var bytes = Convert.FromBase64String(imgBase64);
相关问题