Three months in the past I wrote an article on methods to Create Picture Kinds and Results programmatically and in the present day we’re following up on that article however introducing on how we are able to do this dynamically. So, basically what we wish to do is that we show a picture, the place we are able to modify Drupal Development method Drupal Development picture is outputted, given a peak, width or side ratio and so forth. Please keep in mind that every one code offered on this article are experimental and doesn’t but cowl issues like entry management, and so forth on this half. Let’s check out Drupal Development service Unsplash.com. Its principally a free picture financial institution with top quality photographs submitted by superior freelancers and professionals that you need to use without cost. Picture by Eric Ward Drupal Development Company URL for Drupal Development picture above is Drupal Development following Drupal 10 Upkeep and Assist Service https Drupal 10 Upkeep and Assist Service//photographs.unsplash.com/photo-1499365094259-713ae26508c5?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=26d4766855746c603e3d42aaec633144&auto=format&match=crop&w=500&q=60 Drupal Development Company elements we’re truly focused on are Drupal 10 Upkeep and Assist Service &auto=format&match=crop&w=500&q=60 we are able to modify them as we like and Drupal Development picture is displayed in a different way, i.e. altering Drupal Development width of Drupal Development earlier picture to a smaller one Drupal 10 Upkeep and Assist Service Alright, that is what we wish to do in 8. This text might be very iteratively, we’ll rewrite Drupal Development similar code again and again till we get what we wish. We’ll discover points and issues that we’ll cope with by way of out Drupal Development article. Put together an setting to work in We’ll use a recent 8.6.x set up. To rapidly scaffold some boilerplate code I will use Console. First let’s create a customized Drupal 10 module the place we are able to put our code and logic in Drupal 10 Upkeep and Assist Service $ vendor/bin/Drupal 10 generate Drupal 10 Upkeep and Assist ServiceDrupal 10 module I will identify Drupal Development Drupal 10 module dynamic_image_viewer dynamic_image_viewer.data.yml identify Drupal 10 Upkeep and Assist Service ‘Dynamic Picture Viewer’ kind Drupal 10 Upkeep and Assist Service Drupal 10 module description Drupal 10 Upkeep and Assist Service ‘View a picture dynamically’ core Drupal 10 Upkeep and Assist Service 8.x package deal Drupal 10 Upkeep and Assist Service ‘Customized’ Subsequent we’d like some photographs to work with, we’ll use Drupal Development core Media Drupal 10 module for that. So let’s allow that Drupal 10 module Drupal 10 Upkeep and Assist Service vendor/bin/Drupal 10 Drupal 10 module Drupal 10 Upkeep and Assist Serviceinstall media Now we are able to add some photographs. Go to Content material >> Media >> Add media. Implementing a Controller to show Drupal Development picture Drupal Development Company first step is to create a controller that may render Drupal Development Media picture to Drupal Development browser. Once more we’ll use Console for a controller scaffold Drupal 10 Upkeep and Assist Service vendor/bin/Drupal 10 generate Drupal 10 Upkeep and Assist Servicecontroller We’ll create a route on /picture/{media} the place Media will settle for an media ID that because of s parameter upcasting will give us a media occasion in Drupal Development controller methodology arguments. Doing this, if a invalid media ID is handed in Drupal Development URL a 404 web page is proven for us. Neat! So we’ll modify Drupal Development generated controller barely to this Drupal 10 Upkeep and Assist Service src/Controller/ImageController.php <?php namespace dynamic_image_viewerController; use CoreControllerControllerBase; use mediaMediaInterface; /** * Class ImageController. */ class ImageController extends ControllerBase { /** * Present a picture. * * @param MediaInterface $media * * @return array */ public operate present(MediaInterface $media) { return [ ‘#type’ => ‘markup’, ‘#markup’ => $media->id(), ]; } } And Drupal Development routing file appears to be like like this Drupal 10 Upkeep and Assist Service dynamic_image_viewer.routing.yml dynamic_image_viewer.image_controller_show Drupal 10 Upkeep and Assist Service path Drupal 10 Upkeep and Assist Service ‘/picture/{media}’ defaults Drupal 10 Upkeep and Assist Service _controller Drupal 10 Upkeep and Assist Service ‘dynamic_image_viewerControllerImageController Drupal 10 Upkeep and Assist Service Drupal 10 Upkeep and Assist Serviceshow’ _title Drupal 10 Upkeep and Assist Service ‘present’ necessities Drupal 10 Upkeep and Assist Service _permission Drupal 10 Upkeep and Assist Service ‘entry content material’ If we set up Drupal Development Drupal 10 module, vendor/bin/Drupal 10 Drupal 10 module Drupal 10 Upkeep and Assist Serviceinstall dynamic_image_viewer and hit Drupal Development URL /picture/1 we must always see a web page with Drupal Development ID being outputted. Render Drupal Development unique picture Okay. At the moment nothing is rendered, so what we’ll do is that we render Drupal Development uploaded unique picture first. To serve Drupal Development file we’ll use BinaryFileResponse. So let’s replace Drupal Development ImageController Drupal 10 Upkeep and Assist Service Drupal 10 Upkeep and Assist Serviceshow methodology. We’ll additionally import Drupal Development class in Drupal Development prime of Drupal Development file Drupal 10 Upkeep and Assist Service use SymfonyComponentHttpFoundationBinaryFileResponse; /** * Present a picture. * * @param MediaInterface $media * * @return BinaryFileResponse */ public operate present(MediaInterface $media) { $file = $media->field_media_image->entity; $uri = $file->getFileUri(); $headers = file_get_content_headers($file); $response = new BinaryFileResponse($uri, 200, $headers); return $response; } So what we do right here is that we seize Drupal Development File entity from Drupal Development field_media_image area on Drupal Development Media picture bundle. We get Drupal Development URI and, utilizing Drupal Development file_get_content_headers we get Drupal Development correct headers. Lastly we serve Drupal Development file again with Drupal Development correct headers to Drupal Development viewer. And if we hit Drupal Development URL once more Drupal 10 Upkeep and Assist Service Earlier than we proceed, we must always notice some issues that we’ll get again to later Drupal 10 Upkeep and Assist Service What if Drupal Development media ID will not be a Media picture? Drupal Development Company person can nonetheless entry Drupal Development media even when its unpublished. What about cache? Let’s make a hard-coded picture spinoff To switch Drupal Development picture, we’ll create a brand new occasion of ImageStyle and add a picture impact. Let’s replace Drupal Development ImageController Drupal 10 Upkeep and Assist Service Drupal 10 Upkeep and Assist Serviceshow methodology once more Drupal 10 Upkeep and Assist Service /** * Present a picture. * * @param MediaInterface $media * * @return BinaryFileResponse */ public operate present(MediaInterface $media) So what we do right here is that we create a brand new ImageStyle entity, however we do not put it aside. We give it a singular identify (however we’ll change that quickly) after which add we add a picture impact that scale and crops Drupal Development picture to a width of 600 and peak 500. After which we construct Drupal Development derivate uri and if Drupal Development file exists already, we’ll serve it and if not we’ll create a spinoff of it. There’s one large downside right here. Since we use a singular id as identify of Drupal Development picture type we’ll generate a brand new spinoff on every request which signifies that Drupal Development similar picture might be re-generated again and again. To unravel it for now, we may simply change Drupal Development $image_style = ImageStyle Drupal 10 Upkeep and Assist Service Drupal 10 Upkeep and Assist Servicecreate([ ‘name’ => uniqid(), // @TODO This will create a new image derivative on each request. to a constant value, but I left it for that reason intentionally. The reason is that I want to explicitily tell us that we need to do something about that and here is how Drupal 10 Maintenance and Support Service If we look back at the URI from Unsplash earlier &auto=format&fit=crop&w=500&q=60, these different keys are telling the code to derive the image in a certain way. We’ll use the provided keys and combine them some how in to a fitting name for the image style. For instance, we could just take the values and join them with a underscore. Like so Drupal 10 Maintenance and Support Service format_crop_500_60 and we’ll have a unique string. If the user enters the same URL with the same parameters we’ll be able to find the already existing derivative or if its another image, we’ll create a derivative for it. You’ll also notice that I removed the $headers = file_get_content_headers($file); it is because those headers are not the correct ones for ur derivatives, we’ll add them back soon. Dynamic width and height values On our second iteration of the code we’ll now add the width and height parameters, and we’ll also change the name of the image style to be dynamic. Again, we’ll update ImageController Drupal 10 Maintenance and Support Service Drupal 10 Maintenance and Support Serviceshow We’ll also import a class by adding use SymfonyComponentHttpFoundationRequest; in the top of the file. /** * Show an image. * * @param Request $request * @param MediaInterface $media * * @return BinaryFileResponse */ public function show(Request $request, MediaInterface $media) { $query = $request->query; $width = (int) $query->get(‘width’, 500); $height = (int) $query->get(‘height’, 500); // We’ll create the image style name from the provided values. $image_style_id = sprintf(‘%d_%d’, $width, $height); $file = $media->field_media_image->entity; $image_uri = $file->getFileUri(); $image_style = ImageStyle Drupal 10 Maintenance and Support Service Drupal 10 Maintenance and Support Servicecreate([ ‘name’ => $image_style_id, ]); $image_style->addImageEffect([ ‘id’ => ‘image_scale_and_crop’, ‘weight’ => 0, ‘data’ => [ ‘width’ => $width, ‘height’ => $height, ], ]); // … Remainder of code First we up to date Drupal Development methodology signature and injected Drupal Development present request. Subsequent, we’ll get Drupal Development width and peak parameters in the event that they exist and if not we fallback to one thing. We’ll construct a picture type identify of those dynamic values. With this we up to date Drupal Development identify of Drupal Development ImageStyle occasion we create which makes positive that we are able to load Drupal Development similar spinoff if Drupal Development person hits Drupal Development similar URL. Lastly we up to date Drupal Development width and peak in Drupal Development picture impact. Let’s add Drupal Development correct headers again Right here is Drupal Development up to date ImageController Drupal 10 Upkeep and Assist Service Drupal 10 Upkeep and Assist Serviceshow and present file Drupal 10 Upkeep and Assist Service src/Controller/ImageController.php <?php namespace dynamic_image_viewerController; use CoreControllerControllerBase; use mediaMediaInterface; use SymfonyComponentHttpFoundationBinaryFileResponse; use imageEntityImageStyle; use SymfonyComponentHttpFoundationRequest; use CoreImageImageFactory; use SymfonyComponentDependencyInjectionContainerInterface; /** * Class ImageController. */ class ImageController extends ControllerBase { /** * Drupal Development Company picture manufacturing facility. * * @var CoreImageImageFactory */ protected $imageFactory; /** * Constructs a ImageController object. * * @param CoreImageImageFactory $image_factory * Drupal Development Company picture manufacturing facility. */ public operate __construct(ImageFactory $image_factory) { $this->imageFactory = $image_factory; } /** * {@inheritdoc} */ public static operate create(ContainerInterface $container) { return new static( $container->get(‘picture.manufacturing facility’) ); } /** * Present a picture. * * @param Request $request * @param MediaInterface $media * * @return BinaryFileResponse */ public operate present(Request $request, MediaInterface $media) $image_style->createDerivative($image_uri, $derivative_uri); $headers = []; $picture = $this->imageFactory->get($derivative_uri); $uri = $image->getSource(); $headers += [ ‘Content-Type’ => $image->getMimeType(), ‘Content-Length’ => $image->getFileSize(), ]; $response = new BinaryFileResponse($uri, 200, $headers); return $response; } First we added a brand new dependency to our controller CoreImageImageFactory which permits us to assemble an Picture occasion, the place we are able to get meta information from Drupal Development picture, but additionally provides us a unified interface to use issues to our picture. As an illustration, we may desaturate Drupal Development picture by doing $image->desaturate(); after which resave Drupal Development file. Fow now we’re solely utilizing it to retrieve Drupal Development meta information. We’ll reap the benefits of that in Drupal Development subsequent half, once we refactor a few of Drupal Development written code and add extra flexibility to what we are able to dynamically output. If we hit Drupal Development url and add each Drupal Development width and peak parameters we’ll get one thing like this Drupal 10 Upkeep and Assist Service In Drupal Development up coming article we’ll take a greater take a look at what we’ve got, what we miss (entry management, what if a person hits Drupal Development similar URL at Drupal Development similar time), including extra results, and exploring Drupal Development use of Drupal Development Picture and toolkit APIs extra in depth. We’ll most probably take away including picture results by way of ImageStyles and solely use Drupal Development picture type for creating derivates that we are able to we are able to later apply adjustments with Drupal Development toolkit API. If you wish to proceed by yourself, check out ImageStyleDownloadController.php file in core which comprises a variety of code that we are able to re-use. Drupal 10 Growth and Assist
John Svensson Drupal 10 Upkeep and Assist Service How one can dynamically create picture kinds derivatives – Half 1

Call Us: 1(800)730-2416
Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit
Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)
John Svensson Drupal 10 Upkeep and Assist Service How one can dynamically create picture kinds derivatives – Half 1
On-Site Drupal SEO Master Setup
We make sure your site is 100% optimized (and stays that way) for the best SEO results.
With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.
This service includes:
- Pathauto install and configuration for SEO-friendly URLs.
- Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
- Install and fix all issues on the SEO checklist module.
- Install and configure XML sitemap module and submit sitemaps.
- Install and configure Google Analytics Module.
- Install and configure Yoast.
- Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
- Install and configure Schema.org Metatag.
- Configure robots.txt.
- Google Search Console setup snd configuration.
- Find & Fix H1 tags.
- Find and fix duplicate/missing meta descriptions.
- Find and fix duplicate title tags.
- Improve title, meta tags, and site descriptions.
- Optimize images for better search engine optimization. Automate where possible.
- Find and fix the missing alt and title tag for all images. Automate where possible.
- The project takes 1 week to complete.
