c# - 错误:当从数据库中过滤的 DataGridView 表中的图像数据转换为 pdf 时
问题描述
我正在尝试将带有从我的 SQL 数据库中过滤的图像列的 DataGridView 数据转换为 C# 中的 PDF 文件。我使用 iTextSharp 编写了此代码,但出现错误
无法将 System.Drawing.bitmap 类型的对象转换为系统字节 [] 类型
任何人都可以帮助我吗?
谢谢。
这是我的代码:
foreach (DataGridViewCell cell in row.Cells)
{
if(row.Cells[0].Value!= null)
{
pdfTable.AddCell(row.Cells[0].Value.ToString());
}
if (row.Cells[1].Value != null)
{
byte[] img = (byte[])row.Cells[1].Value;
pdfTable.AddCell(iTextSharp.text.Image.GetInstance(img));
}
}
解决方案
该错误是由于铸造失败而产生的。根据此将位图转换为字节数组,您可能需要添加一个方法来执行转换。
private byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
所以你的代码可能看起来像这样。
foreach (DataGridViewCell cell in row.Cells)
{
//... extra code
if (row.Cells[1].Value != null)
{
byte[] img = ImageToByte(row.Cells[1].Value);
pdfTable.AddCell(iTextSharp.text.Image.GetInstance(img));
}
}
希望这可以帮助
推荐阅读
- javascript - ReactJS:已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查
- c# - 无法将字符串“名称”转换为字典键类型 - 创建一个 TypeConverter 以从字符串转换为键类型对象
- kubernetes - Spinnaker 中存储设置的自定义配置文件
- python - How does this while-loop compute? (x = function(x))
- keras - 如何在谷歌 colab 中找到 keras.json 文件?
- node.js - 将 Strapi API 部署到 Plesk
- java - X509TrustManager 的 checkServerTrusted 方法中验证了哪些所有参数?
- python - 在 python 的子目录中对具有字母数字字符的列表作为文件名进行排序
- objective-c - VSCode 显示 Objective-C 头文件的“无法识别的令牌”
- sql-server - 将 SQL Server 2016 兼容级别更改为 2012