Is there a way in Sulu CMS to create an image object programmatically without uploading an actual image through the admin interface?
The usecase is, that I would like to display a resized fallback image, if the user does not upload a header image.
You can use the sulu_media.media_manager
service and give it a new UploadedFile instance e.g.:
$mediaManager->save(
new UploadedFile($path, $fileName, $mimeType),
[
'title' => 'Test',
'locale' => 'de',
'description' => '',
'collection' => $collectionId,
// ...
]
);
If performance matters or you need to import many files you should create the entities (media, files, fileVersion, fileVersionMeta) yourself and use the sulu.media.storage
service to save the actually file which will return you the storageOptions e.g.:
$media = new \Media();
$file = new File();
$file->setVersion(1);
$file->setMedia($media);
$media->addFile($file);
$mediaType = $this->entityManager->getReference(
MediaType::class, $this->mediaTypeManager->getMediaType($this->getMimeType($uploadedFile))
);
$media->setType($mediaType);
$collection = $this->entityManager->getReference(Collection::class, $collectionid);)
$media->setCollection($collection);
$storageOptions = $this->mediaStorage->save($file->getPathname(), $fileName)
$fileVersion = new FileVersion();
$fileVersion->setVersion($file->getVersion());
$fileVersion->setSize($uploadedFile->getSize());
$fileVersion->setName($fileName);
$fileVersion->setStorageOptions($storageOptions);
$fileVersion->setMimeType(/* ... */);
$fileVersion->setFile($file);
$file->addFileVersion($fileVersion);
$fileVersionMeta = new FileVersionMeta();
$fileVersionMeta->setTitle($title);
$fileVersionMeta->setDescription('');
$fileVersionMeta->setLocale($locale);
$fileVersionMeta->setFileVersion($fileVersion);
$fileVersion->addMeta($fileVersionMeta);
$fileVersion->setDefaultMeta($fileVersionMeta);
$this->entityManager->persist($fileVersionMeta);
$this->entityManager->persist($fileVersion);
$this->entityManager->persist($file);
$this->entityManager->persist($media);
// after importing the files or after every 100 files you should flush the entitymanager
$this->entityManager->flush();
// I also recommend in a import doing a clear to keep the entitymanager unitofwork small as possible
$this->entityManager->clear();
The media type manager is available under sulu_media.type_manager
and the doctrine entityManager doctrine.orm.entity_manager
In the end we made it by utilizing an image proxy (Thumbor in our case). This frees us from the image format restrictions of sulu and allows us to generate exactly the scaled / cropped versions of the file, that we need - all based on the original image url, that has been used for the upload.