Automattic\WooCommerce\EmailEditor\Integrations\Core\Renderer\Blocks

Image::get_local_image_width │ private │ WC 1.0

Get the width of an image stored locally in the uploads directory.

Only local files are measured. External URLs return null so the caller can fall back to the max width.

Method of the class: Image{}

No Hooks.

Returns

int|null. Image width in pixels, or null if it can't be determined locally.

Usage

// private - for code of main (parent) class only
$result = $this->get_local_image_width( $image_url ): ?int;
$image_url(string) (required)
Image URL.

Image::get_local_image_width() code WC 11.1.2

private function get_local_image_width( string $image_url ): ?int {
	$upload_dir = wp_upload_dir();
	$base_url   = trailingslashit( $upload_dir['baseurl'] );

	// Only measure images served from the uploads directory.
	if ( ! str_starts_with( $image_url, $base_url ) ) {
		return null;
	}

	$base_dir   = realpath( $upload_dir['basedir'] );
	$image_path = realpath( $upload_dir['basedir'] . '/' . substr( $image_url, strlen( $base_url ) ) );

	if ( false === $base_dir || false === $image_path ) {
		return null;
	}

	// Make sure the resolved file stays inside the uploads directory.
	$base_dir   = trailingslashit( wp_normalize_path( $base_dir ) );
	$image_path = wp_normalize_path( $image_path );
	if ( ! str_starts_with( $image_path, $base_dir ) ) {
		return null;
	}

	$result = wp_getimagesize( $image_path );

	return $result ? (int) $result[0] : null;
}