Convert all uploaded images to PNG using Doctrine

I am handling file upload in an entity and it works fine with all image formats:

/**
 * @var string
 * @ORMColumn(type="string", length=255, nullable=true)
 */
private $logo;

/**
 * @var string
 */
private $logoTemp;

/**
 * @var UploadedFile
 * @AssertFile(maxSize="1000000", maxSizeMessage="Logotipas didesnis nei 1MB.")
 */
private $logoFile;

// ...

/**
 * Setter of LogoFile
 *
 * @param UploadedFile $logoFile
 */
public function setLogoFile(UploadedFile $logoFile = null)
{
    $this->setUpdated(new DateTime());
    $this->logoFile = $logoFile;

    if ($this->logo) {
        $this->logoTemp = $this->logo;
        $this->logo = null;
    }
}

/**
 * Getter of LogoFile
 *
 * @return UploadedFile
 */
public function getLogoFile()
{
    return $this->logoFile;
}

protected function getUploadRootDir()
{
    return __DIR__ . '/../../../web/uploads';
}

// ...

/**
 * @ORMPreUpdate()
 */
public function preUpload()
{
    /** @var UploadedFile $logoFile */
    if ($logoFile = $this->getLogoFile()) {
        $filename = sha1(uniqid(mt_rand(), true));
        $this->logo = $filename . '.' . $logoFile->guessExtension();
    }
}

/**
 * @ORMPostUpdate()
 */
public function upload()
{
    /** @var UploadedFile $logoFile */
    if ($logoFile = $this->getLogoFile()) {
        $logoFile->move($this->getUploadRootDir(), $this->logo);

        if ($this->logoTemp) {
            $oldFile = $this->getUploadRootDir() . '/' . $this->logoTemp;
            if (file_exists($oldFile)) {
                unlink($oldFile);
            }
            $this->logoTemp = null;
        }

        $this->logoFile = null;
    }
}

Now instead of storing all image formats I would like to convert them to png.

I found this quick solution with PHP, but I have no idea how to apply it to my entity and UploadedFile instance:

imagepng(imagecreatefromstring(file_get_contents($filename)), "output.png");

I was searching in google "how to convert uploaded images in symfony", but I have no success. Anyone can help?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *