CSS Display an Image Resized and Cropped

前端 未结 19 1575
时光取名叫无心
时光取名叫无心 2020-11-22 08:09

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

相关标签:
19条回答
  • 2020-11-22 09:01

    There are services like Filestack that will do this for you.

    They take your image url and allow you to resize it using url parameters. It is pretty easy.

    Your image would look like this after resizing to 200x100 but keeping the aspect ratio

    The whole url looks like this

    https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
    

    but the important part is just

    resize=width:200/crop=d:[0,25,200,100]
    

    0 讨论(0)
  • 2020-11-22 09:04

    You could use a combination of both methods eg.

        .crop {
            width: 200px;
            height: 150px;
            overflow: hidden;
        }
    
        .crop img {
            width: 400px;
            height: 300px;
            margin: -75px 0 0 -100px;
        }
        <div class="crop">
            <img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
        </div>

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

    0 讨论(0)
  • 2020-11-22 09:04

    object-fit may help you, if you're playing with <img> tag

    The below code will crop your image for you. You can play around with object-fit

    img {
      object-fit: cover;
      width: 300px;
      height: 337px;
    }
    
    0 讨论(0)
  • 2020-11-22 09:06

    You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.

    • Upload the image somewhere you prefer (S3, imgur etc.)
    • Plug it into your dedicated API url (from our dashboard)
    0 讨论(0)
  • 2020-11-22 09:07

    Thanks sanchothefat.

    I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.

    <div style="overflow:hidden;">
       <img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
    </div>
    
    0 讨论(0)
  • 2020-11-22 09:10

    Try using the clip-path property:

    The clip-path property lets you clip an element to a basic shape or to an SVG source.

    Note: The clip-path property will replace the deprecated clip property.

    img {
      width: 150px;
      clip-path: inset(30px 35px);
    }
    <img src="http://i.stack.imgur.com/wPh0S.jpg">

    More examples here.

    0 讨论(0)
提交回复
热议问题