You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取MySQL中Dart Uint8List并转换为C#字节数组?

问题解决方法

你的核心问题是Dart端存入的是Base64编码后的字符串,但C#端错误地将读取到的字符串直接强转为byte[],导致生成Bitmap时参数无效。解决步骤如下:

关键原因

Dart代码中通过base64.encode(_getFileValues)将图片字节数组转为了Base64字符串,并存入数据库。C#读取时,数据库返回的是这个Base64字符串,而非原始二进制字节,直接强转byte[]会得到错误的字节数据,无法被Bitmap识别。

修正后的C#代码

不需要额外引入第三方库,使用.NET自带的Convert.FromBase64String方法即可完成转换:

MySqlDataAdapter da = new MySqlDataAdapter(command);
DataSet ds = new DataSet();

da.Fill(ds);
// 读取数据库中的Base64字符串
string base64Str = ds.Tables[0].Rows[0][0].ToString();
// 将Base64字符串转为正确的字节数组
byte[] imageBytes = Convert.FromBase64String(base64Str);
// 用字节数组创建MemoryStream生成Bitmap
using (MemoryStream ms = new MemoryStream(imageBytes))
{
    pictureBox.Image = new Bitmap(ms);
}

补充说明

  • 使用using包裹MemoryStream可以确保资源被正确释放,避免内存泄漏
  • 如果数据库中存储的Base64字符串包含换行或空格,需要先调用base64Str = base64Str.Replace("\r", "").Replace("\n", "").Replace(" ", "")清理无效字符,再进行转换

内容的提问来源于stack exchange,提问作者HenryCollin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:10:53