0

在我的以下代码中,如果我的 PictureBox(pbspic) 为 null,则我想返回数据 null 否则如果 PictureBox(pbspic) 包含图片我希望数据返回图片字节,以便我可以在我的数据库中保存 null 或图片

using (MemoryStream stream = new MemoryStream())
        {
            Bitmap bmp = new Bitmap(pbspic.Image);
            bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            stream.Position = 0;
            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            return data;
        }
cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = data;
dm2.ExecActQuery("StudentsInsert", cmd);
4

2 回答 2

2

您是否尝试过类似以下的方法?:

else if(pbspic == null) /* Or it could be pbspic.Image == null, depends on which is null */ 
{
   ep.SetError(tbmonfee, "Image is missing.");
   return;
}
else
{
using (MemoryStream stream = new MemoryStream())
            {
                Bitmap bmp = new Bitmap(pbspic.Image);
                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                byte[] data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);
            }

if(data == null) /* Or check data length if it's never null */ 
{
   ep.SetError(tbmonfee, "Image is missing.");
   return;
}
}
于 2012-04-17T16:23:33.103 回答
1

尝试创建您的流的方法,然后将其调用为这样的图片

private byte[] GetPic(Image img)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            Bitmap bmp = new Bitmap(pbspic.Image);
            bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            stream.Position = 0;
            byte[] data = new byte[stream.Length];
            stream.Read(data, 0, data.Length);
            return data;
        }
    }

用法:

if (pbspic.Image == null)
        {
            cmd.Parameters.Add("@Photo", SqlDbType.VarChar).Value = "NULL";
        }
        else
        {
            cmd.Parameters.Add("@Photo", SqlDbType.Image).Value = GetPic(pbspic.Image);
        }
        dm2.ExecActQuery("StudentsInsert", cmd);
于 2012-04-17T17:40:15.230 回答