Search code examples
c#sqlasp.net-mvc-2image-scalingimageresizer

Image Resizing from SQL Database on the fly with MVC2


I have a simple MVC2 app that uploads a file from the browser to an MS SQL database as an Image blob.

Then I can return the results with something like:

        public FileContentResult ShowPhoto(int id)
        {
           TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
           tempImageUpload = _service.GetImageData(id) ?? null;
           if (tempImageUpload != null)
           {
              byte[] byteArray = tempImageUpload.TempImageData;
              return new FileContentResult (temp, "image/jpeg");
           }
           return null;
        }

But I want to return these images resized as both thumbnails and as a gallery-sized view. Is this possible to do within this Result? I've been playing around with the great imageresizer.net but it seems to want to store the images on my server which I want to avoid. Is it possible to do this on the fly..?

I need to keep the original file and don't, if possible, want to store the images as files on the server.

Thanks for any pointers!


Solution

  • ImageResizer.NET allows you to pass a stream to it for resizing, see Managed API usage

    The method you'd use is:

    ImageResizer.ImageBuilder.Current.Build(object source, object dest, ResizeSettings settings)

    I modified your method to go about it this way, but it is untested. Hope it helps.

    public FileContentResult ShowPhoto(int id)
        {
           TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
           tempImageUpload = _service.GetImageData(id) ?? null;
           if (tempImageUpload != null)
           {
              byte[] byteArray = tempImageUpload.TempImageData;
              using(var outStream = new MemoryStream()){
                  using(var inStream = new MemoryStream(byteArray)){
                      var settings = new ResizeSettings("maxwidth=200&maxheight=200");
                      ImageResizer.ImageBuilder.Current.Build(inStream, outStream, settings);
                      var outBytes = outStream.ToArray();
                      return new FileContentResult (outBytes, "image/jpeg");
                  }
              }
           }
           return null;
        }