天道酬勤,厚德载物

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1.数据库设计
字段              类型
PhotoID          int
AlbumID         int
Caption           nvarchar(50)
BytesOriginal   image
BytesFull         image
BytesPoster     image
BytesThumb    image

2.前台显示图片

<img src="Handler.ashx?AlbumID=<%# Eval("AlbumID") %>&Size=M" class="photo_198" style="border:4px solid white" alt='示例照片,相册编号 <%Eval("AlbumID"%>' />


3.Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.IO;
using System.Web;

public class Handler : IHttpHandler {

    
public bool IsReusable {
        
get {
            
return true;
        }

    }

    
    
public void ProcessRequest (HttpContext context) {
        
// 设置响应设置
        context.Response.ContentType = "image/jpeg";
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.BufferOutput 
= false;
        
// 设置 Size 参数
        PhotoSize size;
        
switch (context.Request.QueryString["Size"]) {
            
case "S":
                size 
= PhotoSize.Small;
                
break;
            
case "M":
                size 
= PhotoSize.Medium;
                
break;
            
case "L":
                size 
= PhotoSize.Large;
                
break;
            
default:
                size 
= PhotoSize.Original;
                
break;
        }
 
        
// 设置 PhotoID 参数
        Int32 id = -1;
        Stream stream 
= null;
        
if (context.Request.QueryString["PhotoID"!= null && context.Request.QueryString["PhotoID"!= ""{
            id 
= Convert.ToInt32(context.Request.QueryString["PhotoID"]);
            stream 
= PhotoManager.GetPhoto(id, size);
        }
 else {
            id 
= Convert.ToInt32(context.Request.QueryString["AlbumID"]);
            stream 
= PhotoManager.GetFirstPhoto(id, size);
        }

        
// 从数据库获取照片,如果未返回照片,将获取默认的“placeholder”照片
        if (stream == null) stream = PhotoManager.GetPhoto(size);
        
// 将图像流写入响应流中
        const int buffersize = 1024 * 16;
        
byte[] buffer = new byte[buffersize];
        
int count = stream.Read(buffer, 0, buffersize);
        
while (count > 0{
            context.Response.OutputStream.Write(buffer, 
0, count);
            count 
= stream.Read(buffer, 0, buffersize);
        }

    }


}

 


4.业务层类(PhotoManager 部分内容)

    public static List<Photo> GetPhotos(int AlbumID) {
        
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString)) {
            
using (SqlCommand command = new SqlCommand("GetPhotos", connection)) {
                command.CommandType 
= CommandType.StoredProcedure;
                command.Parameters.Add(
new SqlParameter("@AlbumID", AlbumID));
                
bool filter = !(HttpContext.Current.User.IsInRole("Friends"|| HttpContext.Current.User.IsInRole("Administrators"));
                command.Parameters.Add(
new SqlParameter("@IsPublic", filter));
                connection.Open();
                List
<Photo> list = new List<Photo>();
                
using (SqlDataReader reader = command.ExecuteReader()) {
                    
while (reader.Read()) {
                        Photo temp 
= new Photo(
                            (
int)reader["PhotoID"],
                            (
int)reader["AlbumID"],
                            (
string)reader["Caption"]);
                        list.Add(temp);
                    }

                }

                
return list;
            }

        }



    }

 

    // Helper 函数

    
private static byte[] ResizeImageFile(byte[] imageFile, int targetSize) {
        
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) {
            Size newSize 
= CalculateDimensions(oldImage.Size, targetSize);
            
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb)) {
                
using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode 
= SmoothingMode.AntiAlias;
                    canvas.InterpolationMode 
= InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode 
= PixelOffsetMode.HighQuality;
                    canvas.DrawImage(oldImage, 
new Rectangle(new Point(00), newSize));
                    MemoryStream m 
= new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    
return m.GetBuffer();
                }

            }

        }

    }


    
private static Size CalculateDimensions(Size oldSize, int targetSize) {
        Size newSize 
= new Size();
        
if (oldSize.Height > oldSize.Width) {
            newSize.Width 
= (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
            newSize.Height 
= targetSize;
        }
 else {
            newSize.Width 
= targetSize;
            newSize.Height 
= (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
        }

        
return newSize;
    }


    
public static ICollection ListUploadDirectory() {
        DirectoryInfo d 
= new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/Upload"));
        
return d.GetFileSystemInfos("*.jpg");
    }


}


5.批量上传操作

    protected void Button1_Click(object sender, ImageClickEventArgs e) {
        DirectoryInfo d 
= new DirectoryInfo(Server.MapPath("~/Upload"));
        
foreach (FileInfo f in d.GetFiles("*.jpg")) {
            
byte[] buffer = new byte[f.OpenRead().Length];
            f.OpenRead().Read(buffer, 
0, (int)f.OpenRead().Length);
            PhotoManager.AddPhoto(Convert.ToInt32(Request.QueryString[
"AlbumID"]), f.Name, buffer);
        }

        GridView1.DataBind();
    }


 6.上传控件
.net2.0 专门有一个上传服务器控件

<asp:FileUpload ID="PhotoFile" Runat="server" Width="416" FileBytes='<%# Bind("BytesOriginal") %>' CssClass="textfield" /><br />
posted on 2006-09-06 22:19  cobbles  阅读(239)  评论(0编辑  收藏  举报