首页 文章

如何裁剪或调整图像大小以在asp.net中设置宽高比

提问于
浏览
1

我的网络表单中有一个图像控件 . 我将其宽度设置为100px,高度为100px . 但如果有人上传比例为100 * 120的图像 . 我想要裁剪或调整大小并设置100 * 100.我试图设置最大宽度但不起作用,我尝试使用代码的位图方法

protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        string filename = FileUpload1.FileName;
        string directory = Server.MapPath("~/");
        Bitmap originalBMP = new Bitmap(FileUpload1.FileContent);
        float origWidth = originalBMP.Width;
        float origHeight = originalBMP.Height;
        float sngRatio = origWidth / origHeight;
        float newWidth = 100;
        float newHeight = newWidth / sngRatio;
        Bitmap newBMP = new Bitmap(originalBMP,Convert.ToInt32(newWidth),Convert.ToInt32(newHeight));
        Graphics oGraphics = Graphics.FromImage(newBMP);
        oGraphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        oGraphics.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
        newBMP.Save(directory + filename);
        originalBMP = null;
        newBMP = null;
        oGraphics = null;
        Label1.Text = "File <b style='color: red;'>" + filename + "&lt;</b> uploaded.";
        Image1.ImageUrl = @"~/" + filename;
    }
    else
    {
        Label1.Text = "No file uploaded!";
    }
}

它工作但它保存调整后的图像我想要将原始图像保存在目录中并在图像控件中显示调整大小的图像 .

1 回答

  • 1

    在codeplex上查看Web Image Resize处理程序:http://webimageresizer.codeplex.com/

    它是处理图像的自定义处理程序 .

    Sample urls 取自codeplex项目的主页

    //返回映射到/bla.jpg的图像,其大小调整为宽度为100像素,保留相对于高度的方面/ImageHandler.ashx?src=/bla.jpg&width=100

    //返回映射到/bla.jpg的图像,调整大小为100像素的高度,保留相对于宽度的方面/ImageHandler.ashx?src=/bla.jpg&height=100

    //返回映射到/bla.jpg的图像,其大小调整为宽度为100像素,高度为50像素/ImageHandler.ashx?src=/bla.jpg&width=100&height=50

    Another option is to use http://imageresizing.net/

    好处是它注册了一个处理程序来透明地处理图像,这意味着你只需要在原始图像url中添加查询字符串变量来操作图像 .

    Sample urls

    /images/bla.jpg?h=100&w=100

相关问题