最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to cut image into a web page - Stack Overflow

programmeradmin0浏览0评论

I'd like to show a part of an image on my web page. Suppose the original format is 1024x768 the image shown has to be 100x768. It's not a re-size but simple a cut starting from 0,0 pixel. Any suggestions?

I'd like to show a part of an image on my web page. Suppose the original format is 1024x768 the image shown has to be 100x768. It's not a re-size but simple a cut starting from 0,0 pixel. Any suggestions?

Share Improve this question edited Sep 11, 2009 at 13:55 Sampson 269k76 gold badges545 silver badges568 bronze badges asked Sep 11, 2009 at 13:29 Andrea GirardiAndrea Girardi 4,43713 gold badges72 silver badges102 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 8

Use CSS's Clip Property:

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

Or use overflow on a container:

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

You can use the CSS clip to show just part of the image, like:

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

Crop the image or use existing library, WideImage is one of the best for this kind of operations.

Crop the image before you upload it to the server using an image editor. Unless for some reason you need the whole image loaded but cut off...

Another solution would be inserting the image as a background image.

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

Note that the CSS solutions actually download the whole image, then show just the top portion of it.

Depending on usage, I would suggest either a dynamic cropping script or caching pre-cropped images.

A cropping script would be something like:

<?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);

?>

and would be called from your web page like:

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

评论列表(0)

  1. 暂无评论