C# 错误:从数据库中筛选的DataGridView表将图像数据转换为pdf时出错

C# 错误:从数据库中筛选的DataGridView表将图像数据转换为pdf时出错,c#,datagridview,itext,C#,Datagridview,Itext,我正在尝试将带有图像列的DataGridView数据转换为C#中的PDF文件,该图像列是从我的SQL数据库中筛选出来的。我使用iTextSharp编写了这段代码,但是我得到了一个错误 无法将System.Drawing.bitmap类型的对象强制转换为System byte[] 有人能帮我吗 谢谢 这是我的密码: foreach (DataGridViewCell cell in row.Cells) { if(row.Cells[0].Value!= null) {

我正在尝试将带有图像列的DataGridView数据转换为C#中的PDF文件,该图像列是从我的SQL数据库中筛选出来的。我使用iTextSharp编写了这段代码,但是我得到了一个错误

无法将System.Drawing.bitmap类型的对象强制转换为System byte[]

有人能帮我吗

谢谢

这是我的密码:

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

希望这对您有所帮助

该消息暗示您需要在进行转换之前将位图转换为bite数组,此外,您正在使用iTextSharp.text获取图像可能不正确,那么如何将datagridview位图图像转换为字节数组呢?任何资源请?我认为错误发生在哪一行?字节[]img=(字节[])行。单元格[1]。值;请你确认一下好吗?是的,你是对的。。实际上默认情况下,当从数据库调用图像数据时,datagridview包含位图图像。。然后我试图将这个图像列数据转换为pdf格式,它无法将位图转换为字节。。通过互联网搜索,但还没有得到确切的答案:(我为你的问题添加了一个答案。如果有帮助,请不要忘记接受并向上箭头显示答案。谢谢