BeetleDev.com
info
contact
Saturday, December 15, 2018
Beetle Blog
Upload and Image and Restrict File Size
By: douglas - C# - 5/22/2008 3:56:27 AM

This code uploads an image to the server file system.  If the image is wider than a certain width it resizes the image.  The image is saved as a jpg.

 

        // Upload image
        // Make sure to create directory if needed.
        string savePath = Server.MapPath("~/UploadFolder/");

        // Create Directory if it doesn't exist
        if (!System.IO.Directory.Exists(savePath))
        {
            System.IO.Directory.CreateDirectory(savePath);
        }


        // Declare some image variables
        System.Drawing.Image imgOriginal;  // Will hold the original image
        System.Drawing.Image imgNew;  // Will hold the new image
        double targetWidth = 100; // Default target width for new image
        double targetHeight = 100; // Default target height for new image

        // Get new width from config
        try
        {
            targetWidth = Convert.ToDouble(ConfigurationManager.AppSettings["MaxImageWidth"]);
        }
        catch
        {
            targetWidth = 100;
        }

        //Create a new Image using the uploaded picture as a Stream
        imgOriginal = Bitmap.FromStream(ImageUpload.PostedFile.InputStream);

        // Work out a proportionate height from width
        if ((double)imgOriginal.Width < targetWidth)
        {
            targetWidth = (double)imgOriginal.Width;
            targetHeight = (double)imgOriginal.Height;
        }
        else
        {
            targetHeight = (double)imgOriginal.Height / ((double)imgOriginal.Width / targetWidth);
        }

        // Now create the new image
        imgNew = new Bitmap(imgOriginal, (int)targetWidth, (int)targetHeight);

        // Save it to the file system as a jpg.
        imgNew.Save(savePath + "\\" + pAdID.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
 


Last Modified: 5/22/2008 3:57:29 AM

Beetle Blog v0.2.2


Copyright © 1997 - 2018 BeetleDev.com. All rights reserved.