2013-12-14 82 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