简体   繁体   English

将imagick与S3 AWS结合使用

[英]Use imagick with S3 AWS

These are my first steps with AWS S3, so and my goal is to use imagick for manipulating the image before I upload to S3 AWS. 这些是我使用AWS S3的第一步,因此,我的目标是在上传到S3 AWS之前,使用imagick操纵图像。

I use this function for resize and scale the image (works perfect on output browser): 我使用此功能调整图像的大小和缩放比例(在输出浏览器上完美工作):

function resizeImg($img, $width, $height) {

    $i = new Imagick($img);

    $gig = $i->getImageGeometry();

    // crop the image
    if(($gig['width']/$width) < ($gig['height']/$height)) {

        $i->cropImage($gig['width'], floor($height * $gig['width'] / $width), 0, (($gig['height'] - ($height * $gig['width'] / $width)) / 2));

    } else {

        $i->cropImage(ceil($width * $gig['height'] / $height), $gig['height'], (($gig['width'] - ($width * $gig['height'] / $height)) / 2), 0);
    }

    $i->ThumbnailImage($width, $height, true);

    $i->setImageFormat("jpeg");
    $i->setImageCompressionQuality(90);

    $i->getimageblob(); // I tried it with and without getimageblob

    return $i;
}

Thats my attempt, Upload to S3: 那就是我的尝试,上传到S3:

$tmpImg = $_FILES['inputImage']['tmp_name'];

$newImgFile = resizeImg($tmpImg, 100, 100); 

$s3->putObjectFile($newImgFile, BUCKET_NAME, $newfilename, S3::ACL_PUBLIC_READ);

But I get this error: 但是我得到这个错误:

Warning: S3::inputFile(): Unable to open input file: in..... 警告:S3 :: inputFile():无法打开输入文件: in .....

