byte数组存入数据库总是null

byte数组存入数据库总是null,第1张

将byte数组存入数据库时出现null值,可能是由于数据库中没有足够的空间来存储byte数组,或者数据库中的字段类型不正确,或者byte数组的长度超过了数据库中字段的最大长度。因此,在将byte数组存入数据库之前,应该先检查数据库中的字段类型是否正确,并确保byte数组的长度不超过数据库中字段的最大长度。

第一种:可以直接进行写入,代码如下:

[c-sharp] view plaincopyprint?

public static byte[] GetBytesByImage(PictureBox pb)

{

byte[] photo_byte= null

if (!pb.Image.Equals(null))

{

using (MemoryStream ms = new MemoryStream())

{

Bitmap bmp = new Bitmap(pb.Image)

bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg)

photo_byte = new byte[ms.Length]

ms.Position = 0

ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length))

bmp.Dispose()

}

}

return photo_byte

}

第二种:首先将照片转化为byte[]类型,然后在写入数据,代码如下;

[c-sharp] view plaincopyprint?

public static byte[] GetBytesByImagePath(string strFile)

{

byte[] photo_byte = null

using (FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read))

{

using (BinaryReader br = new BinaryReader(fs))

{

photo_byte = br.ReadBytes((int)fs.Length)

}

}

return photo_byte

}

第三种:直接读取byte[]并转化为图片;

[c-sharp] view plaincopyprint?

public static Image GetImageByBytes(byte[] bytes)

{

Image photo = null

using (MemoryStream ms = new MemoryStream(bytes))

{

ms.Write(bytes, 0, bytes.Length)

photo = Image.FromStream(ms, true)

}

return photo

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/sjk/10035167.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-04
下一篇2023-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存