1

I have been looking all over for a way to resize an image before it is uploaded to my database. Right now the files are just upload and if they are not the correct size then my pages look like a mess. How would I resize the image before I upload it to my database, I would like to upload an original sized image, and correct size. Is this possible with ASP.net. I have seen some tutorials on image resizing but none of them were helpful, if anyone can help that would be great. I started looking at this tutorial but wasnt able to implement it in my SQL upload.

Thanks

2
  • could you share code of what you have tried so far? Commented Mar 14, 2011 at 15:47
  • Use the imageresizing.net library for the best image quality and for correct memory managememt. Using (MemoryStream ms = new MemoryStream()){ ImageBuilder.Current.Build(postedFile, ms, new ResizeSettings("maxwidth=800&maxheight=600&format=jpg"); return ms.ToArray();} Commented Aug 31, 2011 at 18:10

1 Answer 1

2

Something like this, I am using MVC thus the HttpPostedFileBase. However this is taking the input of a file input type and returning a byte array, perfect for uploading to DB.

using System.Drawing;
using System.Drawing.Drawing2D;

private static byte[] PrepImageForUpload(HttpPostedFileBase FileData)
{
    using (Bitmap origImage = new Bitmap(FileData.InputStream))
    {
        int maxWidth = 165;

        int newWidth = origImage.Width;
        int newHeight = origImage.Height;          
        if (origImage.Width < newWidth) //Force to max width
        {
            newWidth = maxWidth;
            newHeight = origImage.Height * maxWidth / origImage.Width;   
        }

        using (Bitmap newImage = new Bitmap(newWidth, newHeight))
        {
            using (Graphics gr = Graphics.FromImage(newImage))
            {
                gr.SmoothingMode = SmoothingMode.AntiAlias;
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.DrawImage(origImage, new Rectangle(0, 0, newWidth, newHeight));

                MemoryStream ms = new MemoryStream();
                newImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.