ASP.NET中高品質縮圖的產生代碼

來源:互聯網
上載者:User

private Size NewSize(int maxWidth, int maxHeight, int width, int height)
{
double w = 0.0;
double h = 0.0;
double sw = Convert.ToDouble(width);
double sh = Convert.ToDouble(height);
double mw = Convert.ToDouble(maxWidth);
double mh = Convert.ToDouble(maxHeight);

if ( sw < mw && sh < mh )
{
w = sw;
h = sh;
}
else if ( (sw/sh) > (mw/mh) )
{
w = maxWidth;
h = (w * sh)/sw;
}
else
{
h = maxHeight;
w = (h * sw)/sh;
}

return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
}

private void SendSmallImage(string fileName, int maxWidth, int maxHeight)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(fileName));
System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;

Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height);
Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
Graphics g = Graphics.FromImage(outBmp);

// 設定畫布的描繪品質
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height),
0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();

if (thisFormat.Equals(ImageFormat.Gif))
{
Response.ContentType = "image/gif";
}
else
{
Response.ContentType = "image/jpeg";
}

// 以下代碼為儲存圖片時,設定壓縮品質
EncoderParameters encoderParams = new EncoderParameters();
long[] quality = new long[1];
quality[0] = 100;

EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;

//獲得包含有關內建映像編碼解碼器的資訊的ImageCodecInfo 對象。
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICI = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICI = arrayICI[x];//設定JPEG編碼
break;
}
}

if (jpegICI != null)
{
outBmp.Save(Response.OutputStream, jpegICI, encoderParams);
}
else
{
outBmp.Save(Response.OutputStream, thisFormat);
}

img.Dispose();
outBmp.Dispose();
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.