image.module 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. <?php
  2. /**
  3. * @file
  4. * Exposes global functionality for creating image styles.
  5. */
  6. use Drupal\Core\Entity\EntityInterface;
  7. use Drupal\Core\File\FileSystemInterface;
  8. use Drupal\Core\Routing\RouteMatchInterface;
  9. use Drupal\Core\StreamWrapper\StreamWrapperManager;
  10. use Drupal\Core\Url;
  11. use Drupal\field\FieldConfigInterface;
  12. use Drupal\field\FieldStorageConfigInterface;
  13. use Drupal\file\FileInterface;
  14. use Drupal\image\Entity\ImageStyle;
  15. /**
  16. * Image style constant for user presets in the database.
  17. *
  18. * @deprecated in drupal:8.1.0 and is removed from drupal:9.0.0.
  19. *
  20. * @see https://www.drupal.org/node/1820974
  21. */
  22. const IMAGE_STORAGE_NORMAL = 1;
  23. /**
  24. * Image style constant for user presets that override module-defined presets.
  25. *
  26. * @deprecated in drupal:8.1.0 and is removed from drupal:9.0.0.
  27. *
  28. * @see https://www.drupal.org/node/1820974
  29. */
  30. const IMAGE_STORAGE_OVERRIDE = 2;
  31. /**
  32. * Image style constant for module-defined presets in code.
  33. *
  34. * @deprecated in drupal:8.1.0 and is removed from drupal:9.0.0.
  35. *
  36. * @see https://www.drupal.org/node/1820974
  37. */
  38. const IMAGE_STORAGE_DEFAULT = 4;
  39. /**
  40. * Image style constant to represent an editable preset.
  41. *
  42. * @deprecated in drupal:8.1.0 and is removed from drupal:9.0.0.
  43. *
  44. * @see https://www.drupal.org/node/1820974
  45. */
  46. define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);
  47. /**
  48. * Image style constant to represent any module-based preset.
  49. *
  50. * @deprecated in drupal:8.1.0 and is removed from drupal:9.0.0.
  51. *
  52. * @see https://www.drupal.org/node/1820974
  53. */
  54. define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);
  55. /**
  56. * The name of the query parameter for image derivative tokens.
  57. */
  58. define('IMAGE_DERIVATIVE_TOKEN', 'itok');
  59. /**
  60. * Implements hook_help().
  61. */
  62. function image_help($route_name, RouteMatchInterface $route_match) {
  63. switch ($route_name) {
  64. case 'help.page.image':
  65. $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#';
  66. $output = '';
  67. $output .= '<h3>' . t('About') . '</h3>';
  68. $output .= '<p>' . t('The Image module allows you to create fields that contain image files and to configure <a href=":image_styles">Image styles</a> that can be used to manipulate the display of images. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for terminology and general information on entities, fields, and how to create and manage fields. For more information, see the <a href=":image_documentation">online documentation for the Image module</a>.', [':image_styles' => Url::fromRoute('entity.image_style.collection')->toString(), ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => $field_ui_url, ':image_documentation' => 'https://www.drupal.org/documentation/modules/image']) . '</p>';
  69. $output .= '<h3>' . t('Uses') . '</h3>';
  70. $output .= '<dt>' . t('Defining image styles') . '</dt>';
  71. $output .= '<dd>' . t('The concept of image styles is that you can upload a single image but display it in several ways; each display variation, or <em>image style</em>, is the result of applying one or more <em>effects</em> to the original image. As an example, you might upload a high-resolution image with a 4:3 aspect ratio, and display it scaled down, square cropped, or black-and-white (or any combination of these effects). The Image module provides a way to do this efficiently: you configure an image style with the desired effects on the <a href=":image">Image styles page</a>, and the first time a particular image is requested in that style, the effects are applied. The resulting image is saved, and the next time that same style is requested, the saved image is retrieved without the need to recalculate the effects. Drupal core provides several effects that you can use to define styles; others may be provided by contributed modules.', [':image' => Url::fromRoute('entity.image_style.collection')->toString()]);
  72. $output .= '<dt>' . t('Naming image styles') . '</dt>';
  73. $output .= '<dd>' . t('When you define an image style, you will need to choose a displayed name and a machine name. The displayed name is shown in administrative pages, and the machine name is used to generate the URL for accessing an image processed in that style. There are two common approaches to naming image styles: either based on the effects being applied (for example, <em>Square 85x85</em>), or based on where you plan to use it (for example, <em>Profile picture</em>).') . '</dd>';
  74. $output .= '<dt>' . t('Configuring image fields') . '</dt>';
  75. $output .= '<dd>' . t('A few of the settings for image fields are defined once when you create the field and cannot be changed later; these include the choice of public or private file storage and the number of images that can be stored in the field. The rest of the settings can be edited later; these settings include the field label, help text, allowed file extensions, image resolution restrictions, and the subdirectory in the public or private file storage where the images will be stored. The editable settings can also have different values for different entity sub-types; for instance, if your image field is used on both Page and Article content types, you can store the files in a different subdirectory for the two content types.') . '</dd>';
  76. $output .= '<dd>' . t('For accessibility and search engine optimization, all images that convey meaning on web sites should have alternate text. Drupal also allows entry of title text for images, but it can lead to confusion for screen reader users and its use is not recommended. Image fields can be configured so that alternate and title text fields are enabled or disabled; if enabled, the fields can be set to be required. The recommended setting is to enable and require alternate text and disable title text.') . '</dd>';
  77. $output .= '<dd>' . t('When you create an image field, you will need to choose whether the uploaded images will be stored in the public or private file directory defined in your settings.php file and shown on the <a href=":file-system">File system page</a>. This choice cannot be changed later. You can also configure your field to store files in a subdirectory of the public or private directory; this setting can be changed later and can be different for each entity sub-type using the field. For more information on file storage, see the <a href=":system-help">System module help page</a>.', [':file-system' => Url::fromRoute('system.file_system_settings')->toString(), ':system-help' => Url::fromRoute('help.page', ['name' => 'system'])->toString()]) . '</dd>';
  78. $output .= '<dd>' . t('The maximum file size that can be uploaded is limited by PHP settings of the server, but you can restrict it further by configuring a <em>Maximum upload size</em> in the field settings (this setting can be changed later). The maximum file size, either from PHP server settings or field configuration, is automatically displayed to users in the help text of the image field.') . '</dd>';
  79. $output .= '<dd>' . t('You can also configure a minimum and/or maximum resolution for uploaded images. Images that are too small will be rejected. Images that are to large will be resized. During the resizing the <a href="http://wikipedia.org/wiki/Exchangeable_image_file_format">EXIF data</a> in the image will be lost.') . '</dd>';
  80. $output .= '<dd>' . t('You can also configure a default image that will be used if no image is uploaded in an image field. This default can be defined for all instances of the field in the field storage settings when you create a field, and the setting can be overridden for each entity sub-type that uses the field.') . '</dd>';
  81. $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
  82. $output .= '<dd>' . t('On the <em>Manage display</em> page, you can choose the image formatter, which determines the image style used to display the image in each display mode and whether or not to display the image as a link. On the <em>Manage form display</em> page, you can configure the image upload widget, including setting the preview image style shown on the entity edit form.') . '</dd>';
  83. $output .= '</dl>';
  84. return $output;
  85. case 'entity.image_style.collection':
  86. return '<p>' . t('Image styles commonly provide thumbnail sizes by scaling and cropping images, but can also add various effects before an image is displayed. When an image is displayed with a style, a new file is created and the original image is left unchanged.') . '</p>';
  87. case 'image.effect_add_form':
  88. $effect = \Drupal::service('plugin.manager.image.effect')->getDefinition($route_match->getParameter('image_effect'));
  89. return isset($effect['description']) ? ('<p>' . $effect['description'] . '</p>') : NULL;
  90. case 'image.effect_edit_form':
  91. $effect = $route_match->getParameter('image_style')->getEffect($route_match->getParameter('image_effect'));
  92. $effect_definition = $effect->getPluginDefinition();
  93. return isset($effect_definition['description']) ? ('<p>' . $effect_definition['description'] . '</p>') : NULL;
  94. }
  95. }
  96. /**
  97. * Implements hook_theme().
  98. */
  99. function image_theme() {
  100. return [
  101. // Theme functions in image.module.
  102. 'image_style' => [
  103. // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
  104. // allows the alt attribute to be omitted in some cases. Therefore,
  105. // default the alt attribute to an empty string, but allow code using
  106. // '#theme' => 'image_style' to pass explicit NULL for it to be omitted.
  107. // Usually, neither omission nor an empty string satisfies accessibility
  108. // requirements, so it is strongly encouraged for code using '#theme' =>
  109. // 'image_style' to pass a meaningful value for the alt variable.
  110. // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  111. // - http://www.w3.org/TR/xhtml1/dtds.html
  112. // - http://dev.w3.org/html5/spec/Overview.html#alt
  113. // The title attribute is optional in all cases, so it is omitted by
  114. // default.
  115. 'variables' => [
  116. 'style_name' => NULL,
  117. 'uri' => NULL,
  118. 'width' => NULL,
  119. 'height' => NULL,
  120. 'alt' => '',
  121. 'title' => NULL,
  122. 'attributes' => [],
  123. ],
  124. ],
  125. // Theme functions in image.admin.inc.
  126. 'image_style_preview' => [
  127. 'variables' => ['style' => NULL],
  128. 'file' => 'image.admin.inc',
  129. ],
  130. 'image_anchor' => [
  131. 'render element' => 'element',
  132. 'file' => 'image.admin.inc',
  133. ],
  134. 'image_resize_summary' => [
  135. 'variables' => ['data' => NULL, 'effect' => []],
  136. ],
  137. 'image_scale_summary' => [
  138. 'variables' => ['data' => NULL, 'effect' => []],
  139. ],
  140. 'image_crop_summary' => [
  141. 'variables' => ['data' => NULL, 'effect' => []],
  142. ],
  143. 'image_scale_and_crop_summary' => [
  144. 'variables' => ['data' => NULL, 'effect' => []],
  145. ],
  146. 'image_rotate_summary' => [
  147. 'variables' => ['data' => NULL, 'effect' => []],
  148. ],
  149. // Theme functions in image.field.inc.
  150. 'image_widget' => [
  151. 'render element' => 'element',
  152. 'file' => 'image.field.inc',
  153. ],
  154. 'image_formatter' => [
  155. 'variables' => ['item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL],
  156. 'file' => 'image.field.inc',
  157. ],
  158. ];
  159. }
  160. /**
  161. * Implements hook_file_download().
  162. *
  163. * Control the access to files underneath the styles directory.
  164. */
  165. function image_file_download($uri) {
  166. $path = StreamWrapperManager::getTarget($uri);
  167. // Private file access for image style derivatives.
  168. if (strpos($path, 'styles/') === 0) {
  169. $args = explode('/', $path);
  170. // Discard "styles", style name, and scheme from the path
  171. $args = array_slice($args, 3);
  172. // Then the remaining parts are the path to the image.
  173. $original_uri = StreamWrapperManager::getScheme($uri) . '://' . implode('/', $args);
  174. // Check that the file exists and is an image.
  175. $image = \Drupal::service('image.factory')->get($uri);
  176. if ($image->isValid()) {
  177. // Check the permissions of the original to grant access to this image.
  178. $headers = \Drupal::moduleHandler()->invokeAll('file_download', [$original_uri]);
  179. // Confirm there's at least one module granting access and none denying access.
  180. if (!empty($headers) && !in_array(-1, $headers)) {
  181. return [
  182. // Send headers describing the image's size, and MIME-type.
  183. 'Content-Type' => $image->getMimeType(),
  184. 'Content-Length' => $image->getFileSize(),
  185. // By not explicitly setting them here, this uses normal Drupal
  186. // Expires, Cache-Control and ETag headers to prevent proxy or
  187. // browser caching of private images.
  188. ];
  189. }
  190. }
  191. return -1;
  192. }
  193. }
  194. /**
  195. * Implements hook_file_move().
  196. */
  197. function image_file_move(FileInterface $file, FileInterface $source) {
  198. // Delete any image derivatives at the original image path.
  199. image_path_flush($source->getFileUri());
  200. }
  201. /**
  202. * Implements hook_ENTITY_TYPE_predelete() for file entities.
  203. */
  204. function image_file_predelete(FileInterface $file) {
  205. // Delete any image derivatives of this image.
  206. image_path_flush($file->getFileUri());
  207. }
  208. /**
  209. * Clears cached versions of a specific file in all styles.
  210. *
  211. * @param $path
  212. * The Drupal file path to the original image.
  213. */
  214. function image_path_flush($path) {
  215. $styles = ImageStyle::loadMultiple();
  216. foreach ($styles as $style) {
  217. $style->flush($path);
  218. }
  219. }
  220. /**
  221. * Gets an array of image styles suitable for using as select list options.
  222. *
  223. * @param $include_empty
  224. * If TRUE a '- None -' option will be inserted in the options array.
  225. *
  226. * @return
  227. * Array of image styles both key and value are set to style name.
  228. */
  229. function image_style_options($include_empty = TRUE) {
  230. $styles = ImageStyle::loadMultiple();
  231. $options = [];
  232. if ($include_empty && !empty($styles)) {
  233. $options[''] = t('- None -');
  234. }
  235. foreach ($styles as $name => $style) {
  236. $options[$name] = $style->label();
  237. }
  238. if (empty($options)) {
  239. $options[''] = t('No defined styles');
  240. }
  241. return $options;
  242. }
  243. /**
  244. * Prepares variables for image style templates.
  245. *
  246. * Default template: image-style.html.twig.
  247. *
  248. * @param array $variables
  249. * An associative array containing:
  250. * - width: The width of the image.
  251. * - height: The height of the image.
  252. * - style_name: The name of the image style to be applied.
  253. * - uri: URI of the source image before styling.
  254. * - alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0
  255. * always require an alt attribute. The HTML 5 draft allows the alt
  256. * attribute to be omitted in some cases. Therefore, this variable defaults
  257. * to an empty string, but can be set to NULL for the attribute to be
  258. * omitted. Usually, neither omission nor an empty string satisfies
  259. * accessibility requirements, so it is strongly encouraged for code using
  260. * '#theme' => 'image_style' to pass a meaningful value for this variable.
  261. * - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  262. * - http://www.w3.org/TR/xhtml1/dtds.html
  263. * - http://dev.w3.org/html5/spec/Overview.html#alt
  264. * - title: The title text is displayed when the image is hovered in some
  265. * popular browsers.
  266. * - attributes: Associative array of additional attributes to be placed in
  267. * the img tag.
  268. */
  269. function template_preprocess_image_style(&$variables) {
  270. $style = ImageStyle::load($variables['style_name']);
  271. // Determine the dimensions of the styled image.
  272. $dimensions = [
  273. 'width' => $variables['width'],
  274. 'height' => $variables['height'],
  275. ];
  276. $style->transformDimensions($dimensions, $variables['uri']);
  277. $variables['image'] = [
  278. '#theme' => 'image',
  279. '#width' => $dimensions['width'],
  280. '#height' => $dimensions['height'],
  281. '#attributes' => $variables['attributes'],
  282. '#style_name' => $variables['style_name'],
  283. ];
  284. // If the current image toolkit supports this file type, prepare the URI for
  285. // the derivative image. If not, just use the original image resized to the
  286. // dimensions specified by the style.
  287. if ($style->supportsUri($variables['uri'])) {
  288. $variables['image']['#uri'] = $style->buildUrl($variables['uri']);
  289. }
  290. else {
  291. $variables['image']['#uri'] = $variables['uri'];
  292. // Don't render the image by default, but allow other preprocess functions
  293. // to override that if they need to.
  294. $variables['image']['#access'] = FALSE;
  295. // Inform the site builders why their image didn't work.
  296. \Drupal::logger('image')->warning('Could not apply @style image style to @uri because the style does not support it.', [
  297. '@style' => $style->label(),
  298. '@uri' => $variables['uri'],
  299. ]);
  300. }
  301. if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
  302. $variables['image']['#alt'] = $variables['alt'];
  303. }
  304. if (isset($variables['title']) || array_key_exists('title', $variables)) {
  305. $variables['image']['#title'] = $variables['title'];
  306. }
  307. }
  308. /**
  309. * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
  310. *
  311. * @param $value
  312. * @param $current_pixels
  313. * @param $new_pixels
  314. */
  315. function image_filter_keyword($value, $current_pixels, $new_pixels) {
  316. switch ($value) {
  317. case 'top':
  318. case 'left':
  319. return 0;
  320. case 'bottom':
  321. case 'right':
  322. return $current_pixels - $new_pixels;
  323. case 'center':
  324. return $current_pixels / 2 - $new_pixels / 2;
  325. }
  326. return $value;
  327. }
  328. /**
  329. * Implements hook_entity_presave().
  330. *
  331. * Transforms default image of image field from array into single value at save.
  332. */
  333. function image_entity_presave(EntityInterface $entity) {
  334. // Get the default image settings, return if not saving an image field storage
  335. // or image field entity.
  336. $default_image = [];
  337. if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
  338. $default_image = $entity->getSetting('default_image');
  339. }
  340. else {
  341. return;
  342. }
  343. if ($entity->isSyncing()) {
  344. return;
  345. }
  346. $uuid = $default_image['uuid'];
  347. if ($uuid) {
  348. $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
  349. if ($uuid != $original_uuid) {
  350. $file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid);
  351. if ($file) {
  352. $image = \Drupal::service('image.factory')->get($file->getFileUri());
  353. $default_image['width'] = $image->getWidth();
  354. $default_image['height'] = $image->getHeight();
  355. }
  356. else {
  357. $default_image['uuid'] = NULL;
  358. }
  359. }
  360. }
  361. // Both FieldStorageConfigInterface and FieldConfigInterface have a
  362. // setSetting() method.
  363. $entity->setSetting('default_image', $default_image);
  364. }
  365. /**
  366. * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
  367. */
  368. function image_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
  369. if ($field_storage->getType() != 'image') {
  370. // Only act on image fields.
  371. return;
  372. }
  373. $prior_field_storage = $field_storage->original;
  374. // The value of a managed_file element can be an array if #extended == TRUE.
  375. $uuid_new = $field_storage->getSetting('default_image')['uuid'];
  376. $uuid_old = $prior_field_storage->getSetting('default_image')['uuid'];
  377. $file_new = $uuid_new ? \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid_new) : FALSE;
  378. if ($uuid_new != $uuid_old) {
  379. // Is there a new file?
  380. if ($file_new) {
  381. $file_new->status = FILE_STATUS_PERMANENT;
  382. $file_new->save();
  383. \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field_storage->uuid());
  384. }
  385. // Is there an old file?
  386. if ($uuid_old && ($file_old = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid_old))) {
  387. \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field_storage->uuid());
  388. }
  389. }
  390. // If the upload destination changed, then move the file.
  391. if ($file_new && (StreamWrapperManager::getScheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
  392. $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
  393. \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
  394. file_move($file_new, $directory . $file_new->getFilename());
  395. }
  396. }
  397. /**
  398. * Implements hook_ENTITY_TYPE_update() for 'field_config'.
  399. */
  400. function image_field_config_update(FieldConfigInterface $field) {
  401. $field_storage = $field->getFieldStorageDefinition();
  402. if ($field_storage->getType() != 'image') {
  403. // Only act on image fields.
  404. return;
  405. }
  406. $prior_instance = $field->original;
  407. $uuid_new = $field->getSetting('default_image')['uuid'];
  408. $uuid_old = $prior_instance->getSetting('default_image')['uuid'];
  409. // If the old and new files do not match, update the default accordingly.
  410. $file_new = $uuid_new ? \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid_new) : FALSE;
  411. if ($uuid_new != $uuid_old) {
  412. // Save the new file, if present.
  413. if ($file_new) {
  414. $file_new->status = FILE_STATUS_PERMANENT;
  415. $file_new->save();
  416. \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
  417. }
  418. // Delete the old file, if present.
  419. if ($uuid_old && ($file_old = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid_old))) {
  420. \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field->uuid());
  421. }
  422. }
  423. // If the upload destination changed, then move the file.
  424. if ($file_new && (StreamWrapperManager::getScheme($file_new->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
  425. $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
  426. \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
  427. file_move($file_new, $directory . $file_new->getFilename());
  428. }
  429. }
  430. /**
  431. * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
  432. */
  433. function image_field_storage_config_delete(FieldStorageConfigInterface $field) {
  434. if ($field->getType() != 'image') {
  435. // Only act on image fields.
  436. return;
  437. }
  438. // The value of a managed_file element can be an array if #extended == TRUE.
  439. $uuid = $field->getSetting('default_image')['uuid'];
  440. if ($uuid && ($file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid))) {
  441. \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
  442. }
  443. }
  444. /**
  445. * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
  446. */
  447. function image_field_config_delete(FieldConfigInterface $field) {
  448. $field_storage = $field->getFieldStorageDefinition();
  449. if ($field_storage->getType() != 'image') {
  450. // Only act on image fields.
  451. return;
  452. }
  453. // The value of a managed_file element can be an array if #extended == TRUE.
  454. $uuid = $field->getSetting('default_image')['uuid'];
  455. // Remove the default image when the instance is deleted.
  456. if ($uuid && ($file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid))) {
  457. \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
  458. }
  459. }