一个.net 压缩位图至JPEG的实例代码
2024-07-10 12:44:25
供稿:网友
首先准备一张位图图像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的值,将会看到不同的效果.