【发布时间】: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