图片和字节数组的相互转换
为存储和读取方便,经常需要将图片以字节数组形式存储到数据库,或者从数据库读取图片的字节数组数据还原为图片,可以定义一个转换类,方便调用。
public static class Img2Byte{/// /// 从图像转换为字节数组/// /// Image对象/// 字节数组 public static byte[] getByteFromImage(Image img){byte[] imgByte = null;using (MemoryStream ms = new MemoryStream()){img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);imgByte = ms.GetBuffer();}return imgByte;}/// /// 从字节数组转换为图像/// /// 字节数组/// Image对象 public static Image getImageFromByte(byte[] imgByte){Image img = null;if (imgByte.Length == 0)return null;using (MemoryStream ms = new MemoryStream(imgByte)){img = Image.FromStream(ms);}return img;}/// /// 从图片路径转为字节数组/// /// 图片完整路径/// 字节数组 public static byte[] getByteFromImgFile(string imgFilePath){if(!File.Exists(imgFilePath))return null;FileStream fs = new FileStream(imgFilePath, FileMode.Open, FileAccess.Read);long length = fs.Length;byte[] imgByte = new byte[length];fs.Read(imgByte, 0, imgByte.Length);fs.Close();return imgByte;}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
