【发布时间】:2009-09-11 13:29:33
【问题描述】:
我想在我的网页上显示图像的一部分。假设原始格式为 1024x768,则显示的图像必须为 100x768。这不是重新调整大小,而是从 0,0 像素开始的简单剪切。有什么建议吗?
【问题讨论】:
标签: php javascript css
我想在我的网页上显示图像的一部分。假设原始格式为 1024x768,则显示的图像必须为 100x768。这不是重新调整大小,而是从 0,0 像素开始的简单剪切。有什么建议吗?
【问题讨论】:
标签: php javascript css
使用 CSS 的 Clip 属性:
img { position:absolute; clip:rect(0px 60px 200px 0px) }
或者在容器上使用溢出:
<div style="overflow:hidden; width:100px; height:76px;">
<img src="myImage.jpg" />
</div>
【讨论】:
您可以使用CSS clip 仅显示图像的一部分,例如:
img {
position:absolute;
clip:rect(0px,100px,768px,0px);
}
【讨论】:
裁剪图像或使用现有库,WideImage 是此类操作的最佳选择之一。
【讨论】:
在使用图像编辑器将图像上传到服务器之前对其进行裁剪。除非由于某种原因您需要加载整个图像但被切断...
【讨论】:
另一种解决方案是将图像作为背景图像插入。
<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" />
【讨论】: