New in Symfony 3.1: Data URI Normalizer
April 11, 2016 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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
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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
It's a wonderful new feature :)