概要
wp_get_image_editor
関数は、WordPressで画像を操作するためのエディタオブジェクトを取得するための関数です。この関数は、画像のリサイズ、回転、トリミング、フィルタ適用など、画像処理機能を実装する際によく使用されます。
以下は、この関数がよく使われるシナリオの例です:
- 画像のサムネイルを生成する
- アップロードされた画像を特定のサイズにリサイズする
- 画像の回転を行う
- 画像のトリミングを実施する
- 画像にフィルタを適用する
- 画像を別のフォーマットに変換する(例:JPEGからPNG)
- 画像メタデータを取得する
- 画像の圧縮を行う
構文
$image_editor = wp_get_image_editor( $file );
パラメータ
- $file (string) : 操作対象の画像ファイルのパス。
戻り値
- 成功した場合は
WP_Image_Editor
オブジェクトを返し、失敗した場合はfalse
を返します。
関連する関数
使用可能なバージョン
- この関数は、WordPress 3.5.0以降で利用可能です。
コアファイルのパス
wp-includes/class-wp-image-editor.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | 〇 |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | 〇 |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード1:画像のエディタを取得する
このコードは指定した画像ファイルのエディタオブジェクトを取得し、エディタが正常に取得できた場合は、その画像をリサイズします。
$file = 'path/to/image.jpg';
$image_editor = wp_get_image_editor( $file );
if ( ! is_wp_error( $image_editor ) ) {
$image_editor->resize( 100, 100 );
}
引用元: https://developer.wordpress.org/reference/functions/wp_get_image_editor/
サンプルコード2:画像の回転
このサンプルコードは画像を指定した角度回転させる方法を示しています。
$file = 'path/to/image.jpg';
$image_editor = wp_get_image_editor( $file );
if ( ! is_wp_error( $image_editor ) ) {
$image_editor->rotate( 90 );
}
引用元: https://developer.wordpress.org/reference/functions/wp_get_image_editor/
サンプルコード3:画像のトリミング
画像を特定の位置とサイズでトリミングする方法を示しています。
$file = 'path/to/image.jpg';
$image_editor = wp_get_image_editor( $file );
if ( ! is_wp_error( $image_editor ) ) {
$image_editor->crop( 50, 50, 100, 100 ); // トリミングする位置とサイズ
}
引用元: https://developer.wordpress.org/reference/functions/wp_get_image_editor/
サンプルコード4:画像をJPEGからPNGに変換
指定した画像をJPEGからPNG形式に変換するサンプルコードです。
$file = 'path/to/image.jpg';
$image_editor = wp_get_image_editor( $file );
if ( ! is_wp_error( $image_editor ) ) {
$image_editor->save( 'path/to/output-image.png' );
}
引用元: https://developer.wordpress.org/reference/functions/wp_get_image_editor/
サンプルコード5:画像の圧縮
画像を圧縮するためのサンプルコードです。
$file = 'path/to/image.jpg';
$image_editor = wp_get_image_editor( $file );
if ( ! is_wp_error( $image_editor ) ) {
$image_editor->set_quality( 75 ); // 圧縮率を70%に
$image_editor->save( 'path/to/compressed-image.jpg' );
}
引用元: https://developer.wordpress.org/reference/functions/wp_get_image_editor/