javascript - Resizing image of unknown size and aspect ratio - Stack Overflow

I basically have a group of images of unknown sizes.Some may have a width > height and vice versa.

I basically have a group of images of unknown sizes. Some may have a width > height and vice versa.

I need to display these items scaled to fit in a 300x300 box. Some of these images are smaller than 300x300 and need scaled up and some are larger and need scaled down.

So basically if I have an image that is 100x200, I need it to display at 150x300 and if I have an image that is 800x400 it needs to display as 300x150.

ie one of the dimension need to be fit on the box and other dimension need to be resize as aspect ratio.

Since this is a user selected object in a database, I initially tried this in javascript but I'm struggling. I'm curious if there's a purely CSS way to do this.

I basically have a group of images of unknown sizes. Some may have a width > height and vice versa.

I need to display these items scaled to fit in a 300x300 box. Some of these images are smaller than 300x300 and need scaled up and some are larger and need scaled down.

So basically if I have an image that is 100x200, I need it to display at 150x300 and if I have an image that is 800x400 it needs to display as 300x150.

ie one of the dimension need to be fit on the box and other dimension need to be resize as aspect ratio.

Since this is a user selected object in a database, I initially tried this in javascript but I'm struggling. I'm curious if there's a purely CSS way to do this.

Share Improve this question edited Nov 15, 2016 at 8:02 Samir Karmacharya 8908 silver badges22 bronze badges asked Nov 15, 2016 at 4:58 insertusernamehereinsertusernamehere 311 silver badge4 bronze badges 3
  • so you need a pure css solution or javascript is also acceptable? – S.Serpooshan Commented Nov 15, 2016 at 5:04
  • why don't you set only height or width only ? instead of set both height and width. – Anant Dabhi Commented Nov 15, 2016 at 5:05
  • instead of image, set it ad background of div, background-size: cover; background-position: center; should fit image in background zoomed on center – santosh Commented Nov 15, 2016 at 5:09
Add a ment  | 

5 Answers 5

Reset to default 3

Hello You can use below code only use css and javascript

which will maintain your aspect ration also

<style type="text/css">
    .image_box{
        width: 300px;
        height: 300px;
        background: #FF0;
    }
</style>
<div class="image_box">
    <img src="1.jpg"  id="imageid">
</div>
<script type="text/javascript">
    var img = document.getElementById('imageid'); 
    //or however you get a handle to the IMG
    var width = img.clientWidth;
    var height = img.clientHeight;
    //alert(width);
    //alert(height);
    if(width>height){
         img.style.width = '300px';
    }else{
        img.style.height = '300px';
    }
</script>

There are 2 ways you can do this with pure CSS.

Option 1: CSS Background-Image (Reended)

You can set the image to the background of a div and then set the div's height to the desired dimensions.

<div class="background"></div>

.background {
  background-image: url("SOMEURL");
  background-size: cover;
  background-position: center center;
  width: 150px;
  height: 300px;
}

You can set the background-size to cover to scale the background image so it takes up the available width or height.

This method is remended due to better browser support (IE 9+)

Demo: http://codepen.io/aaronvanston/pen/NbrYWM

Option 2: Using an Image and setting object-fit

You can use a normal image instead

<img src="SOMEURL" class="fit-image" >

.fit-image {
  width: 150px;
  height: 300px;
  object-fit: cover;
}

Demo: http://codepen.io/aaronvanston/pen/gLMeMX

This does the same thing as the background image however it's using an image element. However, this method isn't as supported. (no support for IE) http://caniuse./#feat=object-fit

The solution is a bination of two main features;

  1. Using a transparent gif or png image, sized at 300x300px
  2. css for the background image and using the background-size:contain property value.

Here's an example where i have used a 100x200 image and a 800 x 400 image. http://codepen.io/partypete25/pen/ZBOxKg/

The benefit of not specifying the width and height (using a transparent image to maintain the correct aspect ratio) is that you can use this implementation in a responsive build.

Method1 with simple css: (this way small pics will not scale up to container)

<div style="width:300px; height:300px; border:2px solid black;">
    <img src="images/p1.jpg" style="max-width:300px; max-height:300px;" />
</div>

Update Method 2: (this use background-image and works also for small pics, it is ok for modern browsers including IE9+)

<html>
<head>
<style type="text/css">
.divImg {
  width:300px; height:300px; border:2px solid black;
  background-repeat: no-repeat;
  background-size: contain; /* IE9+ patible */
}
</style>
</head>
<body>  
    <div class="divImg" style="background-image:url(p1.jpg)">
    </div>
</body>
</html>

I would do something like this. I hope this solution helps.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
  .img-cont {
    border: solid 1px red;
    width: 300px; /* reference border */
    height: 300px;
  }
</style>
</head>
<body>
<!-- images with different dimensions -->
<div class="img-cont"><img src="https://dummyimage./800x400/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage./400x800/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage./100x200/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage./200x100/000/fff" alt=""/></div>
    <script src="https://ajax.googleapis./ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">     
  (function($) {
    // max image width/height that we want
    var maxWidthAllowed = 300,
        maxHeightAllowed = 300;        
    function loadImg(imgObj) {        
      $('.img-cont img').one("load", function() {

        var imgWidth = $(this).get(0).naturalWidth,
            imgHeight = $(this).get(0).naturalHeight,
            coeff = imgWidth/imgHeight; // get image proportion
        if(parseFloat(coeff) > 1) {
          // wide image
          // resize proportionately
          $(this).css({
            'max-width': maxWidthAllowed,
            'width': '100%',
            'height' : 'auto'
          });
        } else {
          // thin image
          // resize proportionately
          $(this).css({
            'max-height': maxHeightAllowed,
            'height': '100%',
            'width' : 'auto'
          });
        }
      }).each(function() {
        if(this.plete) $(this).load();
      });
    }
    loadImg();
  })(jQuery);
    </script>
</body>
</html>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745333823a4623009.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信