ViewState Base64保存图片

        protected System.Drawing.Image image = null;
        protected System.IO.MemoryStream ms = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) 
            {
                try  //初始化 将图片写入隐藏域中
                {
                    string path = Server.MapPath("~/images/tianxia.png");
                    image = System.Drawing.Image.FromFile(path);
                    ms = new System.IO.MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] buffer = ms.ToArray();
                    string str = Convert.ToBase64String(buffer);
                    hiddenImg.Value = str;
                    ms.Dispose();
                }                
                finally
                {
                    if (ms!=null)
                    {
                        ms.Dispose();
                    }
                    if (image!=null)
                    {
                        image.Dispose();
                    }
                }
            }
            else
            {
                try  //PostBack 回发,将编码后的字符从隐藏域中取出进行解码
                {
                    string str = hiddenImg.Value;
                    byte[] buffer = Convert.FromBase64String(str);
                    ms = new System.IO.MemoryStream();
                    ms.Write(buffer, 0, buffer.Length);
                    image = System.Drawing.Image.FromStream(ms);
                    image.Save(Server.MapPath("~/images/1.png"));
                }
                finally
                {
                    if (ms != null)
                    {
                        ms.Dispose();
                    }
                    if (image != null)
                    {
                        image.Dispose();
                    }
                }
            }
        }

 

posted @ 2013-04-23 01:39  TakeTry  阅读(200)  评论(0编辑  收藏  举报