【问题标题】:Resizing Images with ASP.NET and saving to Database使用 ASP.NET 调整图像大小并保存到数据库
【发布时间】:2011-01-29 05:24:36
【问题描述】:

我需要拍摄一张上传的图片,调整它的大小,然后将其保存到数据库中。很简单,除了我无权将任何临时文件保存到服务器。我正在拍摄图像,将其大小调整为位图,并且需要将其作为原始图像类型(例如 JPG)保存到数据库字段中。我怎样才能得到这样的 FileBytes(),以便将其保存到数据库中?

在我使用 ImageUpload.FileBytes() 之前,但现在我正在调整大小,我正在处理图像和位图而不是 FileUploads,并且似乎找不到任何可以给我字节的东西。

谢谢!

【问题讨论】:

    标签: asp.net image image-processing bitmap


    【解决方案1】:

    其实没那么简单……有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 了解更多信息。

    【讨论】:

      【解决方案2】:

      请参阅Resizing an Image without losing any quality 然后您可以将图像 (Bitmap.SaveToStream) 写入 MemoryStream 并调用 ToArray 以获取字节。

      【讨论】:

        【解决方案3】:

        这是我为调整图像大小所做的。

            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();            
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-24
          • 2013-05-09
          • 1970-01-01
          • 1970-01-01
          • 2021-11-26
          • 2011-05-17
          相关资源
          最近更新 更多