Kévin Dunglas
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.

Published in #Living on the edge