Resize and crop Wordress functions. Code examples open

Resize and crop Wordress functions. Code examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
	function crop_image( $image_src ) {

		list( $width, $height ) = getimagesize( $image_src );

		//phpcs:disable
		$crop = isset( $_POST['crop_data'] ) ? recursive_map( 'intval', explode( ',', $_POST['crop_data'] ) ) : false;
		$size = isset( $_POST['image_size'] ) ? recursive_map( 'intval', explode( ',', $_POST['image_size'] ) ) : false;
		//phpcs:enable

		if ( ! $crop ) {
			return false;
		}

		list( $crop_x, $crop_y, $crop_w, $crop_h ) = $crop;
		list( $viewWidth, $viewHeight ) = $size;

		$cf = 1;
		if ( $viewWidth < $width ) {
			$cf = $width / $viewWidth;
		}

		$crop_x *= $cf;
		$crop_y *= $cf;
		$crop_w *= $cf;
		$crop_h *= $cf;


		$image = wp_get_image_editor( $image_src );

		if ( ! is_wp_error( $image ) ) {
			$image->crop( $crop_x, $crop_y, $crop_w, $crop_h );
			$image->save( $image_src );
		}
	}

	function resize_image( $image_src ) {

		if ( ! $this->resize ) {
			return false;
		}

		$image = wp_get_image_editor( $image_src );

		if ( ! is_wp_error( $image ) ) {
			$image->resize( $this->resize[0], $this->resize[1], false );
			$image->save( $image_src );
		}
	}

This code defines two functions crop_image() and resize_image() for manipulating images.

crop_image() function takes an image source path as input, along with optional crop data and image size data in POST variables. It then crops the image according to the provided crop data and resizes it based on the provided image size data. Finally, it saves the new image at the same image source path.

resize_image() function takes an image source path as input and resizes that image according to the specified dimensions in $this->resize. The resized image is saved at the same image source path. If resize property is not set or is false, the function returns without doing anything.

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation