Site icon Hip-Hop Website Design and Development

How can I return an image from a custom REST API endpoint?

I’m brand new to WordPress development; Trying to return an image from a custom endpoint, but it seems to want to serialize everything to JSON.

I did manage to get it to work using echo. Is that a hack?

I also tried using WP_HTTP_Response, but that didn’t seem to work.

My code:

require 'vendor/autoload.php';

use InterventionImageImageManagerStatic as Image;

function prefix_generate_cover_photo($data) {
    $image = Image::make(plugin_dir_path(__FILE__) . 'image.png')->response();
    $response = new WP_REST_Response($image, 200, array(
        'Content-Type' => 'image/png'
    ));
    return $response;
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'prefix/v1', '/photo', array(
        'methods' => 'GET',
        'callback' => 'prefix_generate_cover_photo',
    ));
});

This works but I’m not sure if it’s good practice:

function prefix_generate_cover_photo($data) {
    echo Image::make(plugin_dir_path(__FILE__) . 'image.png')->response();
}

Any ideas?