N
N
Nikita Gushchin2015-08-31 22:28:07
symfony
Nikita Gushchin, 2015-08-31 22:28:07

How to correctly resize images in the REST API?

Hello! There is an Image entity that should store 2 images (original + thumbnail):

/**
 * @ORM\Entity
 * @Vich\Uploadable
 */
class Image
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    // ..... other fields

    /**
     * 
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
     * 
     * @var File
     */
    private $imageFile;

When adding an image, you need to:
1) Attach the uploaded image to the entity
2) Convert the uploaded image to jpg
3) Make a thumbnail
If you just add a file, then everything is more or less clear:
/**
     * @Rest\View()
     */
    public function postAction(Request $request)
    {
        /**
         * @var UploadedFile $uploadedFile
         */
        $uploadedFile = $request->files->get('some_file');

        $image = new Image();
        $image->setImageFile($uploadedFile);
        $isValid = $this->get('validator')->validate($image);
        if($isValid->count() !== 0)
            throw new BadRequestHttpException('Bad file');
        $om = $this->getDoctrine()->getManager();

        $om->persist($image);
        $om->flush();
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wittyrider, 2015-08-31
@wittyrider

Take this case to a separate service, resize it with any library, for example , this .
Next, use this service in doctrine events. preUpdate/postDelete/etc.
I think the day is understood. Good luck !

D
Denis, 2015-09-04
@prototype_denis

https://github.com/liip/LiipImagineBundle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question