分享

图片转化为二进制

 若生安饶 2011-05-06
//把指定路径的图片转化为二进制
073     public byte[] GetPictureData(string imagepath)
074     {
075         //根据图片文件的路径使用文件流打开,并保存为byte[]
076         FileStream fs = new FileStream(imagepath, FileMode.Open);
077         byte[] byData = new byte[fs.Length];
078         fs.Read(byData, 0, byData.Length);
079         fs.Close();
080         return byData;
081     }
082     //把上传图片转化为二进制
083     protected string btnAdd_Click(object sender, EventArgs e)//上传单击按钮
084     {
085         //获得图象并把图象转换为byte[] 
086         HttpPostedFile upPhoto = UpPhoto.PostedFile;
087         int upPhotoLength = upPhoto.ContentLength;
088         byte[] PhotoArray = new Byte[upPhotoLength];
089         Stream PhotoStream = upPhoto.InputStream;
090         PhotoStream.Read(PhotoArray, 0, upPhotoLength);
091         return  Encoding.UTF8.GetString(PhotoArray);
092     }   
093     //把图片显示在页面上
094     //ContentType的类型可为1.application/octet-stream,2.image/JPEG等
095     HttpContext.Current.Response.ContentType = "application/octet-stream"
096     HttpContext.Current.Response.BinaryWrite(PhotoArray);
097       
098     //把二进制转化为图像
099     public System.Drawing.Image ReturnPhoto(byte[] streamByte){
100         System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
101         System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
102         return img;
103     }
104       
105     //直接把图片转化为二进制
106         public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto){
107            //将Image转换成流数据,并保存为byte[]
108            MemoryStream mstream = new MemoryStream();
109            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
110            byte[] byData = new Byte[mstream.Length];
111            mstream.Position = 0;
112             mstream.Read(byData, 0, byData.Length);
113            mstream.Close();
114             return byData;
115         }
116       
117
118     //字符串和二进制相互转化.
119       
120     //把字符串转化为二进制.
121     public static byte[] StringToByteArray(string str)
122     {        return Encoding.UTF8.GetBytes(str);    }
123     //把二进制转化为字符串
124     public static string ByteArrayToString(byte[] bytes)
125     {        return Encoding.UTF8.GetString(bytes);    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多