簡體   English   中英

如何裁剪或調整圖像大小以在asp.net中設置縱橫比

[英]How to crop or resize Image to set aspect ratio in asp.net

我的網絡表單中有一個圖像控件。 我將其寬度設置為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!";
    }
}

它可以工作,但是將調整大小后的圖像保存在目錄中我想將原始圖像保存在目錄中,並在圖像控件中顯示調整后的圖像。

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

它是處理圖像的自定義處理程序。

從Codeplex項目主頁獲取的 示例URL

//返回圖像映射到/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

另一種選擇是使用http://imageresizing.net/

好處是它注冊了一個處理程序來透明地處理圖像,這意味着您只需將querystring變量添加到原始圖像url即可操作圖像。

樣本網址

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM