将数组字节转换为图像时发生未处理的错误
本文关键字:未处理 错误 图像 数组 字节 转换 | 更新日期: 2023-09-27 18:05:53
我已经完成了这个转换数组的字节在gridview的列之一到system.drawing.image得到了一个错误在这行
Image returnImage = Image.FromStream(ms);
argumentexception was unhandled
Parameter is not valid.
代码是这样的
private byte[] objtoarray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
public Image bytearraytoimage(byte[] bytearray)
{
MemoryStream ms = new MemoryStream(bytearray,0,bytearray.Length);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
{
byte[] bits = null;
Image img = null;
if (e.ColumnIndex != productgridview.Columns["productimage"].Index) return;
if (productgridview.SelectedCells.Count == 0) return;
object selectedValue = productgridview.SelectedCells[0].Value;
bits= objtoarray(selectedValue);
img = bytearraytoimage(bits);
if (img is Image)
{
// Forms are IDisposable, so use them embedded in a using statement.
using (ProductDescriptionForm pf = new ProductDescriptionForm())
{
pf.picture = (Image)selectedValue;
pf.ShowDialog(this);
}
}
}
文档声明ArgumentException可以在以下情况引发:
The stream does not have a valid image format
-or-
stream is null.
既然objtoarray
可以返回null,那么productgridview.SelectedCells[0].Value
是null还是无效值?
object selectedValue = productgridview.SelectedCells[0].Value;
bits= objtoarray(selectedValue);