如何在使用c#在ASP.net上传图像后调整图像大小?

时间:2014-12-14 15:01:56

标签: c# asp.net gdi+

我尝试上传图片并将其保存在我的主机上,然后立即调整大小并将新图像保存到主机上的其他位置。这是我的代码:

  


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


-----------结束事件--------------------
  ----------- changeImageSize类--------

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


-----------结束班--------------------

正如您在btnStart()事件代码中看到的那样,我希望在上传图像后,制作一个新尺寸的副本并将其保存到另一个文件夹(缩略图)。
但我收到的错误如下:

error scence

2 个答案:

答案 0 :(得分:1)

您的代码效果很好。请检查以下内容:

1)您的图片没有损坏。

2)尝试指定不同的质量等级25,50,75。

3)你指定的maxWidth,maxHeight在这种情况下不能使用。

4)检查文件路径。

编辑:

我将1920x1080图像的质量等级设置为75,并尝试将maxWidth和maxHeight设置为800x600,320x240。效果很好。

        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");

答案 1 :(得分:1)

我认为这是因为在主机上保存文件夹,您必须授予写入权限以保存主机上的路径。您的代码无法在主机中保存图像