我正在尝试生成我上传的PDF的缩略图,缩略图应该是PDF的第一页。现在我正在手动上传一张图片,使缩略图如下:
if (request()->has('pdf')) {
$pdfuploaded = request()->file('pdf');
$pdfname = $request->book_name . time() . '.' . $pdfuploaded->getClientOriginalExtension();
$pdfpath = public_path('/uploads/pdf');
$pdfuploaded->move($pdfpath, $pdfname);
$book->book_file = '/uploads/pdf/' . $pdfname;
$pdf = $book->book_file;
}
if (request()->has('cover')) {
$coveruploaded = request()->file('cover');
$covername = $request->book_name . time() . '.' . $coveruploaded->getClientOriginalExtension();
$coverpath = public_path('/uploads/cover');
$coveruploaded->move($coverpath, $covername);
$book->card_image = '/uploads/cover/' . $covername;
}
当输入许多我想自动生成缩略图的数据时,这可能会很乏味。我搜索了很多答案,但找不到具体的答案。我尝试使用ImageMagic和Ghost脚本,但找不到解决方案和合适的角色来实现。
对不起,还不能发表评论!当文件上传时,您可以使用spatie/pdf-to-image将第一页解析为图像,并将其存储在您的存储器中,并将链接保存在数据库中。
首先,您需要安装并配置php-imagick
和ghostscript
。有关ghostscript
安装的问题,您可以参阅。然后添加包composer require spatie/pdf-to-image
。
根据您的代码示例:
if (request()->has('pdf')) {
$pdfuploaded = request()->file('pdf');
$pdfname = $request->book_name . time() . '.' . $pdfuploaded->getClientOriginalExtension();
$pdfpath = public_path('/uploads/pdf');
$pdfuploaded->move($pdfpath, $pdfname);
$book->book_file = '/uploads/pdf/' . $pdfname;
$pdf = $book->book_file;
$pdfO = new SpatiePdfToImagePdf($pdfpath . '/' . $pdfname);
$thumbnailPath = public_path('/uploads/thumbnails');
$thumbnail = $pdfO->setPage(1)
->setOutputFormat('png')
->saveImage($thumbnailPath . '/' . 'YourFileName.png');
// This is where you save the cover path to your database.
}