По какой-то причине я боролся с этим со вчерашнего дня, чтобы сгенерировать изображение из строки 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());
}
}
}
}
Чего мне здесь не хватает?
Редактировать
Теперь вот что, Клаус, похоже, не выводит изображение 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();
}
}