How can I store an image in the database with Transients API?

I’m trying to store an image generated with imagecreatefrompng() using the Transients API, but it just stores an empty string (string(0) ""). Also, I notice if I set the transient before imagedestroy( $im ), the image is broken and doesn’t display at all (broken image thumbnail).

What can I store in the database with the Transients API? How would I store an image like described above?

1 Answer
1

imagecreatefrom* functions return an image resource identifier, which when cast to a string (saving an option) will result in an empty string(0) "" container.

Raw images created by these functions do not have any specific data structure that can be serialized out of the box. Two solutions I can think of:

image files

Use imagepng, for example to get the actual PNG data and store that instead.

$image_resource = imagecreatefrompng( ... );

// do GD manipulations

$temp = tempnam( sys_get_temp_dir(), 'image_cache_' );
imagepng ( $image_resource, $temp );

$image_data = file_get_contents( $temp );
set_transient( 'cached_image', base64_encode( $image_data ), 3600 );

unlink( $temp );

Remember to always base64_encode the data, since the options table in WordPress has LONGTEXT type data fields which is not binary-ready.

Also note how you can maybe cache the image data in the uploads folder instead and use the Transients API to cache their image names:

$image_resource = imagecreatefrompng( ... );

// do GD manipulations

$upload_dir = wp_upload_dir();
$upload_file = $upload_dir['path'] . "https://wordpress.stackexchange.com/" . $unique_image_name;

imagepng ( $image_resource, $upload_file );

set_transient( 'cached_image', $upload_file, 3600 );

dumping pixels

If, for one reason or another, you require to actually store raw pixel RGBA structures then you’ll need to use the imagecolorat and read each and every pixel of the image, create a huge array and serialize it. Retrieving this data will require the rebuilding of the image.

This method has a very high overhead, can get confusing with color allocations and alpha blending, so in short, should not be used.

Leave a Comment