0
votes

I created form for uploading images. Uploaded image needs to be resized and uploaded to s3 bucket. After that I get s3 url and save to Post object. But I am having some problems with resizing and uploading. Here is my code:

Form Controller:

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 - service that I user to resize and upload image

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;
}

But I am getting error:

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

1 Answers

0
votes

I think the problem is how you want to save the image with file_put_contents() you are dealing with a special image resource used by gd that has to be transformed into a proper, e.g. png, file.

It looks like you are using GD which offers a method imagepng() which you can use instead. You can find an example in the docs as well: http://php.net/manual/en/image.examples.merged-watermark.php

In other words replace:

file_put_contents($tempFilePath, $dst);

with:

imagepng($dst, $tempFilePath);