0

I need to make Wordpress resize automatically images on upload to fit a particular width and height. (say 300px by 400px)

I know the add_image_size() function but it doesn't seems to fit my needs. The image is either resized but it keeps his ratio or it is resized to the desired width and height but cropped! These are not what i'm looking for.

I need the image to be "contained" into a 300x400 rectangle like the css property "background-size: contain" with eventually blank margins on borders if the image has another ratio.

Any idea please ? :)

1

WordPress's image resizing does not artwork your image onto a canvas, it just resizes mages to fit, cropping if you tell it to.

add_image_size('contained-image', 300, 400);

will get you the image size you want, but not letterboxed.

Images will be resized to fit tightly within a 300x400 rectangle. However they won't be padded out to 300x400 with a border saved as part of the image.

You ought to be able to achieve that in your CSS with something like

img.size-contained-image {
    width: 300px;
    height: 400px;
    object-fit: contain;
}

Although IE & older browsers won't support this, there are polyfills.

If you're calling the images into your theme, then you could wrap them in a div and use CSS to get your result.

It's also possible to hook into WP's resizing and do your own thing. Watermarking plugins do this, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.