Cropping an image before inserting into a post

I've got a frontend post form, and I've been using this PHP code to allow uploading an image and to insert it into a post.

    // image upload and attatching to post
    if ( ! empty( $_FILES )  ! empty( $_FILES['upload-image']['name'] ) ) {

        // upload image to server
        $upload = wp_upload_bits( $_FILES['upload-image']['name'], null, file_get_contents( $_FILES['upload-image']['tmp_name'] ) );

        // insert new image to the just created post ================================
        $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );
        $wp_upload_dir = wp_upload_dir();

        $attachment = array(
            'guid'           = $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $upload['file'] ),
            'post_mime_type' = $wp_filetype['type'],
            'post_title'     = preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),
            'post_content'   = '',
            'post_status'    = 'inherit'
        );
        $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );

        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );      
        wp_update_attachment_metadata( $attach_id, $attach_data );
        update_post_meta( $post_id, '_thumbnail_id', $attach_id );
        // end insert ==============================================

    }

How can I ensure that all images are cropped to a 16:9 aspect ratio, before it is inserted into the post? So if the image's height is too high, it crops the top and bottom to fit it into 16:9 ratio, and if the image's width is too wide, it crops the sides to fit it into 16:9 ratio.

I've found a function that always crops the image to a 16:9 ratio here that I could base it on: https://stackoverflow.com/questions/29063094/php-fit-any-size-image-to-169-aspect-ratio (not tested). But I'm not sure how to use this in my above code above - the 16:9 ratio image needs to be ready before inserting into the post.

Any help appreciated.

Topic wp-insert-post cropping images Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.