2013-12-14 41 views
0

我在网页上显示图像。由于图像大小不一,我想裁剪它们(可能来自中心)。我想在运行时裁剪它们。在运行时裁剪图像ASP.NET

我正在使用datalist和img标签来显示来自特定文件夹的图像。有没有办法做到这一点?

编辑:

如果这是原始图像

enter image description here

我要裁剪它一定pixles的,像在这种情况下:220x160

enter image description here

+0

你想如何裁剪他们?到一定的格式(4:3,16:9,16:10等),或者你想裁剪它们到一定数量的像素(400px * 400px在中心等)? – SynerCoder

+0

我已经编辑了我的问题:) – rootpanthera

+0

你可以去找便宜的解决方案吗?在220x160 div中使用你的图像作为背景图像?这将使它们出现裁剪,同时仍然为缓存客户端提供完整大小的详细信息页面。 – sisve

回答

1
public Bitmap CropCenter(Bitmap src, int targetWidth, int targetHeight) 
{ 
    int x = src.Width/2 - targetWidth/2; 
     int y = src.Height/2 - targetHeight/2; 

     Rectangle area = new Rectangle(x, y, targetWidth, targetHeight); 

     return src.Clone(area, src.PixelFormat); 
} 

通源位图,然后输入所需的宽度,高度,裁剪掉IMG的中心也targetWidth的一些检查,targetHeight应该发生,以确保他们比的img本身较小。

编辑: 由于SynerCoder提到你也需要添加引用System.Windows.Drawing到你的项目。

+1

好的答案,但也许是一个好主意,告诉@rootpanthera他需要添加什么参考。他是使用asp.net webforms,所以System.Windows.Drawing不是一个标准的参考(我相信它是绘图,纠正我,如果我错了) – SynerCoder

+0

也..如何传递位图到这个方法?我有datalist和图像标签里面。什么是“cropArea”和“sourceImage”变量? – rootpanthera

+0

我建议你在上传时调整它们的大小,因为这会减少CPU的需求,而不是在每个请求上调整它们的大小。或者你可以在客户端使用CSS来实现这里是一个例子http://stackoverflow.com/questions/11552380/how-to-automatically-crop-and-center-an-image – sanke