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,
Neil
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 👍
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.