Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display resized images on a web page while maintaining aspect ratio?

What is the best and quickest way to resize images on the client side using JavaScript?

EDIT: Sorry, I meant the best way to display an image resized on the client side..

like image 952
mattt Avatar asked Jun 10 '09 03:06

mattt


People also ask

How do you maintain aspect ratio in HTML?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I get pictures to fit on my website?

Open your file, Select Tools > Adjust Size. Set your width first. For this example, I set the width at 504 pixels, but you'll notice that makes the height 336 pixels. And that's how you crop and resize to a required dimension.

How do I keep resolution when resizing?

The resolution is the number of pixels per inch. The higher the resolution, the more pixels there are in the image, and the better the quality. If you want to resize an image without losing quality, you need to make sure that the "Resample Image" checkbox is unchecked.

How do I make my image fit responsive?

To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.


1 Answers

Easy.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Client-Side Image Resize (Why?!)</title>
    <script type="text/javascript">
      window.onload = function() {
        var url = "http://www.google.com/intl/en_ALL/images/logo.gif";
        var img = new Image();
        img.onload = function() {
          var w = parseInt((this.width + "").replace(/px/i, ""), 10);
          var h = parseInt((this.height + "").replace(/px/i, ""), 10);

          // 50% scale
          w = (w / 2) + "px";
          h = (h / 2) + "px";

          var htmlImg = document.createElement("img");
          htmlImg.setAttribute("src", url);
          htmlImg.setAttribute("width", w);
          htmlImg.style.width = w;
          htmlImg.setAttribute("height", h);
          htmlImg.style.height = h;
          document.body.appendChild(htmlImg);
        }
        img.src = url;
      }
    </script>
  </head>
  <body>
    <h1>Look, I'm Resized!</h1>
  </body>
</html>
like image 55
Josh Stodola Avatar answered Sep 23 '22 23:09

Josh Stodola