(更新答案)
这个sight()
函数不仅上载图像,还创建一个附件(即attachment
类型);因此,我更新了代码—现在是function
已命名attachment_to_png
, 它使用get_attached_file()
要获取附加到该附件的图像文件update_attached_file()
更新文件路径。
因此,请遵循以下步骤:
将此添加到主题的functions.php
文件:
function attachment_to_png( $att_id ) {
$file = get_attached_file( $att_id );
if ( ! $file ) {
return false;
}
// Check MIME and make sure it\'s not already a PNG image.
$mime = strtolower( mime_content_type( $file ) );
if ( ! preg_match( \'#^image/([a-z]{3,})$#\', $mime, $m ) ||
\'png\' === $m[1]
) {
return false;
}
$im = imagecreatefromstring( file_get_contents( $file ) );
if ( false !== $im ) {
$filename = pathinfo( $file, PATHINFO_FILENAME );
$to = dirname( $file ) . \'/\' . $filename . \'.png\';
// Creates the image and saves it in `$to`.
imagepng( $im, $to );
// Frees the image from memory.
imagedestroy( $im );
// Deletes the original file.
unlink( $file );
// Update the attached file.
update_attached_file( $att_id, $to );
}
}
在
remove_filter(\'intermediate_image_sizes_advanced\', \'no_image_resizing\');
:
// Convert the image to PNG and delete the old image.
attachment_to_png( $newvidPix );
Additional Note
我不认为这是必要的。。所以你应该把它去掉。。。
$mfile = wp_handle_upload($files, $upload_overrides );
UTC于2018年12月3日更新(针对单个文件上载更新)
您不应该使用$im
然后简单地使用attachment_to_png()
作用并按如下方式调用函数:attachment_to_png( 123 )
哪里123
是附件ID。
使用media_handle_upload()
为上传的图像创建附件帖子,而不是wp_handle_upload()
.
所以试试这个:
if ( isset( $_POST["ebc_submit"] ) ) {
$uploadedfile2 = $_FILES[\'ebc_upload\'];
if ( ! empty( $uploadedfile2[\'name\'] ) ) {
$upload_overrides = array(
\'test_form\' => false
);
add_filter( \'upload_dir\', \'wpse_141088_upload_dir\' );
add_filter( \'intermediate_image_sizes_advanced\', \'no_image_resizing\' );
// Load media_handle_upload() and other media/image/file functions.
require_once ABSPATH . \'wp-admin/includes/media.php\';
require_once ABSPATH . \'wp-admin/includes/image.php\';
require_once ABSPATH . \'wp-admin/includes/file.php\';
// $v_Id is the ID of the post where the image should be attached to.
$endpic = media_handle_upload( \'ebc_upload\', $v_Id, array(), $upload_overrides );
remove_filter( \'upload_dir\', \'wpse_141088_upload_dir\' );
remove_filter( \'intermediate_image_sizes_advanced\', \'no_image_resizing\' );
// Convert the image to PNG and delete the old image.
if ( $endpic && ! is_wp_error( $endpic ) ) {
attachment_to_png( $endpic );
//echo \'Success!\';
}
}
}
如果您百分之百确定不会使用唯一的文件名,请于2018年12月5日UTC更新;i、 e.当您上载与以前上载的图像同名的图像时,您可以创建一个回调函数,该函数将由
wp_unique_filename()
, 返回原始(但已清理)文件名,如下所示:
// Add this to the theme\'s functions.php
function no_unique_filename( $dir, $name, $ext ) {
return $name;
}
然后,在
$upload_overrides
(请参阅以前的更新),添加
unique_filename_callback
像这样:
$upload_overrides = array(
\'test_form\' => false,
\'unique_filename_callback\' => \'no_unique_filename\',
);