views:

316

answers:

6

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?

+1  A: 

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

usoban
+3  A: 

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

img {
    position:absolute;
    clip:rect(0px,100px,768px,0px);
}
Chris Pebble
+8  A: 

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>
Jonathan Sampson
Great!!!! Thanks a lot!
Andrea Girardi
One thing to add: although the CSS 2.1 spec shows clip used with commas to separate the values for rect, this isn't supported by IE 6, which requires spaces instead. Everything else supports this variation, so it's best just to use spaces and leave the commas out. See http://www.w3.org/TR/CSS21/visufx.html#propdef-clip: "User agents must support separation with commas, but may also support separation without commas (but not a combination), because a previous revision of this specification was ambiguous in this respect."
NickFitz
Noted, and corrected, NickFitz. Thanks.
Jonathan Sampson
+1  A: 

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...

spudly
It sounds like he needs the whole image loaded, but cut off.
Ape-inago
+1  A: 

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>
Alex
A: 

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" />
Hugh Bothwell