解决方案 »

  1.   


    /******************************************
    -- Author       : Coder.Yan
    -- Create date  : 2011-11-24 13:25:24
    -- CopyRight    : HZST (C) 2011
    -- Description  : 图像转换类
     ******************************************/
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;namespace SVG4Net
    {
        public class ImageConvert
        {
            /// <summary>
            /// 将图片转换为Base64格式字符串
            /// </summary>
            /// <param name="img"></param>
            /// <returns></returns>
            public static string ToBase64String(Image img)
            {
                return ToBase64String(img, ImageFormat.Png);
            }        public static string ToBase64String(Image img,ImageFormat format)
            {
                if (img != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        img.Save(ms, format);
                        byte[] buffer = ms.ToArray();
                        return Convert.ToBase64String(buffer);
                    }
                }
                return string.Empty;
            }        public static string ToBase64HtmlString(Image img)
            {
                return ToBase64HtmlString(img, ImageFormat.Png);
            }        public static string ToBase64HtmlString(Image img, ImageFormat format)
            {
                string type = "jpeg";
                if (format.Guid == ImageFormat.Png.Guid)
                {
                    type = "png";
                }
                else if (format.Guid == ImageFormat.Gif.Guid)
                {
                    type = "gif";
                }
                return string.Format("data:image/{0};base64,", type) + ToBase64String(img, format);
            }        public static Image FromBase64String(string base64Str)
            {
                Bitmap bitmap = null;
                Image img = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] buffer = Convert.FromBase64String(base64Str);
                    ms.Write(buffer, 0, buffer.Length);
                    try
                    {
                        img = Image.FromStream(ms);
                        if (img != null)
                        {
                            bitmap = new Bitmap(img.Width,img.Height);
                            using (Graphics g = Graphics.FromImage(bitmap))
                            {
                                g.DrawImage(img,new Rectangle(0,0,bitmap.Width,bitmap.Height));
                            }
                        }
                    }
                    catch { }
                }
                return bitmap;
            }        public static Image FromBase64HtmlString(string str)
            {
                string[] strs = str.Split(',');
                if (strs.Length > 0)
                {
                    return FromBase64String(strs[strs.Length - 1]);
                }
                else
                {
                    return FromBase64String(str);
                }
            }
        }
    }
      

  2.   

    我给你写了个小例子,我也是刚学C#,没啥经验,希望一起讨论;
    我自己试了一下,能将一个jpg图片转成stream,再保存到硬盘上。
            static void Main(string[] args)
            {           
                string picPath = @"D:\download\Pic.jpg";//Origin picture path as jpg
                string destPath = @"D:\download\Pic2.bmp";//Destination picture as bmp(or any type u like)
                Image img = Image.FromFile(picPath);//load origin picture
                File.Create(destPath);//create dest picture as path u want
                using(MemoryStream memStream=new MemoryStream())//create a instance of memorystream
                {
                    img.Save(memStream, ImageFormat.Bmp);//save stream from origin pic as format bmp
                    Bitmap destBmp = new Bitmap(memStream);//create bmp instance from stream above
                    destBmp.Save(destPath);//save bmp to the path you want
                }
                Console.WriteLine("**********Done**************");
                Console.ReadKey();
            }
      

  3.   

    ms.Write(by, 0, by.Length);
    ms.Position = 0;  // 加入这行试试
    Image bi = Image.FromStream(ms);
      

  4.   

    MemoryStream st = new MemoryStream();
                            Image img = c.GetType().GetProperty("Image").GetValue(c, null) as Image;
                            img.Save(st, System.Drawing.Imaging.ImageFormat.Jpeg);
                            byte[] by = st.ToArray();
                            string text = Convert.ToBase64String(by);
    按照1楼的说法,改成st.ToArray(),就可以了
      

  5.   

    以二进制流形式存储图片到数据库示例
    protected void imgbtnCreate_Click(object sender, ImageClickEventArgs e)
        {
            
            string PerHomeName=tbPerHomeName.Text;//获取空间名
           
            string PerHomeSign=txtPerSign.Text; //获取个性签名
            
            string imgPath = uploadFile.PostedFile.FileName;//获取文件件名
            
            string lastName = imgPath.Substring(imgPath.LastIndexOf(".") + 1);//获取文件上传后缀名
            SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["conStr"]);
            conn.Open();
            if (uploadFile.PostedFile.FileName != "" && lastName.ToLower() == "jpg" || lastName.ToLower() == "gif")
            {
                if (uploadFile.PostedFile.ContentLength > 40960)
                {
                    Response.Write("<script language='javaScript'>alert('你上传的图片超过了40KB!')</script>");
                    return;
                }
                int imgLength = uploadFile.PostedFile.ContentLength;//获取上传文件大小
                Byte[] imageData = new Byte[imgLength]; //定义Byte数组
                HttpPostedFile hp = uploadFile.PostedFile;//创建访问客户端上传文件的对象
                Stream imagestream = hp.InputStream;//创建数据流对象
                //将图片数据放到image数据对象实例中,其中0代表数组指针的起始位置,imagelength表示要读取流的长度
                imagestream.Read(imageData, 0, imgLength);
                string sqlstr = "insert into PerHomeDetail(PerHomeName,PerHomeSign,PerHomeLogo)values('" + PerHomeName + "','" + PerHomeSign + "',@ImageData)";
                SqlCommand comm = new SqlCommand(sqlstr, conn);
                comm.Parameters.Add("@ImageData", SqlDbType.Image);
                comm.Parameters["@ImageData"].Value = imageData;
                comm.ExecuteNonQuery();
                conn.Close();
                Response.Write("<Script>alert('个人空间创建成功!')</Script>");
            }
            else
            {
                Response.Write("<script>alert('上传头像不能为空,且格式必须为gif或jpg!');location='javascript:history.go(-1)'</script>");
            }
        }
    //读取数据库中流形式保存的图片
    protected void Page_Load(object sender, EventArgs e)
        {
            string requestID = Request.QueryString["id"];//获取Default.aspx页面传过来的id值
            SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["conStr"]);
            string strsql = "select * from [PerHomeDetail] where PerHomeId=" + requestID;
            SqlCommand comm = new SqlCommand(strsql, conn);//创建命令对象 
            conn.Open();
            SqlDataReader dr = comm.ExecuteReader();//创建数据阅读器
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    byte[] imageData = (byte[])dr["PerHomeLogo"];
                    Response.BinaryWrite(imageData);//输出二进制流形式的图片
                }
            }
            dr.Close();
            conn.Close();
        }