1

I need to take an uploaded image, resize it, and save it to the database. Simple enough, except I don't have access to save any temp files to the server. I'm taking the image, resizing it as a Bitmap, and need to save it to a database field as the original image type (JPG for example). How can I get the FileBytes() like this, so I can save it to the database?

Before I was using ImageUpload.FileBytes() but now that I'm resizing I'm dealing with Images and Bitmaps instead of FileUploads and can't seem find anything that will give me the bytes.

Thanks!

Ryan
  • 17,511
  • 23
  • 63
  • 88

3 Answers3

3

It's actually not so simple... there are 28 non-obvious pitfalls you should watch out for when doing image resizing. It's best to use my free, open-source library to handle all the encoding issues and avoid the GDI bugs.

Here's how to get an encoded byte[] array for each uploaded file, after resizing, cropping, and converting to Jpeg format.

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

It's also a bad idea to use MS SQL for storing images. See my podcast with Scott Hanselman for more info.

Lilith River
  • 16,204
  • 2
  • 44
  • 76
1

See Resizing an Image without losing any quality You can then write your image (Bitmap.SaveToStream) to a MemoryStream and call ToArray to get the bytes.

Community
  • 1
  • 1
jjxtra
  • 20,415
  • 16
  • 100
  • 140
0

This is what I've done to resize images.

    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();            
    }
Aaron
  • 7,431
  • 12
  • 35
  • 37