How to Expand a Cropped Image into a Box

CSS Display an Image Resized and Cropped

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>

Scale image to fit a bounding box

Note: Even though this is the accepted answer, the answer below is more accurate and is currently supported in all browsers if you have the option of using a background image.

Edit 2: In the modern age, using object-fit might be an even better solution: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

No, there is no CSS only way to do this in both directions. You could add

.fillwidth {
min-width: 100%;
height: auto;
}

To the an element to always have it 100% width and automatically scale the height to the aspect ratio, or the inverse:

.fillheight {
min-height: 100%;
width: auto;
}

to always scale to max height and relative width. To do both, you will need to determine if the aspect ratio is higher or lower than it's container, and CSS can't do this.

The reason is that CSS does not know what the page looks like. It sets rules beforehand, but only after that it is that the elements get rendered and you know exactly what sizes and ratios you're dealing with. The only way to detect that is with JavaScript.


Although you're not looking for a JS solution I'll add one anyway if someone might need it. The easiest way to handle this with JavaScript is to add a class based on the difference in ratio. If the width-to-height ratio of the box is greater than that of the image, add the class "fillwidth", else add the class "fillheight".

$('div').each(function() {
var fillClass = ($(this).height() > $(this).width())
? 'fillheight'
: 'fillwidth';
$(this).find('img').addClass(fillClass);
});
.fillwidth { 
width: 100%;
height: auto;
}
.fillheight {
height: 100%;
width: auto;
}

div {
border: 1px solid black;
overflow: hidden;
}

.tower {
width: 100px;
height: 200px;
}