What I`m doing wrong? 我做错了什么?

Is imagick not compatible with S3 AWS? imagick与S3 AWS不兼容吗?

Or is there a better way? 或者,还有更好的方法?

And my next goal is to put different image resizes to S3, eg 100x100, 300x300.... from same input file, but of course I have to solve before the first goal. 我的下一个目标是将来自同一个输入文件的不同图像大小调整为S3,例如100x100、300x300 ....,但是当然我必须在第一个目标之前解决。

EXTRA: 额外:

With this solution from here: PHP Imagick: Write Image directly to Amazon S3? 使用此处提供的解决方案: PHP Imagick:将图像直接写入Amazon S3吗?

I get this Error: 我收到此错误:

Warning: S3::putObject(): [SignatureDoesNotMatch] The request signature we calculated does not match the signature you provided. 警告:S3 :: putObject():[SignatureDoesNotMatch]我们计算出的请求签名与您提供的签名不匹配。 Check your key and signing method. 检查您的密钥和签名方法。

If I do this: $new = urlencode($new); 如果我这样做: $new = urlencode($new); or $new = strtolower($new); $new = strtolower($new); ...Works to upload but no readable! ...可以上传,但不可读!

The error came from extra spaces or slashes in there, so far as I have understood 据我所知,该错误来自其中的多余空格或斜杠

And if its important, here the Url from the image in S3 如果重要的话,这里是S3中的图片网址

https->awsCount.xxxx.xxxxx/img.jpg?AWSAccessKeyId=xxxx&Expires=1383787878&Signature=xxxx&x-amz-security-token=AQoDYXdzEGAasAJlJXrt/7FPf84wE9stfgBfEoWaPMDHlubQBlQ6oMY6sNMT4cizkEm9khypHulLB/zJ%2BbqqAErvFBKKs2I9bKDBzrKYKhgRn%2Bta057CZaLougsxHLRGquhd5H26br/Odkq98%2BoDTnfK0LHFa9vYbX6sXDIzCSHcZx4%2B5o0y3cKlxCMsYLqw6wYD1DNjJ%2BHlWWuh%2B6V0FtpbYaErB1XUZfRRZdx3ZPEOvyZxQS7uzP8C3B1nK0wo3uqqSAhn9PPtQt5jrRutYRao2KugxK8TbkZbr/v5NOYSbpc%2BmI2iYYrUjylqgenzf85Avss0CA1GfOzg%2BMs2/TQ7evH7epr09B8Vyd89Gk1XQpVMyrTSvbzDYE8UCcgrUrXgdHTYWdGLVZ%2BBHzft9nHtNhggePD6AXMuIP%2Ba6ZMF https-> awsCount.xxxx.xxxxx / img.jpg?AWSAccessKeyId = XXXX&过期= 1383787878&签名= XXXX&X-AMZ-安全令牌= AQoDYXdzEGAasAJlJXrt / 7FPf84wE9stfgBfEoWaPMDHlubQBlQ6oMY6sNMT4cizkEm9khypHulLB / ZJ%2BbqqAErvFBKKs2I9bKDBzrKYKhgRn%2Bta057CZaLougsxHLRGquhd5H26br / Odkq98%2BoDTnfK0LHFa9vYbX6sXDIzCSHcZx4%2B5o0y3cKlxCMsYLqw6wYD1DNjJ%2BHlWWuh%2B6V0FtpbYaErB1XUZfRRZdx3ZPEOvyZxQS7uzP8C3B1nK0wo3uqqSAhn9PPtQt5jrRutYRao2KugxK8TbkZbr / v5NOYSbpc%2BmI2iYYrUjylqgenzf85Avss0CA1GfOzg %2BMs2 / TQ7evH7epr09B8Vyd89Gk1XQPVMyrTSvbzDYE8UCcgrUrXgdHTYWdGLVZ%2BBHzft9nHtNhggePD6AXMuIP%2Ba6ZMF

You are trying to put an object from S3 from a file (putObjectFile takes a file name as an argument) but you're giving the image blob as a parameter, instead of a file name. 您正在尝试从文件中放入S3中​​的对象(putObjectFile将文件名作为参数),但是您将图像Blob作为参数而不是文件名。

You should do something like this: In resizeImg: 您应该执行以下操作:在resizeImg中:

return $i-> getimageblob(); //(this is just an assumption)

For uploading to S3, something similar to this: 要上传到S3,类似于以下内容:

$s3 = new AmazonS3();   
$s3->batch()->create_object(__BUCKET__,$filename, array(
                'body' => $object,
                'acl' => AmazonS3::ACL_PUBLIC,
                'contentType' => $contentType,
                'storage' => AmazonS3::STORAGE_REDUCED
                ));
$file_upload_response = $s3->batch()->send();

Note that this is using the PHP SDK V1 (not sure if you're using V2). 请注意,这是使用PHP SDK V1(不确定是否使用V2)。

I'll have the answer, I show the whole code for each one: 我会得到答案,我将显示每个代码的完整代码:

if (!empty($_FILES["input_file"])) {    

        if ($_FILES["input_file"]["error"] !== UPLOAD_ERR_OK) {

            echo "<p>An error occurred.</p>";
            exit;
        }    

        // Move/Copy from temporary file to local file

        $success = move_uploaded_file($_FILES["input_file"]["tmp_name"],
                'local_temp_file_directory/' . $_FILES["input_file"]["name"]);

        if (!$success) {

            echo "<p>Unable to save file.</p>";
            exit;
        }    
    }

    // I make a function to get the local file and save the edited file

    function resizeImg($img_from_local_file, $width, $height, $pathToSaveImg) {

        $i = new Imagick($img_from_local_file);
        $gig = $i->getImageGeometry();

        if(($gig['width']/$width) < ($gig['height']/$height)) {

            $i->cropImage($gig['width'], floor($height * $gig['width'] / $width), 0, (($gig['height'] - ($height * $gig['width'] / $width)) / 2));

        } else {

            $i->cropImage(ceil($width * $gig['height'] / $height), $gig['height'], (($gig['width'] - ($width * $gig['height'] / $height)) / 2), 0);
        }

        $i->ThumbnailImage($width, $height,true);
        $i->setImageFormat("jpeg");
        $i->setImageCompressionQuality(90);
        $i->writeImage($pathToSaveImg);
        return $i->getimage();
    }

    // Call the resizeImg function

    resizeImg("local_temp_file_directory/".$_FILES["input_file"]["name"], 40, 40, "local_temp_file_directory/resized_".$_FILES["input_file"]["name"]);

    $s3->putObject(
        S3::inputFile("local_temp_file_directory/resized_".$_FILES["input_file"]["name"]),
        BUCKET_NAME, 
        "make_a_new_image_name".date("his").".jpg", 
        S3::ACL_PUBLIC_READ, 
        array(), 
        array("Content-Type"=>'image/jpeg'));

 // Remove the temporary local file
 unlink("local_temp_file_directory/".$_FILES["input_file"]["name"]);
 unlink("local_temp_file_directory/resized_".$_FILES["input_file"]["name"]);

Thats it... Enjoy it! 就是这样...享受它!

you can doing these : 您可以执行以下操作:

    $outFile = $this->get('kernel')->getRootDir().'/../web/uploads/imageWithImagick.png';
    $url = "http//......";
    $img = new Imagick();
    $dir = "images/profile";
    $uploader = $this->get('core_storage.uploader');
    $width = 300;
    $height = 500;
    $compression = 90;
    $imageFormat = "jpeg";
    $uploader->uploadImagick($url,$img,$outFile,$width,$height,$dir,$imageFormat,$compression);

and the function : 和功能:

public function uploadImagick($url,$img,$outFile,$width,$height,$dir,$imageFormat,$compression)
{
    $handle = fopen($url, 'rb');
    $img->readImageFile($handle);
    $gig = $img->getImageGeometry();

    if(($gig['width']/$width) < ($gig['height']/$height)) {

        $img->cropImage($gig['width'], floor($height * $gig['width'] / $width), 0, (($gig['height'] - ($height * $gig['width'] / $width)) / 2));

    } else {

        $img->cropImage(ceil($width * $gig['height'] / $height), $gig['height'], (($gig['width'] - ($width * $gig['height'] / $height)) / 2), 0);
    }
    $img->thumbnailImage($width,$height);
    $img->setImageFormat($imageFormat);
    $img->setImageCompressionQuality($compression);
    $img->writeImage($outFile);
    // Generate a unique filename based on the date and add file extension of the uploaded file
    $filename = sprintf('%s/%s.%s', $dir, uniqid(), $imageFormat);
    $adapter = $this->filesystem->getAdapter();
    $adapter->write($filename, file_get_contents($outFile));
    unlink($outFile);
    return $filename;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM