图像转字节数组时有时会遇到无法识别图片格式的情况,造成无法转换,此时强制传入图片格式参数进行强制转换即可。
/// <summary> /// 将字节数组转为图片 /// </summary> /// <param name=" b">字节数组</param> /// <returns>返回图片</returns> public static Image ByteToImage(byte[] b) { try { MemoryStream ms = new MemoryStream(b); return Bitmap.FromStream(ms, true); } catch { return null; } } /// <summary> /// 图像转字节数组 /// </summary> /// <param name="image">图像</param> /// <param name="f">特殊情况下无法识别图片格式,手动传入图片格式进行强制转换</param> /// <returns></returns> public static byte[] ImageToBytes(Image image, ImageFormat f = null) { ImageFormat format = image.RawFormat; using (MemoryStream ms = new MemoryStream()) { if (f == null) { if (format.Equals(ImageFormat.Jpeg)) { image.Save(ms, ImageFormat.Jpeg); } else if (format.Equals(ImageFormat.Png)) { image.Save(ms, ImageFormat.Png); } else if (format.Equals(ImageFormat.Bmp)) { image.Save(ms, ImageFormat.Bmp); } else if (format.Equals(ImageFormat.Gif)) { image.Save(ms, ImageFormat.Gif); } else if (format.Equals(ImageFormat.Icon)) { image.Save(ms, ImageFormat.Icon); } else if (format.Equals(ImageFormat.Tiff)) { image.Save(ms, ImageFormat.Tiff); } } else { image.Save(ms, f); } byte[] buffer = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return buffer; } }
评论前必须登录!
注册