Working with Files and Images

Drupal comes with many capabilities for handling and manipulating files and images and has been adding to its toolset more and more with recent versions. Of course, this is not to say that media management has not been always a pain point for Drupal developers. In Drupal 7, a complicated suite of contributed modules was needed to achieve a basic level of functionality, something that users of "competitors" like WordPress enjoy out of the box. In Drupal 8, there is more emphasis placed on media management, and with each release Media capabilities have gone into core. The Media (entity) module, with its essential source plugins for supporting Images, Files, Remote Videos (Oembed) and Audio, as well as the experimental Media library, make for great advancements in the area. And together with popular contributed modules such as Entity Browser, a lot of this gap has been filled.

In this chapter, we will look at how we can work with files and images in Drupal, supported by the core features. Although the Media module allows developers to provide new Source plugins to expose media entities to all sorts of types of media, we won't be going into this quite advanced topic. Instead, we'll focus on lower-level tools that can be used for working with files. And we will see some examples along the way. So, what are we going to discuss?

First, we are going to get an understanding of the Drupal filesystems. Developers from previous versions of Drupal should already be familiar with these in theory, and we will see how these work in Drupal 8. Related to this, we're going to talk about stream wrappers and how Drupal handles native PHP file operations. We will even create our own custom stream wrapper a bit later in the chapter.

Then, we will talk a bit about the different ways to handle files in Drupal, namely, managed (tracked) and unmanaged files. In exemplifying the work with managed files, we will add an image field to our Product entity type and have images imported from a fictional remote environment. We will also create a brand-new CSV-based importer by which the product data is imported from a CSV file we read. In this process, we will note the Entity CRUD hooks, a very important extension point in Drupal 8, and see how we can use those in our example context.

We will end the chapter by seeing how we can work with various APIs that deal specifically with images, especially for manipulating them via image toolkits and working with image styles. So let's get to it.