开发者

ASP.net c# Resize Image SQL Upload

开发者 https://www.devze.com 2023-02-16 22:06 出处:网络
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.

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 be开发者_运维百科fore 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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号