本文提供一個功能完整的相簿管理類別 PhotoManager,涵蓋相片與相簿的增刪改查、權限控管、縮圖產生、批次上傳等核心功能,採用預存程序存取資料庫,並整合 ASP.NET 角色機制進行公開/私有權限過濾。
ResizeImageFile 依指定尺寸等比縮放,支援高品質插值模式。ListUploadDirectory 列出上傳資料夾所有 JPG 檔案。public class PhotoManager
{
public static string ConnString = "server=****;database=****; uid=sa; pwd=****; pooling=true";
// 取得相片串流(含權限過濾)
public static Stream GetPhoto(int photoid, PhotoSize size) { ... }
public static Stream GetPhoto(PhotoSize size) { ... } // 預設佔位圖
public static Stream GetFirstPhoto(int albumid, PhotoSize size) { ... }
// 取得相簿內所有相片
public static List<Photo> GetPhotos(int AlbumID) { ... }
public static List<Photo> GetPhotos() { ... } // 隨機相簿
// 相片 CRUD
public static void AddPhoto(int AlbumID, string Caption, byte[] BytesOriginal) { ... }
public static void RemovePhoto(int PhotoID) { ... }
public static void EditPhoto(string Caption, int PhotoID) { ... }
// 相簿 CRUD
public static List<Album> GetAlbums() { ... }
public static void AddAlbum(string Caption, bool IsPublic) { ... }
public static void RemoveAlbum(int AlbumID) { ... }
public static void EditAlbum(string Caption, bool IsPublic, int AlbumID) { ... }
// 輔助方法
private static byte[] ResizeImageFile(byte[] imageFile, int targetSize) { ... }
private static Size CalculateDimensions(Size oldSize, int targetSize) { ... }
public static ICollection ListUploadDirectory() { ... }
}
程式碼中大量使用 using 區塊確保 SqlConnection、SqlCommand、SqlDataReader、Graphics 等非受控資源正確釋放,並透過 HttpContext.Current.User.IsInRole 實作角色基礎的存取控制。