2

I'm using Drupal 9.2.9,

I have some migrated content that comes from an external source. there are some <img tags,

the Ckeditor image resizer is working for the images I insert into the editor the upload icon but for the images that come from the content migration, the resizer is not enabled.

enter image description here

I even tried to add height manually to the <img tag but nothing appear.

the question is that, how can I enable image resizer for all images within the ckeditor?

1 Answer 1

0

I figure out the resizer plugin works if the image has the following attributes:

  • data-entity-type="file"

  • data-entity-uuid=

So what I did, I create a batch process and go through all the content and find the image, then based on the image I load their uuid and file replaced it.

something like the following code may helps people which have similar requirement:

if (preg_match_all('~<img.*?src=["\']+(.*?)["\']+~', $node->body->value, $matches)) {
            $URIS = array_unique($matches[1]);
            foreach ($URIS as $imgUri) {
              $imgUriDecoded = urldecode($imgUri);
              $node->body->value = str_replace($imgUri, $imgUriDecoded, $node->body->value);
              $fileData = self::getFileDataByUrl($imgUriDecoded);
              $fileUuid = "xxx-just-for-resize";
              if ($fileData) {
                $fileUuid = $fileData->get('uuid')->value ?? "xxx-just-for-resize";
              }
              // skip Danger.jpg
              if ($fileUuid == "4f6db862-2c5d-4fb1-8d5b-830b89514af4") {
                continue;
              }
              $replacement = sprintf('<img data-entity-type="file" data-entity-uuid="%s"', $fileUuid);
              $node->body->value = str_replace("<img ", $replacement, $node->body->value);
              \Drupal::messenger()->addStatus($node->id());
            }
          }
      $node->setSyncing(TRUE);
      $node->save();
    }

The following file helps to get file by fileURI:

  static function getFileDataByUrl($fileURI) {
    $file_name = \Drupal::service('file_system')->basename($fileURI);
    $target_file = \Drupal::entityTypeManager()
      ->getStorage('file')
      ->loadByProperties(['filename' => $file_name]);
    $file_data = reset($target_file);
    if ($file_data) {
      return ($file_data);
    }
    else {
      return FALSE;
    }
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.