【问题标题】:Amazon S3 Upload PDF and Create Cover ImageAmazon S3 上传 PDF 并创建封面图片
【发布时间】:2026-02-19 21:15:02
【问题描述】:

我有以下代码将 PDF 上传到 Amazon S3,我需要做的是从 PDF 的第一页创建一个图像并将其上传到 s3。

//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);

//check whether a form was submitted
if($_SERVER['REQUEST_METHOD'] == "POST")
{
    //retreive post variables
    $fileName = $_FILES['file']['name'];
    $fileTempName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];

    $extension=end(explode(".", $fileName));
    $rand = rand(1,100000000);
    $sha1 = sha1($rand);
    $md5 = md5($sha1);
    $fName = substr($md5, 0, 20);       
    $finalName = $fName.'.'.$extension;

    //create a new bucket
    $s3->putBucket("bucket", S3::ACL_PUBLIC_READ);

    //move the file
    if ($s3->putObjectFile($fileTempName, "bucket", 'publications/'.$finalName, S3::ACL_PUBLIC_READ)) {
        $s3file='http://bucket.s3.amazonaws.com/publications/'.$finalName;
        $aS3File = 'publications/'.$finalName;

        $im = new imagick($s3file[0]); 
        // convert to jpg 
        $im->setImageColorspace(255); 
        $im->setCompression(Imagick::COMPRESSION_JPEG); 
        $im->setCompressionQuality(75); 
        $im->setImageFormat('jpeg'); 
        //resize 
        $im->resizeImage(640, 877, imagick::FILTER_LANCZOS, 1);  
        //write image on server (line 54) 
        $s3->putObjectFile("","bucket", 'publications/'.$im->writeImage($fName.'.jpg'), S£::ACL_PUBLIC_READ);

    }else{
        echo "<strong>Something went wrong while uploading your file... sorry.</strong>";
    }

为了安全起见,我已经用“bucket”替换了我的实际存储桶名称,谁能告诉我我在这里做错了什么,因为我收到以下错误:

PHP 致命错误:带有消息的未捕获异常“ImagickException” '无法读取文件:h' in /var/www/ams/pub-new-issue.php:45\n堆栈跟踪:\n#0 /var/www/ams/pub-new-issue.php(45): Imagick->__construct('h')\n#1 {main}\n 在第 45 行的 /var/www/ams/pub-new-issue.php 中抛出,

谢谢

【问题讨论】:

    标签: php pdf amazon-s3 imagick


    【解决方案1】:
    $s3file='http://bucket.s3.amazonaws.com/publications/'.$finalName;
    $im = new imagick($s3file[0]); 
    

    $s3file 是一个字符串,但您正在访问其中的数组索引。结果,您获取了第一个字符h。在您的 Imagick 实例化中只使用 $s3file 就可以了。

    【讨论】:

    • 照你说的做了,但是得到了以下错误 未捕获的异常 'ImagickException' 并带有消息'无法打开图像`/var/www/ams/d4cf8f3e33c27055fcb3.jpg':@error/blob .c/OpenBlob/2587' 在 /var/www/ams/pub-new-issue.php:54\n堆栈跟踪:\n#0 /var/www/ams/pub-new-issue.php(54): Imagick->writeimage('d4cf8f3e33c2705...')\n#1 {main}\n 在第 54 行的 /var/www/ams/pub-new-issue.php 中抛出
    • /var/www/ams/d4cf8f3e33c27055fcb3.jpg 存在吗?网络服务器用户可以访问它吗?无论如何,这条路从何而来?根据您的代码,$s3file 应该是 http://bucket.s3.amazonaws.com/publications/...
    • /var/www/ams 是此应用程序的根文件夹,因此我认为它是可访问的。我只按照你的建议删除了 [0],所以我不确定它从哪里得到这个?
    • 很难说,因为您已经从示例中删除了一些代码,所以很难知道哪一行是#54。是$im-&gt;writeImage($fName.'.jpg') 行吗?如果是这样,您的网络服务器可能没有权限将图像写入该位置。您可能应该写入一个临时文件。
    • 第 54 行是 $s3->putObjectFile("","bucket", 'publications/'.$im->writeImage($fName.'.jpg'), S£::ACL_PUBLIC_READ) ;