wp_crop_image()WP 2.1.0

Crops an image to a given size.

Хуков нет.

Возвращает

Строку|WP_Error. New filepath on success, WP_Error on failure.

Использование

wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs, $dst_file );
$src(строка|int) (обязательный)
The source file or Attachment ID.
$src_x(int) (обязательный)
The start x position to crop from.
$src_y(int) (обязательный)
The start y position to crop from.
$src_w(int) (обязательный)
The width to crop.
$src_h(int) (обязательный)
The height to crop.
$dst_w(int) (обязательный)
The destination width.
$dst_h(int) (обязательный)
The destination height.
$src_abs(true|false|false)
If the source crop points are absolute.
По умолчанию: false
$dst_file(строка|false)
The destination file to write to.
По умолчанию: false

Список изменений

С версии 2.1.0 Введена.

Код wp_crop_image() WP 6.5.2

function wp_crop_image( $src, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false ) {
	$src_file = $src;
	if ( is_numeric( $src ) ) { // Handle int as attachment ID.
		$src_file = get_attached_file( $src );

		if ( ! file_exists( $src_file ) ) {
			/*
			 * If the file doesn't exist, attempt a URL fopen on the src link.
			 * This can occur with certain file replication plugins.
			 */
			$src = _load_image_to_edit_path( $src, 'full' );
		} else {
			$src = $src_file;
		}
	}

	$editor = wp_get_image_editor( $src );
	if ( is_wp_error( $editor ) ) {
		return $editor;
	}

	$src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs );
	if ( is_wp_error( $src ) ) {
		return $src;
	}

	if ( ! $dst_file ) {
		$dst_file = str_replace( wp_basename( $src_file ), 'cropped-' . wp_basename( $src_file ), $src_file );
	}

	/*
	 * The directory containing the original file may no longer exist when
	 * using a replication plugin.
	 */
	wp_mkdir_p( dirname( $dst_file ) );

	$dst_file = dirname( $dst_file ) . '/' . wp_unique_filename( dirname( $dst_file ), wp_basename( $dst_file ) );

	$result = $editor->save( $dst_file );
	if ( is_wp_error( $result ) ) {
		return $result;
	}

	if ( ! empty( $result['path'] ) ) {
		return $result['path'];
	}

	return $dst_file;
}