简体   繁体   中英

Unable to cast System.string to System.Byte[]

For some reason, i have been struggling with this since yesterday to generate an image from a Base64 string, it just wouldnt and it shows ok from a test box but does not create the image file , be it PNG or JPG hence i decided to paste here maybe i am wrong somehow.

Code looks like this

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

Now the winform i am using to call it to generate the image file, looks like this

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

What could i be missing here ?

Edit

Now here is what, Klaus, it does not seem to output the PNG image to my desktop folder unlike the PDF which did earlier

Code now looks like this

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

Since the database field contains the base64 string, simply get it as string and convert to binary:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM