Tuesday, March 6, 2012

Using css and (optionally a Java class) to manipulate image

OK, this is not really about Java per se, it's about you can use only css to crop or resize an image
without having to rely on Java to do it for you (there are advantages and disadvantages to this approach)

I found these techniques by a Google search, here's an excellent article
that describes the concepts in greater detail:

http://cssglobe.com/post/6089/3-easy-and-fast-css-techniques-for-faux-image
(written by Allen Grakelik, Sept. 2009)

1. Create a css container to hold the canvas (where the image is placed) and apply
a background color for the canvas (if the image is getting resized to fit on the canvas)

2. Embed another css container to hold the actual image (that will be resized or cropped)

<style>
   #canvas {
       width: 600px;
        height: 400px;
       background-color: #aaaaaa;
   }
     #img-container {
         overflow:hidden !important /* this is the key */
     }        
    #img-container img {
          // the code in here will do the cropping of a square image so that it fits in the canvas
         width: 600px; // sets the full width of the image to the width of the canvas
         margin:  0px 0px -200px 0px;  // this will crop off 200px from the bottom of the actual image

        // code below resizes the image to 400x400 so it fits fully in the canvas
       
       height:400px; sets the dimension of the image
       padding-left: 100px; // centers the image on the canvas
    }
 </style>
 
 <div id='canvas'>
 <div id='img-container'>
           <img src='path_to_image'>
 </div>
  </div>
 
3.  You can generate the styling based on the image and canvas parameters and put that in a Java method to automate how you crop or resize an image, but it's not required.  Keep in mind you are not actually manipulating the image in java on the server (like you would in PHP using the GD library -- see my recent article here.)

The advantage of this method is that you can display the same image on a variety of different canvases without requiring Java, and it's very easy to set up.  The big disadvantage is that you have to load the full sized image first in the browser and then apply the css styling to it.  For extremely large images this approach is not recommended.  In such cases, it would be better to dynamically resize/crop the image on the server before sending it to the browser.

No comments:

Post a Comment