低调的逍遥

仗剑江湖梦已远
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net从数据库中读取图片

Posted on 2007-09-10 16:18  低调的逍遥  阅读(708)  评论(0编辑  收藏  举报
 1    /// <summary>
 2    /// 经过处理获取所略图
 3    /// </summary>
 4    /// <param name="ms"></param>
 5    /// <param name="height"></param>
 6    /// <returns></returns>

 7    private byte[] LessonPicAutoWidth(MemoryStream ms, int height)
 8    {
 9        byte[] ChagedByte;
10        System.Drawing.Image OriginalImage = System.Drawing.Image.FromStream(ms, true);
11        System.Drawing.Bitmap OriginalPic, NewPic;
12        OriginalPic = new System.Drawing.Bitmap(OriginalImage);
13        int Width = height * OriginalPic.Width / OriginalPic.Height;
14
15        if (Width > 280)
16        {
17            Width = 280;
18        }

19        NewPic = new Bitmap(OriginalPic, Width, height);
20        MemoryStream Newms = new MemoryStream();
21        NewPic.Save(Newms, System.Drawing.Imaging.ImageFormat.Jpeg);
22        ChagedByte = Newms.GetBuffer();
23        OriginalPic.Dispose();
24        NewPic.Dispose();
25        Newms.Close();
26        return ChagedByte;
27    }
    
28
29    /// <summary>
30    /// 显示图片
31    /// </summary>
32    /// <param name="EmployeeID"></param>

33    public void GetPhoto(string EmployeeID, int height)
34    {
35        Bitmap bmp;
36        byte[] PhotoByte;
37        string cnstr;
38        string sql;
39        cnstr = "Data Source=localhost;Database=Northwind;uid=sa;pwd=123";
40        sql = "Select Photo From Employees Where EmplyeeID=" + EmployeeID;
41        using (SqlConnection cn = new SqlConnection(cnstr))
42        {
43            using (SqlCommand cmd = cn.CreateCommand())
44            {
45                cn.Open();
46                cmd.CommandText = sql;
47                using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
48                {
49                    reader.Read();
50                    PhotoByte = (byte[])reader.GetValue(0);
51                }

52            }

53        }

54        if (PhotoByte == null || PhotoByte.Length == 0return;
55        MemoryStream tempStream = new MemoryStream(PhotoByte);
56        PhotoByte = LessonPicAutoWidth(tempStream, height);
57        bmp = new Bitmap(tempStream);
58        Response.ContentType = "image/gif";
59        bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
60        Response.End();
61    }