Cropping an image before inserting into a post

I think you are good, but you don’t need to use other functions. You have all in

File: wp-includes/media.php

For instance, you may _wp_get_image_size_from_meta to get the image dimensions, so you don’t need to use something like this:

$size = getimagesize($file);
$width = $size[0];
$height = $size[1];
$mime = $size['mime'];

To get the image dimensions and type.

On the other hand, it is not clear why not using add_image_size

File: wp-includes/media.php
256: /**
257:  * Register a new image size.
258:  *
259:  * Cropping behavior for the image size is dependent on the value of $crop:
260:  * 1. If false (default), images will be scaled, not cropped.
261:  * 2. If an array in the form of array( x_crop_position, y_crop_position ):
262:  *    - x_crop_position accepts 'left' 'center', or 'right'.
263:  *    - y_crop_position accepts 'top', 'center', or 'bottom'.
264:  *    Images will be cropped to the specified dimensions within the defined crop area.
265:  * 3. If true, images will be cropped to the specified dimensions using center positions.
266:  *
267:  * @since 2.9.0
268:  *
269:  * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
270:  *
271:  * @param string     $name   Image size identifier.
272:  * @param int        $width  Image width in pixels.
273:  * @param int        $height Image height in pixels.
274:  * @param bool|array $crop   Optional. Whether to crop images to specified width and height or resize.
275:  *                           An array can specify positioning of the crop area. Default false.
276:  */
277: function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
278:    global $_wp_additional_image_sizes;
279: 
280:    $_wp_additional_image_sizes[ $name ] = array(
281:        'width'  => absint( $width ),
282:        'height' => absint( $height ),
283:        'crop'   => $crop,
284:    );
285: }

You can set the $crop option to true, and create thumbnails of 16:9 ratio. This organizes your images to particular size.

You can add multiple times:

add_image_size( 'andy1', 160, 90 , true);
add_image_size( 'andy2', 1600, 900, true);

And if possible thumbnails will be created, and in a way you like.

If you work with image srcset attribute this comes handy.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)