2017-07-31 28 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、ファイル。

代わりに使用できる方法imagepng()を提供するGDを使用しているようです。あなたにもドキュメントの例を見つけることができます。つまりhttp://php.net/manual/en/image.examples.merged-watermark.php

は交換してください:

file_put_contents($tempFilePath, $dst); 

で:

imagepng($dst, $tempFilePath); 
関連する問題