查看cropzee documentation
要知道如何设置此插件,请按照以下说明进行操作。
- 将返回类型设置为
data-url
jQuery("#cropzee-input").cropzee({
returnImageMode: 'data-url',
});
- 通过ajax发送图片数据到后端
ajaxRequ.send(cropzeeGetImage('cropzee-input'));
[假设你知道'ajax with wordpress',如果不先谷歌然后回到这里]
- 将 data-url 转换为图像并将其保存在自定义文件夹中。
<?php
function base64_to_jpeg($base64_string) {
// open the output file for writing
$token = rand();
global $current_user;
wp_get_current_user() ;
//create a directory
mkdir(get_template_directory().'/temp');
//give a unique name to the image you may use username
$temp_path = get_template_directory().'/temp/profile_pic_'.$current_user->user_login.'.jpg';
// open the file to write the image data
$ifp = fopen($temp_path,'w' ) or die();
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// write image data
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
exit();
}
add_action("wp_ajax_temp_profile_pic","temp_profile_pic");
function temp_profile_pic(){
$bsestring = file_get_contents("php://input");
base64_to_jpeg($bsestring);
wp_die();
}
- 最后附上wordpress附件
// to use media_handle_sideload() include the following
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
$temp_path = get_template_directory().'/temp/profile_pic_'.$current_user->user_login.'.jpg';
//check if file exists
if (file_exists($temp_path)) {
// check whether it is real image or not
if (getimagesize($temp_path)) {
$final_path = wp_upload_dir()['path'].'/'.pathinfo($temp_path, PATHINFO_BASENAME);
//create file array
$tmp = download_url(get_template_directory_uri().'/temp/profile_pic_'.$current_user->user_login.'.jpg');
$file_array = array(
'name' => basename(get_template_directory_uri().'/temp/profile_pic_'.$current_user->user_login.'.jpg'),
'tmp_name' => $tmp
);
//upload it to wp media upload directory
$upload = media_handle_sideload($file_array, 0);
if (empty($upload)) {
echo "Successfully Uploaded"
} elseif (!empty($upload)) {
echo "Upload Failed!"
}
}
//delete existing photo
@unlink($tmp);
}
}
}
?>
您可以检查各种条件以使操作更精确。当然不用ajax也可以操作。只需将数据 url 放入 html textarea 元素并提交然后处理它。