一个.net 压缩位图至JPEG的实例代码
程序员文章站
2024-02-29 15:21:40
首先准备一张位图图像source.bmp,将它保存在bmp.aspx同一目录中 复制代码 代码如下:  ...
首先准备一张位图图像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的值,将会看到不同的效果.
复制代码 代码如下:
<%@ 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的值,将会看到不同的效果.
上一篇: C#获取当前页面的URL示例代码
下一篇: Android实现分享功能