2010-03-18 81 views
1

我需要拍攝上傳的圖像,調整大小並將其保存到數據庫。很簡單,除非我無法將任何臨時文件保存到服務器。我正在拍攝圖像,將其調整爲位圖大小,並且需要將其作爲原始圖像類型(例如JPG)保存到數據庫字段中。我怎樣才能得到這樣的FileBytes(),所以我可以將它保存到數據庫?使用ASP.NET調整圖像大小並保存到數據庫

在我使用ImageUpload.FileBytes()之前,但現在我正在調整大小,我正在處理圖像和位圖而不是FileUpload,並且找不到任何能夠給我的字節。

謝謝!

回答

0

這是我所做的調整圖像大小。

private byte[] toBytes(Image image) 
    {    
     Bitmap resized = new Bitmap(image, yourWidth, yourHeight);    
     System.IO.MemoryStream ms = new System.IO.MemoryStream();    
     resized.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
     resized.Dispose(); 
     return ms.ToArray();    
    } 
3

其實並不那麼簡單......有28 non-obvious pitfalls you should watch out for when doing image resizing。最好使用我的free, open-source library to handle all the encoding issues and avoid the GDI bugs.

下面是如何在調整大小,裁剪和轉換爲Jpeg格式之後,爲每個上傳的文件獲取編碼的byte []數組。

using ImageResizer; 
using ImageResizer.Encoding; 


//Loop through each uploaded file 
foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { 
    HttpPostedFile file = HttpContext.Current.Request.Files[fileKey]; 

    //You can specify any of 30 commands.. See http://imageresizing.net 
    ResizeSettings resizeCropSettings = 
     new ResizeSettings("width=200&height=200&format=jpg&crop=auto"); 

    using (MemoryStream ms = new MemoryStream()) { 
     //Resize the image 
     ImageBuilder.Current.Build(file, ms, resizeCropSettings); 

     //Upload the byte array to SQL: ms.ToArray(); 
    } 
} 

使用MS SQL存儲圖像也是一個壞主意。有關更多信息,請參閱我的podcast with Scott Hanselman

相關問題