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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…