Byte[]、Image、Bitmap 之间的相互转换
2014-04-11 16:16
465 查看
//Image转换Bitmap //1. Bitmap img = new Bitmap(imgSelect.Image); //2. Bitmap bmp = (Bitmap)pictureBox1.Image; /// <summary> /// 将图片Image转换成Byte[] /// </summary> /// <param name="Image">image对象</param> /// <param name="imageFormat">后缀名</param> /// <returns></returns> public static byte[] ImageToBytes(Image Image, System.Drawing.Imaging.ImageFormat imageFormat) { if (Image == null) { return null; } byte[] data = null; using (MemoryStream ms = new MemoryStream()) { using (Bitmap Bitmap = new Bitmap(Image)) { Bitmap.Save(ms, imageFormat); ms.Position = 0; data = new byte[ms.Length]; ms.Read(data, 0, Convert.ToInt32(ms.Length)); ms.Flush(); } } return data; } /// <summary> /// byte[]转换成Image /// </summary> /// <param name="byteArrayIn">二进制图片流</param> /// <returns>Image</returns> public static System.Drawing.Image byteArrayToImage(byte[] byteArrayIn) { if (byteArrayIn == null) return null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayIn)) { System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms); ms.Flush(); return returnImage; } } /// <summary> /// byte[] 转换 Bitmap /// </summary> /// <param name="Bytes">byte[]</param> /// <returns></returns> public static Bitmap BytesToBitmap(byte[] Bytes) { MemoryStream stream = null; try { stream = new MemoryStream(Bytes); return new Bitmap((Image)new Bitmap(stream)); } catch (ArgumentNullException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } finally { stream.Close(); } } /// <summary> /// Bitmap转byte[] /// </summary> /// <param name="Bitmap">Bitmap</param> /// <returns></returns> public static byte[] BitmapToBytes(Bitmap Bitmap) { MemoryStream ms = null; try { ms = new MemoryStream(); Bitmap.Save(ms, Bitmap.RawFormat); byte[] byteImage = new Byte[ms.Length]; byteImage = ms.ToArray(); return byteImage; } catch (ArgumentNullException ex) { throw ex; } finally { ms.Close(); } }
相关文章推荐
- iOS NSURLCONNECTION下载进度条
- [物理学与PDEs]第2章第2节 粘性流体力学方程组 2.1 引言
- ajax调用servlet
- ajax调用servlet
- Android开发之获取手机通话记录
- 错误:内存不能为Read的解决方法
- VB控制单片机LED之最简单上位机
- The table xxxx is full处理
- VM下的linux系统上不了网?? 使用putty远程登录不上linux的解决方法?
- (转载)谈谈JS里的{ }大括号和[ ]中括号的用法,理解后就可以看懂JSON结构了。
- 游戏模块化开发的一些思考
- C#类的定义
- dao层和service层的重用
- python产生随机字符串
- 哈希表
- 使用Jconsole监控远程Linux上的JVM
- 求一个字符串当中的最长重复子串
- 大整数运算包
- Android读取本地图片,图片太大导致OOM问题。
- Unity3d截图两种方式