将array的字节转换为image时,argumentException是未处理的错误

时间:2011-08-18 10:47:52

标签: c# .net image

我已完成此操作,用于将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);
        }
    }      
}

1 个答案:

答案 0 :(得分:0)

可以引发ArgumentException的docs状态:

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