Wordpress 插入 base64 图像作为附件不起作用
Wordpress insert base64 image as attachment not working
我找到了一种插入base64图像作为附件的方法,它插入成功但不显示图像的缩略图和大小。
see here
这是我的代码:
$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 );
我不确定哪里有问题或遗漏了,请帮忙!
谢谢
我找到了解决方案,我们需要为附件添加元数据。
$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);
这会很好用。
我找到了一种插入base64图像作为附件的方法,它插入成功但不显示图像的缩略图和大小。
see here
这是我的代码:
$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 );
我不确定哪里有问题或遗漏了,请帮忙!
谢谢
我找到了解决方案,我们需要为附件添加元数据。
$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);
这会很好用。