.trailer {
width: 200px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tower">
<img src="http://placekitten.com/150/150" />
</div>
<div class="trailer">
<img src="http://placekitten.com/150/150" />
</div>

How to crop a rectangular image into a square with CSS?

Assuming they do not have to be in IMG tags...

HTML:

<div class="thumb1">
</div>

CSS:

.thumb1 { 
background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}

.thumb1:hover { YOUR HOVER STYLES HERE }

EDIT: If the div needs to link somewhere just adjust HTML and Styles like so:

HTML:

<div class="thumb1">
<a href="#">Link</a>
</div>

CSS:

.thumb1 { 
background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}

.thumb1 a {
display: block;
width: 250px;
height: 250px;
}

.thumb1 a:hover { YOUR HOVER STYLES HERE }

Note this could also be modified to be responsive, for example % widths and heights etc.

How to resize a image in php to fit it into a box of custom size preserving its aspect ratio?

$thumb_width = 90;
$thumb_max_height = 80;

$imageEditor = new ImageEditor($image_name, $path);

// get the size of the image
list($width_orig, $height_orig, $image_type) = getimagesize($path . $image_name);

// calculate the aspect ratio
$aspect_ratio = (float) $height_orig / $width_orig;

// calculate new height
$thumb_height = round($thumb_width * $aspect_ratio);

while($thumb_height>$thumb_max_height)
{
$thumb_width -= 10;
$thumb_height = round($thumb_width * $aspect_ratio);
}

// resize
$imageEditor->resize($thumb_width, $thumb_height);

$imageEditor->outputFile($image_name, $paththumbnail);
$imageEditor->outputFile();

Using Python- How to resize a cropped image to meet an aspect ratio while not exceeding original image size

The below code crops the image to required coordinates, then increases its size to match the aspect ratio depending if its >16/9 or <4/3. Advantage of this method is that it will not crop the centre object (car) when it resizes the image and corrects aspect ratio, and will increase left side of image if there is no space to increase in right side (and viceversa,for height and width) to achieve the Aspect ratio

import cv2
import math
import sys
imagepath=('/home/usr/Desktop/filename.jpeg')
img=cv2.imread(imagepath)
h,w,_=img.shape#height and width of original image

#Dimensions of car or object you want to crop (See step 2 in question)
crop_dimensions=[96, 56, 602, 686] #w1,h1,w2,h2

def cropimage(crop_dimensions,imgx):
crop_img = imgx[crop_dimensions[1]:crop_dimensions[3], crop_dimensions[0]:crop_dimensions[2]]
return crop_img

crop_img=cropimage(crop_dimensions,img)
height,width,_=crop_img.shape #height and width of cropped image

if width/height>16/9 or width/height<4/3:
crop_centrepoint = ((crop_dimensions[2] - crop_dimensions[0])/2, (crop_dimensions[3] - crop_dimensions[1])/2)
print(crop_centrepoint) #Centre point of cropped image

if width/height<4/3:
print('<4/3')

newwidth=4/3*height
newheight=height

additionalwidth=newwidth-width

w1maxadditional = crop_dimensions[0] - 0 #distance from cropped image to left edge (0)
w2maxadditional=w-crop_dimensions[2]#distance between cropped image and right end

if w2maxadditional > additionalwidth/2:
correction2=0
w2=(additionalwidth/2)
else:
correction2=abs(w2maxadditional-(additionalwidth/2))
w2=w2maxadditional

if w1maxadditional > additionalwidth/2:
correction1=0
w1=(additionalwidth/2)+correction1
else:
correction1=abs(w2maxadditional-(additionalwidth/2))
w1=w1maxadditional

w1=w1+correction2
w2 = w2+correction1
if w1>w1maxadditional:
w1=w1maxadditional
if w2>w2maxadditional:
w2=w2maxadditional

w1 = crop_dimensions[0] - w1
w2 = w2 + crop_dimensions[2]
h1=crop_dimensions[1]
h2=crop_dimensions[3]

if width / height > 16/9:
print('>16/9')

newheight = width * 9 / 16
newwidth = width

additionalheight = newheight - height

h1maxadditional = crop_dimensions[1] - 0 # distance from cropped image to top edge

h2maxadditional = h - crop_dimensions[3] # distance between cropped image to bottom end

if h2maxadditional > additionalheight / 2:
correction2 = 0
h2 = (additionalheight / 2)
else:
correction2 = abs(h2maxadditional - (additionalheight / 2))
h2 = h2maxadditional

if h1maxadditional > additionalheight / 2:
correction1 = 0
h1 = (additionalheight / 2) + correction1
else:
correction1 = abs(h2maxadditional - (additionalheight / 2))
h1 = h1maxadditional

h1 = h1 + correction2
h2 = h2 + correction1
if h1 > h1maxadditional:
h1 = h1maxadditional
if h2 > h2maxadditional:
h2 = h2maxadditional

h1 = crop_dimensions[1] - h1
h2 = h2 + crop_dimensions[3]

w1 = crop_dimensions[0]
w2 = crop_dimensions[2]

else:
[w1,h1,w2,h2]=crop_dimensions

#Rounding down because cropimage function takes integers
w1=math.trunc(w1)
h1=math.trunc(h1)
w2=math.trunc(w2)
h2=math.trunc(h2)

new_image=cropimage([w1,h1,w2,h2],img)

cv2.imshow('img',new_image)
cv2.waitKey(0)

How do I auto-resize an image to fit a 'div' container?

Do not apply an explicit width or height to the image tag. Instead, give it:

max-width:100%;
max-height:100%;

Also, height: auto; if you want to specify a width only.

Example: http://jsfiddle.net/xwrvxser/1/

img {
max-width: 100%;
max-height: 100%;
}

.portrait {
height: 80px;
width: 30px;
}

.landscape {
height: 30px;
width: 80px;
}

.square {
height: 75px;
width: 75px;
}
Portrait Div
<div class="portrait">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Landscape Div
<div class="landscape">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Square Div
<div class="square">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>

Cropping an image from the center into the largest square you can make in Yii2 Imagine?

Another try :p

<?php

use yii\imagine\Image;
use Imagine\Image\Box;
use Imagine\Image\Point;

// ...

$thumbnail = Image::thumbnail($save_path, $img_size, $img_size);
$size = $thumbnail->getSize();
if ($size->getWidth() < $img_size or $size->getHeight() < $img_size) {
$white = Image::getImagine()->create(new Box($img_size, $img_size));
$thumbnail = $white->paste($thumbnail, new Point($img_size / 2 - $size->getWidth() / 2, $img_size / 2 - $size->getHeight() / 2));
}
$thumbnail->save($save_path);

Resize and crop image with CSS

The only way you can achieve this only using css is to use the CSS background property combining it with the background-size and background-position properties.

SEE THIS FIDDLE

More information for these properties :

background-position

background-size

HTML:

<div class="container" style="background-image:url(http://www.recipestap.com/wp-content/plugins/wp-o-matic/cache/af4e1_ap.jpg)"></div>
<div class="container" style="background-image:url(http://3.bp.blogspot.com/-LAfvYIuz6c4/UpQxIe-FlmI/AAAAAAAAAcE/DVeCw1W6Yu4/s320/Eggless+Mini+Apple+Pie.JPG)"></div>

CSS:

.container { 
width: 180px;
height: 160px;
border:red solid 2px;

/* add following */
background-size:cover;
background-position:50% 50%;
}

ADDITIONAL INFORMATION

If you realy need the <img> tag for SEO reasons or other, you will need JS to face all the cases you may come through.

CASE 1 : image ratio is wider than container

Use height:100%; and width:auto; then you will need JS again to center the image in the container.

CASE 2 : image ratio is heigher than the container

Use width:100%; and height:auto; then JS or display:table;/display:table-cell to verticaly center the image in container.

I have used this technique on some projects but it is pretty heavy compared to the background CSS technique.

CSS Image size, how to fill, but not stretch?

You can use the css property object-fit. ("sets how the content of a replaced element, such as an <img> or <video>, should be resized to fit its container.")

.cover {
object-fit: cover;
width: 50px;
height: 100px;
}
<img src="http://i.stack.imgur.com/2OrtT.jpg" class="cover" width="242" height="363" />


Related Topics



Leave a reply



Submit