2009-09-11 47 views
0

我想在我的網頁上顯示圖像的一部分。假設原始格式爲1024x768,則所顯示的圖像必須是100x768。這不是一個重新調整大小,而是從0,0像素開始的簡單切割。有什麼建議麼?如何將圖像剪切成網頁

回答

8

使用CSS的剪輯屬性:

img { position:absolute; clip:rect(0px 60px 200px 0px) } 

或容器上使用溢出:

<div style="overflow:hidden; width:100px; height:76px;"> 
    <img src="myImage.jpg" /> 
</div> 
+0

大!!!!非常感謝! – 2009-09-11 13:40:34

+0

需要補充的一點是:儘管CSS 2.1規範顯示了用逗號分隔rect的值的剪輯,但IE 6不支持該屬性,而需要空格。其他所有內容都支持這種變體,所以最好只使用空格並留下逗號。請參閱http://www.w3.org/TR/CSS21/visufx.html#propdef-clip:「用戶代理必須支持用逗號分隔,但也可能支持不帶逗號的分隔(但不是組合),因爲以前的修訂這個規範在這方面是不明確的。「 – NickFitz 2009-09-11 13:50:13

+0

NickFitz注意到並糾正了。謝謝。 – Sampson 2009-09-11 13:55:19

1

裁剪圖像或使用現有庫,WideImage是此類操作的最佳選擇之一。

3

可以使用CSS clip只顯示圖像的一部分,如:

img { 
    position:absolute; 
    clip:rect(0px,100px,768px,0px); 
} 
1

在使用圖像編輯器將圖像上載到服務器之前裁剪圖像。除非由於某種原因,您需要加載整個圖像,但切斷...

+0

這聽起來像他需要加載整個圖像,但切斷。 – 2009-09-11 13:47:30

1

另一種解決方案是將圖像作爲背景圖像插入。

<div style="width: 768px; height: 100px; background: url(theimage.jpg) no-repeat left top;"></div> 
0

請注意,CSS解決方案實際上下載整個圖像,然後只顯示它的頂部。

根據使用情況,我會建議使用動態裁剪腳本或緩存預先裁剪的圖像。

裁剪腳本會是這樣的:

<?php 

// get parameters 
$fname = (string) $_GET['f']; 
$top = (int) $_GET['h']; 

// load original 
$old = imagecreatefromjpeg($fname); 
list($width, $height) = getimagesize($fname); 
    // N.B. this reloads the whole image! Any way to get 
    // width/height directly from $old resource handle?? 

// create new canvas 
$new = imagecreatetruecolor($width, $top); 

// copy portion of image 
imagecopy($dest, $src, 0, 0, 0, 0, $width, $top); 

// Output and free from memory 
header('Content-Type: image/jpeg'); 
imagejpg($new); 

?> 

,並會從你的網頁像被稱爲:

<img src="crop.php?f=myimg.jpg&h=100" />