Ryan
Ryan

Reputation: 18109

Resizing Images with ASP.NET and saving to Database

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!

Upvotes: 1

Views: 3685

Answers (3)

Lilith River
Lilith River

Reputation: 16468

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.

Upvotes: 3

jjxtra
jjxtra

Reputation: 21120

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.

Upvotes: 1

Aaron
Aaron

Reputation: 7541

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

Upvotes: 0

Related Questions