Sunday, March 27, 2011

CSS Display an Image Resized and Cropped

I want to show an image from an URL with a certain width and height even if it has a diferent size ratio. So I want to resize (maintaning the ratio) and then cut the image to the size I want.

I can resize with html img property and I can cut with background-image.
How can I do both?

Example:

This image: "http://img1.jurko.net/wall/paper/donald_duck_4.jpg"
Has the size 800x600 pixels and I want to show like an image of 200x100 pixels


With img I can resize the image 200x150px:

<img style="width: 200px; height: 150px;" src="http://img1.jurko.net/wall/paper/donald_duck_4.jpg">


That gives me this:


And with "background-image" I can cut the image 200x100 pixels.

<div style="background-image:url('http://img1.jurko.net/wall/paper/donald_duck_4.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div>

Gives me:

 


How can I do both?
Resize the image and then cut it the size I want?

From stackoverflow
  • You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.

  • You could use a combination of both methods eg.

    <div class="crop">
        <img src="..." alt="..." />
    </div>
    

    CSS:

    .crop { width: 200px; height: 150px; overflow: hidden; }
    .crop img { width: 400px; height: 300px; margin: -75px 0 0 -100px; }
    

    You can use negative margin to move the image around within the div.

    Frank Schwieterman : Note that if you set position:relative on the contained image, you'll need to set position:relative on the containing div. If you don't, I've found that IE won't actually clip the image.
  • <style>
      .imgContainer{
      overflow:hidden;
      width:200px;
      height: 100px;
      }
      .imgContainer img{
      width:200px;
      hieght:120px;
      }
    </style>
    
    <div class="imgContainer">
         <img src="imageSrc" />
    </div>
    

    The containing div with essentially crop the image by hiding the overflow.

  • What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.

    It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)

    strager : CGI is probably the most portable method (and bandwidth-efficient), unless the OP intends to allow the user to perform their own resizing and cropping via Javascript.
  • Rob, I know it is a bit old thread, but maybe You could help me... if You have that code any more... i'd be grateful for it :) Can You write it down, or sent me on my e-mail address (drartoor[at]o2.pl)

    Thanks in advance

    Sorry for my English - it's not my native language :)

0 comments:

Post a Comment