我有一个函数,可以获取上传的文件,保存它,然后用imagecrop
现在我需要再次将其保存到媒体。我知道怎么做香草PHP
, 但我需要将文件(元数据)插入数据库,而不仅仅是将文件保存到服务器。
使用此功能,我将文件插入媒体:
$attachmentId = media_handle_upload(\'image\', 0);
然后获取文件路径:
$img= get_attached_file($attachmentId);
然后,我将使用自定义裁剪图像:
function crop($filePath, $cropWidth, $cropHeight, $cropX, $cropY){
// returns imageCreateFromJpeg($filepath),
$image = $this->createImageFromAnyType($filepath);
$cropped = imagecrop($image, [\'x\' => $cropX,
\'y\' => $cropY, \'width\' => $cropWidth, \'height\' => $cropHeight]);
return $cropped ? imagejpeg($cropped) : false;
}
现在我有了这个资源
imagejpeg($cropped)
我不知道如何保存,就像
media_handle_upload
.
最合适的回答,由SO网友:gdfgdfg 整理而成
我所做的是获取媒体文件夹并将裁剪后的图像保存在那里。更新元数据后:
$imageToCropPath= get_attached_file($attachmentId); // Get file path to the image that will be cropped
$img = imageCreateFromJpeg($imageToCropPath);
$croppedImage = imagecrop($img, [\'x\' => $cropX,
\'y\' => $cropY,
\'width\' => $cropWidth,
\'height\' => $cropHeight]);
$uniqueId = md5(uniqid()); // Create unique name for the new image
$imagePath = wp_upload_dir()[\'path\'] . \'/\' . $uniqueId . \'.jpg\';
imagejpeg($croppedImage, $imagePath); // Save image in the media folder
$attachment = array(
\'post_mime_type\' => \'image/jpeg\',
\'post_title\' => basename($imagePath),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$croppedAttachmentId = wp_insert_attachment( $attachment, $imagePath );
$attachedData = wp_generate_attachment_metadata( $croppedAttachmentId, $imagePath);
wp_update_attachment_metadata( $croppedAttachmentId , $attachedData );