New in Symfony 3.1: Data URI Normalizer

Contributed by
Kévin Dunglas
in #16164.

The Serializer component uses normalizers/denormalizers to turn objects into the interim arrays used to serialize/deserialize contents. In Symfony 3.1, a new DataUriNormalizer has been added to turn file objects into data:URI strings.

First, to normalize an object into a data:URI string, pass the instance of the object to the normalize() method:

1
2
3
4
5
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;

$normalizer = new DataUriNormalizer();
$avatar = $normalizer->normalize(new \SplFileObject('avatar.gif'));
// $avatar = 'data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=';

The normalized file contents can now be shared safely even with other technologies, such as JavaScript thanks to its FileReader.readAsDataURL() method.

Denormalizing a data:URI string into an object instance is very simple too:

1
2
3
4
5
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;

$normalizer = new DataUriNormalizer();
$avatar = $normalizer->denormalize('data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=', 'SplFileObject');
// $avatar is a SplFileObject with the GIF image contents

The normalizer/denormalizer supports any file object which is an instance of \SplFileInfo, including \SplFileObject and Symfony\Component\HttpFoundation\File\File objects.

When normalizing objects, the MimeTypeGuesser provided by the HttpFoundation component is used to determine the MIME type of the object. If your application uses a custom guesser, pass it as the first argument of the DataUriNormalizer class.

Comments

Awesome!
WoW!
It's a wonderful new feature :)
It might be a good idea to add that normalizer into Symfony 2.8+
@Artem due to the development policy of Symfony, we don't backport new features into older branches. First, adding new features is always risky and can introduce bugs, so we prefer to not break older branches. Second, having new features to use in your applications is a nice incentive to upgrade the Symfony version.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.