Home Forums ACF PRO Convert uploaded image to base64 value


Convert uploaded image to base64 value

  • Hello everyone,

    I wondered if anyone has managed to do the following with ACF:

    I would like to allow admins to upload an image using the Image field type (JPG, PNG, WEBP format etc), then convert the uploaded image to a base64 value, storing the base64 value in the DB for that field.

    My use for this is for an iOS app where I’m utilising the WP Rest API and would like to display icons as base64.

    If anyone’s experimented with this or can point me in the right direction it would be much appreciated.

    Many thanks,

  • You would need to use another field to store the converted value.

    I would not use an ACF field, I would simply use a standard WP meta field that is not viewable or editable by the user. I would create an acf/save_post action that converted the image and used update_post_meta() and get_post_meta() to deal with the value.

  • Many thanks for the quick reply John.

    This seems like a great solution thanks. Will attempt this now and report back 🙌

  • Thanks again John,

    This works great for me:

    add_action('acf/save_post', 'convert_to_base64');
    function convert_to_base64( $post_id ) {
    	// Get newly saved values.
    	$values = get_fields( $post_id );
    	// Check the new value of a specific field.
    	$icon_set = get_field('icon', $post_id);
    	$icon_output = get_field('icon_base64', $post_id);
    	$icon_default = 'No icon';
    	if( $icon_set ) {
    		$image = $icon_set;
    		$finfo = new finfo(FILEINFO_MIME_TYPE);
    		$type  = $finfo->buffer($image);
    		$base64 = "data:".$type.";charset=utf-8;base64,".base64_encode(file_get_contents($image));
    		update_field('icon_base64', $base64, $post_id);
    	} else {
    		update_field('icon_base64', $icon_default, $post_id);

    I want the user to be able to see the Base64 output but not interact with it. So have added some backend CSS styles to the output field to disable the cursor and show the field at 50% opacity.

    Thanks again for your help. Will mark as solved 👍

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.