如何将图像剪切成网页

如何将图像剪切成网页

问题描述:

我想在我的网页上显示图像的一部分。假设原始格式为1024x768,则所显示的图像必须是100x768。这不是一个重新调整大小,而是从0,0像素开始的简单切割。有什么建议么?如何将图像剪切成网页

使用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

裁剪图像或使用现有库,WideImage是此类操作的最佳选择之一。

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

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

在使用图像编辑器将图像上载到服务器之前裁剪图像。除非由于某种原因,您需要加载整个图像,但切断...

+0

这听起来像他需要加载整个图像,但切断。 – 2009-09-11 13:47:30

另一种解决方案是将图像作为背景图像插入。

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

请注意,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" />