C#中如何調整圖像大小


在本篇文章中,我將介紹如何在C#中來調整你想要的圖像大小。要實現這一目標,我們可以采取以下幾個步驟:

1.首先要獲取你想要調整大小的圖像:

string path = Server.MapPath("~/Images");
System.Drawing.Image img = System.Drawing.Image.FromFile(string.Concat(path,"/3904.jpg"));

2.將圖像轉換為Bitmap:

Bitmap b = new Bitmap(img);

3.創建一個調整圖像大小的方法:

private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
    //獲取圖片寬度
    int sourceWidth = imgToResize.Width;
    //獲取圖片高度
    int sourceHeight = imgToResize.Height;
 
    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;
    //計算寬度的縮放比例
    nPercentW = ((float)size.Width / (float)sourceWidth);
    //計算高度的縮放比例
    nPercentH = ((float)size.Height / (float)sourceHeight);       
 
    if (nPercentH < nPercentW)
        nPercent = nPercentH;
    else
     nPercent = nPercentW;
     //期望的寬度
     int destWidth = (int)(sourceWidth * nPercent);
     //期望的高度
     int destHeight = (int)(sourceHeight * nPercent);
 
     Bitmap b = new Bitmap(destWidth, destHeight);
     Graphics g = Graphics.FromImage((System.Drawing.Image)b);
     g.InterpolationMode = InterpolationMode.HighQualityBicubic;
     //繪制圖像
     g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
     g.Dispose();
     return (System.Drawing.Image)b;
}

 在上面的方法中,我們獲取了位圖圖像,然后繪制了不同尺寸的圖像(這里繪制出的圖像是基於指定的縱橫比)

4.調用上述方法,得到調整大小之后的圖片:

System.Drawing. Image i = resizeImage(b, new Size(100, 100));

 輸出結果:

謝謝瀏覽,希望對你有所幫助。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM