Symfony | liipimaginebundle: отобразить или преобразовать файл hei c - PullRequest
0 голосов
/ 15 января 2020

Технический контекст: Symfony 4.4, пакет liipimagine.

Я работаю над разработкой веб-приложения, в основном используемого на смартфоне. В моем приложении пользователь может загрузить изображение для своего профиля.

По сути, моя загрузка работает отлично. Моя единственная проблема - когда люди хотят загрузить изображение из их iphone: я не могу отобразить файл .hei c, так как это новый формат.

Я могу sh Я мог бы конвертировать файл hei c, или, если есть способ его отобразить ..

Вот мой существующий код:

Контроллер:

/** @var FormInterface $form */
$form = $this->createForm(UsersType::class, $currentUser);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {

    $uploadedFile = $form['imageFilename']->getData();

    if ($uploadedFile) {

        $newFilename = $uploaderHelper->uploadUserImage($uploadedFile, $currentUser);
        $currentUser->setImageFilename($newFilename);

        $entityManager->persist($currentUser);
        $entityManager->flush();
    }

    return $this->redirectToRoute('users_participants_list');
}

Класс UploadHelper:

class UploaderHelper
{
    const USER_IMAGE = 'user_image';

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

    /**
     * @var RequestStackContext
     */
    private $requestStackContext;

    /**
     * UploaderHelper constructor.
     * @param string $uploadsPath
     * @param RequestStackContext $requestStackContext
     */
    public function __construct(string $uploadsPath, RequestStackContext $requestStackContext)
    {
        $this->uploadsPath          = $uploadsPath;
        $this->requestStackContext  = $requestStackContext;
    }

    /**
     * @param UploadedFile $uploadedFile
     * @param Users $user
     * @return string
     */
    public function uploadUserImage(UploadedFile $uploadedFile, Users $user): string
    {
        /** @var string $destination */
        $destination =  $this->uploadsPath . '/' . self::USER_IMAGE;

        /** @var string $originalFilename */
        $originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);

        if ($uploadedFile->guessExtension() == 'heic') {

            // We need to convert the image

        }

        /** @var string $newFilename */
        $newFilename = strtolower($user->getName()).'_'.strtolower($user->getSurname()).'-'.uniqid().'.'.$uploadedFile->guessExtension();

        $uploadedFile->move($destination, $newFilename);
//        $this->correctImageOrientation($destination);

        return $newFilename;
    }

    /**
     * @param string $path
     * @return string
     */
    public function getPublicPath(string $path): string
    {
        return $this->requestStackContext->getBasePath() . '/uploads/' . $path;
    }

Конфигурация liip:

liip_imagine:
    # valid drivers options include "gd" or "gmagick" or "imagick"
    driver: "imagick"
    filter_sets:
        squared_thumbnail_small:
            filters:
                thumbnail:
                    size: [200, 200]

Отображение в виде:

{% if currentUser.imageFilename %}

<img src="{{ uploaded_asset(currentUser.imagePath)|imagine_filter('squared_thumbnail_small') }}" alt="{{ currentUser.name }} {{ currentUser.surname }}">#}

{% endif %}

1 Ответ

0 голосов
/ 16 января 2020

Кажется, что вы можете справиться с этим, не конвертируя свои файлы, используйте VichUploaderBundle для загрузки файлов https://symfony.com/doc/current/bundles/EasyAdminBundle/integration/vichuploaderbundle.html, и уже упоминалось, что вы можете проверять файлы, упомянутые в ссылке на этот вопрос, внутри вашего класса сущностей .

/**
 * @param ExecutionContextInterface $context
 */
public function validate(ExecutionContextInterface $context)
{
    if (! in_array($this->file->getMimeType(), array(
        'image/jpeg',
        'image/gif',
        'image/png',
        'image/heif',
        'image/heic',
        'image/heif-sequence',
        'image/heic-sequence',
    ))) {
        $context
            ->buildViolation('Wrong file type (mp4,mov,avi)')
            ->atPath('fileName')
            ->addViolation()
        ;
    }
} 

Как использовать mimeType Assert с VichUploader?

Надеюсь, это поможет вам.

...