Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

Wordpress insert base64 image as attachment not working

I have found a way to insert base64 image as attachment, it inserted succeed but not show the thumbnail and size of image.

see here

THis is my code:

$imgpath = "data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA34AAAK8C...";
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$img = str_replace('data:image/jpeg;base64,','',$imgpath);
$img = str_replace( ' ', '+', $img );
$decoded = base64_decode( $img );
$filename = "preview.jpeg";
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename;
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );
$attachment = array(
    'post_mime_type' => "image/jpeg",
    'post_title' => preg_replace('/.[^.]+$/', '', basename($hashed_filename)),
    'post_content' => '',
    'post_status' => 'inherit',
    'guid' => $wp_upload_dir['url'] . '/' . basename($hashed_filename)
);
$attach_id = wp_insert_attachment( $attachment, $upload_dir['path'] . '/' . $hashed_filename );

I don't sure what's wrong or missing, please help!

Thanks

question from:https://stackoverflow.com/questions/65951240/wordpress-insert-base64-image-as-attachment-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found solution, we will need add meta for the attachment.

$info = getimagesize($imgpath);
$meta = array (
    'width' => $info[0],
    'height' => $info[1],
    'hwstring_small' => "height='{$info[1]}' width='{$info[0]}'",
    'file' => preg_replace('/.[^.]+$/', '', basename($hashed_filename)),
    'sizes' => array(),         // thumbnails etc.
    'image_meta' => array(),    // EXIF data
);
update_post_meta($attach_id, '_wp_attachment_metadata', $meta);

This will work fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...