แบบฟอร์ม Symfony3: ปรับขนาดภาพที่อัพโหลด

ฉันสร้างแบบฟอร์มสำหรับการอัพโหลดภาพ รูปภาพที่อัปโหลดจะต้องได้รับการปรับขนาดและอัปโหลดไปยังบัคเก็ต 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

person Community    schedule 31.07.2017    source แหล่งที่มา


คำตอบ (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);
person dbrumann    schedule 31.07.2017