Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3119

New in Symfony 3.1: Data URI Normalizer

$
0
0
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 newDataUriNormalizer 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
useSymfony\Component\Serializer\Normalizer\DataUriNormalizer;$normalizer=newDataUriNormalizer();$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
useSymfony\Component\Serializer\Normalizer\DataUriNormalizer;$normalizer=newDataUriNormalizer();$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 andSymfony\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.


Be trained by Symfony experts - 2016-04-11 Cologne - 2016-04-11 Cologne - 2016-04-11 Clichy

Viewing all articles
Browse latest Browse all 3119

Trending Articles