首先准備一張位圖圖像source.bmp,將它保存在bmp.aspx同一目錄中
復制代碼 代碼如下:
<%@ Page language="c#" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script language="c#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
// 設置 mime 類型為image/jpeg,即將向浏覽器輸出JPGE格式的圖像
Response.Clear();
Response.ContentType="image/jpeg";
Bitmap OutputBitmap = new Bitmap(Server.MapPath("source.bmp"));//新建BitMap對象
System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
long[] quality = new long[1];
int comp = 0;
if (Request.QueryString["comp"] != "") { comp = Convert.ToInt16(Request.QueryString["comp"]); }
quality[0] = comp; //0 to 100 最高質量為100
System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();//獲得包含有關內置圖像編碼解碼器的信息的ImageCodecInfo 對象。
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)
{
OutputBitmap.Save(Response.OutputStream, jpegICI, encoderParams);//將位圖對象以流格式並用JPEG編解碼參數保存到輸出流。
}
// clean up
OutputBitmap.Dispose();
}
</script>
在浏覽器地址輸入:http://localhost/bmp.aspx?comp=0
將會看到圖像,調整comp的值,將會看到不同的效果.