我们在做项目的时候我会用到图片对吧?
特别是在做列表页的时候。如果要显示缩略图,就随机挑选一张图片,我们的图片精度都比较高。
所以图片都比较大,所以我就想了一个方法。写一个方法对每张图片进行处理,然后html上的img标签,
就不在链接图片的真实的地址,而是链接Thumbnail.aspx?url=xxx 这种链接。代码为C#。
首先我们先添加一个web窗体,名为Thumbnail.aspx。
然后在Thumbnail.aspx.cs更换为如下代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Dome_Thumbnail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = Request["url"].ToString();
string url1 = Server.MapPath(url);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
GetReducedImage(200,200,url1).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/png";
Response.BinaryWrite(ms.ToArray());
}
public System.Drawing.Image GetReducedImage(int Width, int Height,string url)
{
string src = url;
System.Drawing.Image ResourceImage = System.Drawing.Image.FromFile(src);
try
{
//用指定的大小和格式初始化Bitmap类的新实例
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
//从指定的Image对象创建新Graphics对象
Graphics graphics = Graphics.FromImage(bitmap);
//清除整个绘图面并以透明背景色填充
graphics.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片对象
graphics.DrawImage(ResourceImage, new Rectangle(0, 0, Width, Height));
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
return bitmap;
}
catch (Exception e)
{
return null;
}
}
}
注意Thumbnail.aspx前台的html代码要全部删除,只留下c#代码,如下图所示。
然后我们添加一个html页面用img标签来链接两个地址。看看效果如何。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
old:<img src="../images/computer.png" style="width:200px; height:200px;" /><br/><br/>
new:<img src="/Dome/Thumbnail.aspx?url=/images/computer.png">
</body>
</html>
首先看原图,大小为121672字节:
再来看处理过后的图片,大小为21649字节:
这样就看出效果了。图片小了。页面的加载速度自然也就快了。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。