【问题标题】:Symfony3 forms: resize uploaded imageSymfony3 表单:调整上传图片的大小
【发布时间】:2018-01-06 21:15:14
【问题描述】:

我创建了上传图片的表单。上传的图片需要调整大小并上传到 s3 存储桶。之后我得到 s3 url 并保存到 Post 对象。但是我在调​​整大小和上传时遇到了一些问题。这是我的代码:

表单控制器:

public function newAction(Request $request)
{
    $post = new Post();
    $form = $this->createForm('AdminBundle\Form\PostType', $post);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $img = $form['image']->getData();
        $s3Service = $this->get('app.s3_service');

        $fileLocation = $s3Service->putFileToBucket($img, 'post-images/'.uniqid().'.'.$img->guessExtension());

        $post->setImage($fileLocation);

        $em = $this->getDoctrine()->getManager();
        $em->persist($post);
        $em->flush();

        return $this->redirectToRoute('admin_posts_show', ['id' => $post->getId()]);
    }

    return $this->render('AdminBundle:AdvertPanel:new.html.twig', [
        'advert' => $advert,
        'form' => $form->createView(),
    ]);
}

app.s3_service - 我用来调整图片大小和上传图片的服务

public function putFileToBucket($data, $destination){

    $newImage = $this->resizeImage($data, 1080, 635);

    $fileDestination = $this->s3Service->putObject([
        "Bucket" => $this->s3BucketName,
        "Key" => $destination,
        "Body" => fopen($newImage, 'r+'),
        "ACL" => "public-read"
    ])["ObjectURL"];

    return $fileDestination;
}

public function resizeImage($image, $w, $h){
    $tempFilePath = $this->fileLocator->locate('/tmp');

    list($width, $height) = getimagesize($image);

    $r = $width / $height;

    if ($w/$h > $r) {
        $newwidth = $h*$r;
        $newheight = $h;
    } else {
        $newheight = $w/$r;
        $newwidth = $w;
    }

    $dst = imagecreatetruecolor($newwidth, $newheight);
    $image = imagecreatefrompng($image);
    imagecopyresampled($dst, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    file_put_contents($tempFilePath, $dst);
    return $tempFilePath;
}

但我收到错误:

  Warning: file_put_contents(): supplied resource is not a valid stream resource

【问题讨论】:

    标签: php symfony image-processing amazon-s3


    【解决方案1】:

    我认为问题在于您要如何使用 file_put_contents() 保存图像,您正在处理 gd 使用的特殊图像资源,该资源必须转换为正确的,例如png,文件。

    看起来您正在使用 GD,它提供了一种方法 imagepng(),您可以使用它来代替。您也可以在文档中找到示例:http://php.net/manual/en/image.examples.merged-watermark.php

    换句话说替换:

    file_put_contents($tempFilePath, $dst);
    

    与:

    imagepng($dst, $tempFilePath);
    

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 2011-08-25
      • 2014-08-26
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多