2017-07-31 58 views
0

我創建了用於上傳圖片的表格。上傳的圖片需要調整大小並上傳到s3存儲區。之後,我得到s3 url並保存到Post對象。但是我在調​​整大小和上傳時遇到了一些問題。這裏是我的代碼:Symfony3表格:調整上傳圖片的大小

表單控制器:

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 

回答

0

我認爲這個問題是你想如何保存圖像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);