2010-03-18 78 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

相关问题