空间无限,追求无限...

导航

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

    /// <summary>
    
/// 经过处理获取所略图
    
/// </summary>
    
/// <param name="ms"></param>
    
/// <param name="height"></param>
    
/// <returns></returns>

    private byte[] LessonPicAutoWidth(MemoryStream ms, int height)
    
{
        
byte[] ChagedByte;
        System.Drawing.Image OriginalImage 
= System.Drawing.Image.FromStream(ms, true);
        System.Drawing.Bitmap OriginalPic, NewPic;
        OriginalPic 
= new System.Drawing.Bitmap(OriginalImage);

        
int Width = height * OriginalPic.Width / OriginalPic.Height;

        
if (Width > 280)
        
{
            Width 
= 280;
        }


        NewPic 
= new Bitmap(OriginalPic, Width, height);
        MemoryStream Newms 
= new MemoryStream();
        NewPic.Save(Newms, System.Drawing.Imaging.ImageFormat.Jpeg);
        ChagedByte 
= Newms.GetBuffer();
        OriginalPic.Dispose();
        NewPic.Dispose();
        Newms.Close();

        
return ChagedByte;
    }
    /// <summary>
    
/// 显示图片
    
/// </summary>
    
/// <param name="EmployeeID"></param>

    public void GetPhoto(string EmployeeID, int height)
    
{
        Bitmap bmp;
        
byte[] PhotoByte;
        
string cnstr;
        
string sql;
        cnstr 
= "Data Source=localhost;Database=Northwind;uid=sa;pwd=123";
        sql 
= "Select Photo From Employees Where EmplyeeID=" + EmployeeID;

        
using (SqlConnection cn = new SqlConnection(cnstr))
        
{
            
using (SqlCommand cmd = cn.CreateCommand())
            
{
                cn.Open();
                cmd.CommandText 
= sql;
                
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                
{
                    reader.Read();
                    PhotoByte 
= (byte[])reader.GetValue(0);
                }

            }

        }

        
if (PhotoByte == null || PhotoByte.Length == 0return;

            MemoryStream tempStream = new MemoryStream(PhotoByte);
        PhotoByte 
= LessonPicAutoWidth(tempStream, height);
        bmp 
= new Bitmap(tempStream);

        Response.ContentType 
= "image/gif";
        bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
        Response.End();
    }

posted on 2006-10-18 12:41  笨鸟先飞_淡泊人生  阅读(1187)  评论(0编辑  收藏  举报