Reza Paidar
Reza Paidar

Reputation: 883

How to resize an image after upload it in ASP.net using c#?

I try to upload an image and save it on my host then immediately resize it and save the new image to another place on my host. here is my code:


---------------btnStart()-----------------

    //1-get web path
    string path = Server.MapPath("..") + "\\images\\";
    string thumbPath = Server.MapPath("..") + "\\thumbnails\\";
    path += folder;
    thumbPath += folder;
    //2-get and check file extension
    String[] validext = { ".jpg", ".png" };
    string ext = System.IO.Path.GetExtension(UploadPicture.PostedFile.FileName);
    if (Array.IndexOf(validext, ext.ToLower()) < 0)
    {
        lblMessage.Text ="this file is not allowed";
        return;
    }
    //3-get and check file size
    long size = UploadPicture.PostedFile.ContentLength;
    size = size / 1024;
    if (size > 1300)
    {
        lblMessage.Text ="incorrect size";
        return;
    }
    //4-get file name
    string filename = System.IO.Path.GetFileName(UploadPicture.PostedFile.FileName);
    lblFileName.Text = filename;
    //5-check file exist and if (true) generate new name
    while (System.IO.File.Exists(path + "\\" + filename))
    filename = "1" + filename;

    //6-save file to server
    UploadPicture.PostedFile.SaveAs(path + filename);
    changeImageSize cis = new changeImageSize();
    Bitmap bm = new Bitmap(path + filename);


-----------end event--------------------
-----------changeImageSize class--------

public class changeImageSize
{
public changeImageSize() { }
/// <summary>
/// Method to resize, convert and save the image.
/// </summary>
/// <param name="image">Bitmap image.</param>
/// <param name="maxWidth">resize width.</param>
/// <param name="maxHeight">resize height.</param>
/// <param name="quality">quality setting value.</param>
/// <param name="filePath">file path.</param>      
public void Save(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath)
{
    // Get the image's original width and height
    int originalWidth = image.Width;
    int originalHeight = image.Height;

    // To preserve the aspect ratio
    float ratioX = (float)maxWidth / (float)originalWidth;
    float ratioY = (float)maxHeight / (float)originalHeight;
    float ratio = Math.Min(ratioX, ratioY);

    // New width and height based on aspect ratio
    int newWidth = (int)(originalWidth * ratio);
    int newHeight = (int)(originalHeight * ratio);

    // Convert other formats (including CMYK) to RGB.
    Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);

    // Draws the image in the specified size with quality mode set to HighQuality
    using (Graphics graphics = Graphics.FromImage(newImage))
    {
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);
    }

    // Get an ImageCodecInfo object that represents the JPEG codec.
    ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);

    // Create an Encoder object for the Quality parameter.
    Encoder encoder = Encoder.Quality;

    // Create an EncoderParameters object. 
    EncoderParameters encoderParameters = new EncoderParameters(1);

    // Save the image as a JPEG file with quality level.
    EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
    encoderParameters.Param[0] = encoderParameter;
    newImage.Save(filePath, imageCodecInfo, encoderParameters);
}

/// <summary>
/// Method to get encoder infor for given image format.
/// </summary>
/// <param name="format">Image format</param>
/// <returns>image codec info.</returns>
private ImageCodecInfo GetEncoderInfo(ImageFormat format)
{
    return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
}
}


-----------end class--------------------

as you see on btnStart() event code , i want after uploading an image, make an copy with new size and save it to another folder(thumbnail).
but I get an error as bellow :

error scence

Upvotes: 0

Views: 1270

Answers (2)

Reza zarif
Reza zarif

Reputation: 11

I think It's because of saving folder on host, you must grant writing permission to saving path on your host. your code can't save image in host

Upvotes: 1

Wallstrider
Wallstrider

Reputation: 856

Your code works well. Just check following:

1) Your image is not corrupted.

2) Try to specify different quality levels 25, 50, 75.

3) maxWidth, maxHeight you specified cannot be used in this case.

4) Check your file paths.

Edit:

I set quality level to 75 for 1920x1080 image, and tried to set maxWidth and maxHeight to 800x600, 320x240. It works well.

        ChangeImageSize cis = new ChangeImageSize();
        Bitmap b = new Bitmap(@"C:\Users\Alex Len Paul\Desktop\1\1920x1080.jpg");
        cis.Save(b, 320, 240, 75, @"C:\Users\Alex Len Paul\Desktop\1\1920x1080_2.jpg");

Upvotes: 1

Related Questions