diff --git a/core/includes/common.inc b/core/includes/common.inc
index 323a666..8e8fd24 100644
--- a/core/includes/common.inc
+++ b/core/includes/common.inc
@@ -16,11 +16,11 @@
 use Drupal\Core\Cache\Cache;
 use Drupal\Core\Render\Element\Link;
 use Drupal\Core\Render\Markup;
-use Drupal\Core\StringTranslation\TranslatableMarkup;
 use Drupal\Core\PhpStorage\PhpStorageFactory;
 use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
 use Drupal\Core\Render\BubbleableMetadata;
 use Drupal\Core\Render\Element;
+use Drupal\Core\Utility\FormatBytesSize;
 
 /**
  * @defgroup php_wrappers PHP wrapper functions
@@ -246,43 +246,13 @@ function check_url($uri) {
  *
  * @return \Drupal\Core\StringTranslation\TranslatableMarkup
  *   A translated string representation of the size.
+ *
+ * @deprecated in Drupal 8.4.x, will be removed before Drupal 9.0.0.
+ *   Use \Drupal\Core\Utility\FormatBytesSize::format($size, $langcode)
+ *   instead.
  */
 function format_size($size, $langcode = NULL) {
-  if ($size < Bytes::KILOBYTE) {
-    return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', [], ['langcode' => $langcode]);
-  }
-  else {
-    $size = $size / Bytes::KILOBYTE; // Convert bytes to kilobytes.
-    $units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
-    foreach ($units as $unit) {
-      if (round($size, 2) >= Bytes::KILOBYTE) {
-        $size = $size / Bytes::KILOBYTE;
-      }
-      else {
-        break;
-      }
-    }
-    $args = ['@size' => round($size, 2)];
-    $options = ['langcode' => $langcode];
-    switch ($unit) {
-      case 'KB':
-        return new TranslatableMarkup('@size KB', $args, $options);
-      case 'MB':
-        return new TranslatableMarkup('@size MB', $args, $options);
-      case 'GB':
-        return new TranslatableMarkup('@size GB', $args, $options);
-      case 'TB':
-        return new TranslatableMarkup('@size TB', $args, $options);
-      case 'PB':
-        return new TranslatableMarkup('@size PB', $args, $options);
-      case 'EB':
-        return new TranslatableMarkup('@size EB', $args, $options);
-      case 'ZB':
-        return new TranslatableMarkup('@size ZB', $args, $options);
-      case 'YB':
-        return new TranslatableMarkup('@size YB', $args, $options);
-    }
-  }
+  return FormatBytesSize::format($size, $langcode);
 }
 
 /**
diff --git a/core/lib/Drupal/Component/Utility/Bytes.php b/core/lib/Drupal/Component/Utility/Bytes.php
index d625b12..a4acda2 100644
--- a/core/lib/Drupal/Component/Utility/Bytes.php
+++ b/core/lib/Drupal/Component/Utility/Bytes.php
@@ -39,4 +39,34 @@ public static function toInt($size) {
     }
   }
 
+  /**
+   * Returns unit of measurement and size of a byte quantity.
+   *
+   * This method returns a BytesUnitAndSize value object containing unit of
+   * measurement and a float representing, rounded to 2 decimals, the size
+   * expressed in the unit of measurement. If you need to get a translation
+   * aware string or object, use format_size().
+   *
+   * @param float $size
+   *   A quantity of bytes.
+   *
+   * @return \Drupal\Component\Utility\BytesUnitAndSize|null
+   *   NULL if the input value is negative, a
+   *   \Drupal\Component\Utility\BytesUnitAndSize value object otherwise.
+   *
+   * @see format_size
+   */
+  public static function toUnitAndSize($size) {
+    if ($size < 0) {
+      return NULL;
+    }
+    foreach (['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) {
+      if (round($size, 2) < self::KILOBYTE) {
+        break;
+      }
+      $size = $size / self::KILOBYTE;
+    }
+    return new BytesUnitAndSize(round($size, 2), $unit);
+  }
+
 }
diff --git a/core/lib/Drupal/Component/Utility/BytesUnitAndSize.php b/core/lib/Drupal/Component/Utility/BytesUnitAndSize.php
new file mode 100644
index 0000000..915d30d
--- /dev/null
+++ b/core/lib/Drupal/Component/Utility/BytesUnitAndSize.php
@@ -0,0 +1,63 @@
+<?php
+
+namespace Drupal\Component\Utility;
+
+/**
+ * A value object class to store a bytes quantity with an unit of measurement.
+ */
+class BytesUnitAndSize {
+
+  /**
+   * The bytes quantity.
+   *
+   * @var float
+   */
+  protected $size;
+
+  /**
+   * The unit of measurement of this bytes quantity.
+   *
+   * @var string
+   */
+  protected $unit;
+
+  /**
+   * Constructs a new BytesUnitAndSize object.
+   *
+   * @param int $size
+   *   The bytes quantity.
+   * @param string $unit
+   *   The unit of measurement of this bytes quantity.
+   *
+   * @throws \InvalidArgumentException
+   *   When an invalid parameter is passed in.
+   */
+  public function __construct($size, $unit) {
+    if (!is_numeric($size) || $size < 0) {
+      throw new \InvalidArgumentException("Invalid size ({$size}) specified for a BytesUnitAndSize object");
+    }
+    $this->size = $size;
+    $this->unit = $unit;
+  }
+
+  /**
+   * Gets the bytes quantity.
+   *
+   * @return int
+   *   The bytes quantity.
+   */
+  public function getSize() {
+    return $this->size;
+  }
+
+  /**
+   * Gets the unit of measurement of this bytes quantity.
+   *
+   * @return string
+   *   The unit of measurement of this bytes quantity.
+   */
+  public function getUnit() {
+    return $this->unit;
+  }
+
+}
diff --git a/core/lib/Drupal/Component/Utility/Environment.php b/core/lib/Drupal/Component/Utility/Environment.php
index bfee60c..05db4c4 100644
--- a/core/lib/Drupal/Component/Utility/Environment.php
+++ b/core/lib/Drupal/Component/Utility/Environment.php
@@ -4,6 +4,9 @@
 
 /**
  * Provides PHP environment helper methods.
+ *
+ * @deprecated in Drupal 8.4.x, will be removed before Drupal 9.0.0. Use
+ *   \Drupal\Component\Utility\EnvironmentMemory instead.
  */
 class Environment {
 
@@ -23,18 +26,21 @@ class Environment {
    * @return bool
    *   TRUE if there is sufficient memory to allow the operation, or FALSE
    *   otherwise.
+   *
+   * @deprecated in Drupal 8.4.x, will be removed before Drupal 9.0.0.
+   *   Use \Drupal\Component\Utility\EnvironmentMemory:
+   *   @code
+   *     $memory = new EnvironmentMemory();
+   *     $memory->setTotal($memory_limit); // optional
+   *     $enough_memory = $memory->checkLimit($required);
+   *   @endcode
    */
   public static function checkMemoryLimit($required, $memory_limit = NULL) {
-    if (!isset($memory_limit)) {
-      $memory_limit = ini_get('memory_limit');
+    $memory = new EnvironmentMemory();
+    if ($memory_limit) {
+      $memory->setTotal($memory_limit);
     }
-
-    // There is sufficient memory if:
-    // - No memory limit is set.
-    // - The memory limit is set to unlimited (-1).
-    // - The memory limit is greater than or equal to the memory required for
-    //   the operation.
-    return ((!$memory_limit) || ($memory_limit == -1) || (Bytes::toInt($memory_limit) >= Bytes::toInt($required)));
+    return $memory->checkLimit($required);
   }
 
 }
diff --git a/core/lib/Drupal/Component/Utility/EnvironmentMemory.php b/core/lib/Drupal/Component/Utility/EnvironmentMemory.php
new file mode 100644
index 0000000..6d900d4
--- /dev/null
+++ b/core/lib/Drupal/Component/Utility/EnvironmentMemory.php
@@ -0,0 +1,125 @@
+<?php
+
+namespace Drupal\Component\Utility;
+
+/**
+ * Provides PHP memory helper class.
+ */
+class EnvironmentMemory {
+
+  /**
+   * Constant representing unlimited memory.
+   */
+  const UNLIMITED = -1;
+
+  /**
+   * Total memory, in bytes, available to PHP.
+   *
+   * Will be set to static::UNLIMITED when no memory limit is set or it is set
+   * to unlimited.
+   *
+   * @var int
+   */
+  protected $total;
+
+  /**
+   * Gets the total memory, in bytes, available to PHP.
+   *
+   * @return int
+   *   The total memory, in bytes, available to PHP. Returns static::UNLIMITED
+   *   when no memory limit is set or it is set to unlimited.
+   */
+  public function getTotal() {
+    if (!isset($this->total)) {
+      $this->setTotal();
+    }
+    return $this->total;
+  }
+
+  /**
+   * Sets the total memory, in bytes, available to PHP.
+   *
+   * @param int|string|null $size
+   *   (optional) The total memory available to PHP, expressed as a number of
+   *   bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
+   *   6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
+   *   memory_limit will be used. Defaults to NULL.
+   *
+   * @return $this
+   *
+   * @see https://en.wikipedia.org/wiki/Binary_prefix
+   */
+  public function setTotal($size = NULL) {
+    if (!$size) {
+      $size = ini_get('memory_limit');
+    }
+    // ini_get() may return -1 or null for memory_limit to indicate there is no
+    // limit set. We check that explicitly, and in that case map the result to
+    // the internal constant static::UNLIMITED.
+    $this->total = (!$size || (int) $size === -1) ? static::UNLIMITED : Bytes::toInt($size);
+  }
+
+  /**
+   * Gets the amount of memory, in bytes, currently allocated to PHP.
+   *
+   * @return int
+   *   The memory, in bytes, currently used by PHP.
+   */
+  public function getUsed() {
+    return memory_get_usage(TRUE);
+  }
+
+  /**
+   * Gets the amount of memory, in bytes, currently free to be used by PHP.
+   *
+   * @return int
+   *   The amount of memory, in bytes, free for use by PHP. Returns
+   *   static::UNLIMITED when no memory limit is set or it is set to unlimited.
+   */
+  public function getFree() {
+    return $this->getTotal() === static::UNLIMITED ? static::UNLIMITED : $this->getTotal() - $this->getUsed();
+  }
+
+  /**
+   * Compares the memory required for an operation to the total memory.
+   *
+   * @param string $required
+   *   The memory required for the operation, expressed as a number of bytes
+   *   with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB,
+   *   8bytes, 9mbytes).
+   *
+   * @return bool
+   *   TRUE if there is sufficient memory to allow the requirements, or FALSE
+   *   otherwise.
+   *
+   * @see https://en.wikipedia.org/wiki/Binary_prefix
+   */
+  public function checkLimit($required) {
+    $memory_limit = $this->getTotal();
+    // There is sufficient memory if:
+    // - No memory limit is set, or set to unlimited (static::UNLIMITED).
+    // - The memory limit is greater than or equal to the memory required for
+    //   the operation.
+    return $memory_limit === static::UNLIMITED || $memory_limit >= Bytes::toInt($required);
+  }
+
+  /**
+   * Compares the memory required for an operation to the remaining memory.
+   *
+   * @param string $required
+   *   The memory required for the operation, expressed as a number of bytes
+   *   with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB,
+   *   8bytes, 9mbytes).
+   *
+   * @return bool
+   *   TRUE if there is sufficient remaining memory to allow the requirements,
+   *   or FALSE otherwise.
+   *
+   * @see https://en.wikipedia.org/wiki/Binary_prefix
+   */
+  public function checkAvailable($required) {
+    $memory_limit = $this->getTotal();
+    return $memory_limit === static::UNLIMITED || $this->getFree() >= Bytes::toInt($required);
+  }
+
+}
diff --git a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitBase.php b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitBase.php
index 72f3d29..fe950b0 100644
--- a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitBase.php
+++ b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitBase.php
@@ -132,6 +132,10 @@ public function apply($operation, array $arguments = []) {
       $this->logger->warning($e->getMessage(), []);
       return FALSE;
     }
+    catch (\RuntimeException $e) {
+      $this->logger->warning($e->getMessage(), []);
+      return FALSE;
+    }
   }
 
 }
diff --git a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationBase.php b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationBase.php
index c9a93ff..ebeee3a 100644
--- a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationBase.php
+++ b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationBase.php
@@ -185,6 +185,9 @@ protected function validateArguments(array $arguments) {
    *
    * @return bool
    *   TRUE if the operation was performed successfully, FALSE otherwise.
+   *
+   * @throws \RuntimeException
+   *   If the operation can not be performed.
    */
   abstract protected function execute(array $arguments);
 
diff --git a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationInterface.php b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationInterface.php
index 0d84be4..c793c70 100644
--- a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationInterface.php
+++ b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationInterface.php
@@ -29,6 +29,8 @@
    *
    * @throws \InvalidArgumentException
    *   If one or more of the arguments are not valid.
+   * @throws \RuntimeException
+   *   If the operation can not be performed.
    */
   public function apply(array $arguments);
 
diff --git a/core/lib/Drupal/Core/Utility/FormatBytesSize.php b/core/lib/Drupal/Core/Utility/FormatBytesSize.php
new file mode 100644
index 0000000..a3e4085
--- /dev/null
+++ b/core/lib/Drupal/Core/Utility/FormatBytesSize.php
@@ -0,0 +1,53 @@
+<?php
+
+namespace Drupal\Core\Utility;
+
+use Drupal\Component\Utility\Bytes;
+use Drupal\Core\StringTranslation\TranslatableMarkup;
+use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
+
+/**
+ * Drupal class to generate a string representation for a given byte count.
+ */
+class FormatBytesSize {
+
+  /**
+   * Generates a string representation for the given byte count.
+   *
+   * @param int $size
+   *   A size in bytes.
+   * @param string $langcode
+   *   (Optional) Language code to translate to a language other than what is
+   *   used to display the page.
+   *
+   * @return \Drupal\Core\StringTranslation\TranslatableMarkup|\Drupal\Core\StringTranslation\PluralTranslatableMarkup
+   *   A translated string representation of the size.
+   */
+  public static function format($size, $langcode = NULL) {
+    $options = ['langcode' => $langcode];
+    /** @var \Drupal\Component\Utility\BytesUnitAndSize $value */
+    $value = Bytes::toUnitAndSize($size);
+    $args = ['@size' => $value->getSize()];
+    switch ($value->getUnit()) {
+      case 'B':
+        return new PluralTranslatableMarkup($value->getSize(), '1 byte', '@count bytes', [], $options);
+      case 'KB':
+        return new TranslatableMarkup('@size KB', $args, $options);
+      case 'MB':
+        return new TranslatableMarkup('@size MB', $args, $options);
+      case 'GB':
+        return new TranslatableMarkup('@size GB', $args, $options);
+      case 'TB':
+        return new TranslatableMarkup('@size TB', $args, $options);
+      case 'PB':
+        return new TranslatableMarkup('@size PB', $args, $options);
+      case 'EB':
+        return new TranslatableMarkup('@size EB', $args, $options);
+      case 'ZB':
+        return new TranslatableMarkup('@size ZB', $args, $options);
+      case 'YB':
+        return new TranslatableMarkup('@size YB', $args, $options);
+    }
+  }
+
+}
diff --git a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
index 818c5b5..97b11c9 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
@@ -2,7 +2,9 @@
 
 namespace Drupal\system\Plugin\ImageToolkit;
 
+use Drupal\Component\Utility\Bytes;
 use Drupal\Component\Utility\Color;
+use Drupal\Component\Utility\EnvironmentMemory;
 use Drupal\Component\Utility\Unicode;
 use Drupal\Core\Config\ConfigFactoryInterface;
 use Drupal\Core\Form\FormStateInterface;
@@ -134,7 +136,9 @@ public function setResource($resource) {
    */
   public function getResource() {
     if (!is_resource($this->resource)) {
-      $this->load();
+      if (!$this->load()) {
+        return NULL;
+      };
     }
     return $this->resource;
   }
@@ -176,6 +180,24 @@ protected function load() {
       return FALSE;
     }
 
+    // Check if enough memory is available.
+    $memory = $this->isMemoryAvailable($this->getWidth(), $this->getHeight());
+    if ($memory !== TRUE) {
+      // If not, it is not possible to load the GD resource. Mark the image as
+      // invalid, to avoid useless attempts to manipulate it.
+      $this->preLoadInfo = NULL;
+      $this->logger->error("Not enough memory (required: %req_size %req_unit, free: %free_size %free_unit, total: %tot_size %tot_unit) to load image '%file'", [
+        '%req_size' => $memory['required']->getSize(),
+        '%req_unit' => $memory['required']->getUnit(),
+        '%free_size' => $memory['free']->getSize(),
+        '%free_unit' => $memory['free']->getUnit(),
+        '%tot_size' => $memory['total']->getSize(),
+        '%tot_unit' => $memory['total']->getUnit(),
+        '%file' => $this->getSource()
+      ]);
+      return FALSE;
+    }
+
     $function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);
     if (function_exists($function) && $resource = $function($this->getSource())) {
       $this->setResource($resource);
@@ -443,4 +465,53 @@ protected static function supportedTypes() {
     return [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF];
   }
 
+  /**
+   * Checks that there is enough memory available for a GD operation.
+   *
+   * GD functions that create new GD resources will fail fatally if there is
+   * not enough memory available to perform the operation. This method checks
+   * if there is enough memory available before calling the GD function. The
+   * algorithm implemented follows the one described in
+   * http://php.net/manual/en/function.imagecreatetruecolor.php#99623.
+   *
+   * @param int $width
+   *   The image width.
+   * @param int $height
+   *   The image height.
+   * @param int $bits_per_pixel
+   *   (optional) The bits per pixel of the image. Defaults to 31, as GD
+   *   internally manages RGB with 8 bits each color + 7 bits for the alpha
+   *   channel.
+   * @param float $tweak_factor
+   *   (optional) A tweak factor as described in
+   *   http://php.net/manual/en/function.imagecreatetruecolor.php#99623.
+   *   Defaults to 1.7.
+   *
+   * @return TRUE|\Drupal\Component\Utility\BytesUnitAndSize[]
+   *   TRUE if the memory is available. If not enough memory is available, an
+   *   associative array of BytesUnitAndSize objects with the following keys:
+   *   - 'required': information about required memory.
+   *   - 'free': information about unused memory, free for PHP to allocate.
+   *   - 'total': information about total memory available for PHP.
+   *
+   * @see http://php.net/manual/en/function.imagecreatetruecolor.php#99623
+   */
+  public function isMemoryAvailable($width, $height, $bits_per_pixel = 31, $tweak_factor = 1.7) {
+    // Bytes per pixel need to accommodate enough bytes to store all the bits
+    // needed.
+    $bytes_per_pixel = ceil($bits_per_pixel / 8);
+    $required = (int) ($width * $height * $bytes_per_pixel * $tweak_factor);
+    $memory = new EnvironmentMemory();
+    if ($memory->checkAvailable($required)) {
+      return TRUE;
+    }
+    else {
+      return [
+        'required' => Bytes::toUnitAndSize($required),
+        'free' => Bytes::toUnitAndSize($memory->getFree()),
+        'total' => Bytes::toUnitAndSize($memory->getTotal()),
+      ];
+    }
+  }
+
 }
diff --git a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php
index cb57cc4..18bfd69 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php
@@ -79,6 +79,12 @@ protected function validateArguments(array $arguments) {
    * {@inheritdoc}
    */
   protected function execute(array $arguments) {
+    // Check if enough memory is available.
+    $memory = $this->getToolkit()->isMemoryAvailable($arguments['width'], $arguments['height']);
+    if ($memory !== TRUE) {
+      throw new \RuntimeException("Not enough memory (required: {$memory['required']->getSize()} {$memory['required']->getUnit()}, free: {$memory['free']->getSize()} {$memory['free']->getUnit()}, total: {$memory['total']->getSize()} {$memory['total']->getUnit()}) to perform the image '{$this->getPluginId()}' operation");
+    }
+
     // Get the image type.
     $type = $this->getToolkit()->extensionToImageType($arguments['extension']);
 
diff --git a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php
index 4335612..83b1242 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php
@@ -3,6 +3,7 @@
 namespace Drupal\system\Plugin\ImageToolkit\Operation\gd;
 
 use Drupal\Component\Utility\Color;
+use Drupal\Component\Utility\Rectangle;
 
 /**
  * Defines GD2 rotate operation.
@@ -93,6 +94,14 @@ protected function execute(array $arguments) {
       return FALSE;
     }
 
+    // Check if enough memory is available.
+    $rect = new Rectangle($this->getToolkit()->getWidth(), $this->getToolkit()->getHeight());
+    $rect = $rect->rotate($arguments['degrees']);
+    $memory = $this->getToolkit()->isMemoryAvailable($rect->getBoundingWidth(), $rect->getBoundingHeight());
+    if ($memory !== TRUE) {
+      throw new \RuntimeException("Not enough memory (required: {$memory['required']->getSize()} {$memory['required']->getUnit()}, free: {$memory['free']->getSize()} {$memory['free']->getUnit()}, total: {$memory['total']->getSize()} {$memory['total']->getUnit()}) to perform the image '{$this->getPluginId()}' operation");
+    }
+
     // Stores the original GD resource.
     $original_res = $this->getToolkit()->getResource();
 
diff --git a/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php b/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php
new file mode 100644
index 0000000..35adc72
--- /dev/null
+++ b/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php
@@ -0,0 +1,213 @@
+<?php
+
+namespace Drupal\Tests\system\Unit\Plugin\ImageToolkit;
+
+use Drupal\Component\Utility\BytesUnitAndSize;
+use Drupal\Core\Image\Image;
+use Drupal\Core\ImageToolkit\ImageToolkitInterface;
+use Drupal\Tests\UnitTestCase;
+
+/**
+ * Tests the GDToolkit class.
+ *
+ * @coversDefaultClass \Drupal\system\Plugin\ImageToolkit\GDToolkit
+ * @group Image
+ */
+class GdToolkitTest extends UnitTestCase {
+
+  /**
+   * Path of the image file used for testing.
+   *
+   * @var string
+   */
+  protected $source;
+
+  /**
+   * Image object under test.
+   *
+   * @var \Drupal\Core\Image\Image
+   */
+  protected $image;
+
+  /**
+   * The GD Image toolkit used for testing.
+   *
+   * @var \Drupal\Core\ImageToolkit\ImageToolkitInterface|\PHPUnit_Framework_MockObject_MockObject
+   */
+  protected $toolkit;
+
+  /**
+   * The GD Image toolkit operation used for testing.
+   *
+   * @var \Drupal\Core\ImageToolkit\ImageToolkitOperationInterface
+   */
+  protected $toolkitOperation;
+
+  /**
+   * Result for GDToolkit::isMemoryAvailable, for mocking.
+   *
+   * @var \Drupal\Component\Utility\BytesUnitAndSize[]
+   */
+  protected $availableMemoryFalse;
+
+  /**
+   * @inheritdoc
+   */
+  protected function setUp() {
+    // Use the Druplicon image.
+    $this->source = __DIR__ . '/../../../../../../simpletest/files/image-test.jpg';
+    $this->availableMemoryFalse =  [
+      'free' => new BytesUnitAndSize(10, 'MB'),
+      'required' => new BytesUnitAndSize(20, 'MB'),
+      'total' => new BytesUnitAndSize(20, 'MB'),
+    ];
+  }
+
+  /**
+   * Sets the GD toolkit mock.
+   *
+   * @param array $stubs
+   *   (optional) Array containing methods to be replaced with stubs.
+   */
+  protected function setToolkitMock(array $stubs = []) {
+    $logger = $this->getMock('Psr\Log\LoggerInterface');
+    $operation_manager = $this->getMock('Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface');
+    $config_factory = $this->getMock('Drupal\Core\Config\ConfigFactoryInterface');
+    $stream_wrapper_manager = $this->getMock('Drupal\Core\StreamWrapper\StreamWrapperManagerInterface');
+    $stubs = array_merge(['getPluginId'], $stubs);
+    $mock_builder = $this->getMockBuilder('Drupal\system\Plugin\ImageToolkit\GDToolkit');
+    $this->toolkit = $mock_builder
+      ->setConstructorArgs([[], '', [], $operation_manager, $logger, $config_factory, $stream_wrapper_manager])
+      ->setMethods($stubs)
+      ->getMock();
+    $this->toolkit->expects($this->any())
+      ->method('getPluginId')
+      ->will($this->returnValue('gd'));
+  }
+
+  /**
+   * Sets the GD toolkit operation mock.
+   *
+   * @param string $class_name
+   *   The name of the GD toolkit operation class to be mocked.
+   * @param ImageToolkitInterface $toolkit
+   *   The image toolkit object.
+   * @param array $stubs
+   *   (optional) Array containing methods to be replaced with stubs.
+   */
+  protected function setToolkitOperationMock($class_name, ImageToolkitInterface $toolkit, array $stubs = []) {
+    $logger = $this->getMock('Psr\Log\LoggerInterface');
+    $mock_builder = $this->getMockBuilder('Drupal\system\Plugin\ImageToolkit\Operation\gd\\' . $class_name);
+    $this->toolkitOperation = $mock_builder
+      ->setMethods($stubs)
+      ->setConstructorArgs([[], '', [], $toolkit, $logger])
+      ->getMock();
+  }
+
+  /**
+   * Mock function for GDToolkit::apply().
+   */
+  public function applyMockedOperation($operation, array $arguments = []) {
+    return $this->toolkitOperation->apply($arguments);
+  }
+
+  /**
+   * Test loading an image.
+   *
+   * @covers ::load
+   */
+  public function testLoad() {
+    $this->setToolkitMock(['isMemoryAvailable']);
+    $this->toolkit->expects($this->any())
+      ->method('isMemoryAvailable')
+      ->will($this->returnValue(TRUE));
+
+    $this->image = new Image($this->toolkit, $this->source);
+    $this->assertTrue(is_resource($this->image->getToolkit()->getResource()));
+    $this->assertTrue($this->image->isValid());
+    $this->assertEquals(40, $this->image->getWidth());
+    $this->assertEquals(20, $this->image->getHeight());
+  }
+
+  /**
+   * Simulates not enough memory to load an image.
+   *
+   * @covers ::load
+   */
+  public function testNotEnoughMemoryOnLoad() {
+    $this->setToolkitMock(['isMemoryAvailable']);
+    $this->toolkit->expects($this->any())
+      ->method('isMemoryAvailable')
+      ->will($this->returnValue($this->availableMemoryFalse));
+
+    // Getting image from file validates the Image object, since GD toolkit is
+    // lazy loading the resource.
+    $this->image = new Image($this->toolkit, $this->source);
+    $this->assertTrue($this->image->isValid());
+    // Trying to get GD resource without enough memory yields to NULL resource
+    // and invalidates Image object.
+    $this->assertFalse(is_resource($this->image->getToolkit()->getResource()));
+    $this->assertFalse($this->image->isValid());
+    $this->assertEquals(NULL, $this->image->getWidth());
+    $this->assertEquals(NULL, $this->image->getHeight());
+  }
+
+  /**
+   * Simulates not enough memory to create a new image.
+   *
+   * @covers \Drupal\system\Plugin\ImageToolkit\Operation\gd\CreateNew::execute
+   *
+   * @expectedException \RuntimeException
+   */
+  public function testNotEnoughMemoryOnCreateNew() {
+    $this->setToolkitMock(['isMemoryAvailable', 'getToolkitOperation', 'apply']);
+    $this->setToolkitOperationMock('CreateNew', $this->toolkit);
+    $this->toolkit->expects($this->any())
+      ->method('isMemoryAvailable')
+      ->will($this->onConsecutiveCalls(TRUE, $this->availableMemoryFalse));
+    $this->toolkit->expects($this->any())
+      ->method('getToolkitOperation')
+      ->will($this->returnValue($this->toolkitOperation));
+    $this->toolkit->expects($this->once())
+      ->method('apply')
+      ->will($this->returnCallback([$this, 'applyMockedOperation']));
+
+    $this->image = new Image($this->toolkit, $this->source);
+    // Get the GD resource to force GDToolkit::load, where the memory check is
+    // mocked to succeed.
+    $this->assertTrue(is_resource($this->image->getToolkit()->getResource()));
+    // Try the Image::createNew operation, where the memory check is mocked
+    // to fail. Expected a runtime exception.
+    $this->image->createNew(100, 200);
+  }
+
+  /**
+   * Simulates not enough memory to rotate an image.
+   *
+   * @covers \Drupal\system\Plugin\ImageToolkit\Operation\gd\Rotate::execute
+   *
+   * @expectedException \RuntimeException
+   */
+  public function testNotEnoughMemoryOnRotate() {
+    $this->setToolkitMock(['isMemoryAvailable', 'getToolkitOperation', 'apply']);
+    $this->setToolkitOperationMock('Rotate', $this->toolkit);
+    $this->toolkit->expects($this->any())
+      ->method('isMemoryAvailable')
+      ->will($this->onConsecutiveCalls(TRUE, $this->availableMemoryFalse));
+    $this->toolkit->expects($this->any())
+      ->method('getToolkitOperation')
+      ->will($this->returnValue($this->toolkitOperation));
+    $this->toolkit->expects($this->once())
+      ->method('apply')
+      ->will($this->returnCallback([$this, 'applyMockedOperation']));
+
+    $this->image = new Image($this->toolkit, $this->source);
+    // Get the GD resource to force GDToolkit::load, where the memory check is
+    // mocked to succeed.
+    $this->assertTrue(is_resource($this->image->getToolkit()->getResource()));
+    // Try the Image::rotate operation, where the memory check is mocked
+    // to fail. Expected a runtime exception.
+    $this->image->rotate(120);
+  }
+
+}
diff --git a/core/tests/Drupal/KernelTests/Core/Common/SizeTest.php b/core/tests/Drupal/KernelTests/Core/Common/SizeTest.php
index 9829b26..c01836f 100644
--- a/core/tests/Drupal/KernelTests/Core/Common/SizeTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Common/SizeTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\KernelTests\Core\Common;
 
 use Drupal\Component\Utility\Bytes;
+use Drupal\Core\Utility\FormatBytesSize;
 use Drupal\KernelTests\KernelTestBase;
 
 /**
@@ -19,6 +20,7 @@ protected function setUp() {
     parent::setUp();
     $kb = Bytes::KILOBYTE;
     $this->exactTestCases = [
+      '0 bytes' => 0,
       '1 byte' => 1,
       '1 KB'   => $kb,
       '1 MB'   => $kb * $kb,
@@ -32,6 +34,7 @@ protected function setUp() {
     $this->roundedTestCases = [
       '2 bytes' => 2,
       '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
+      '3.77 GB' => 4053371676, // not 3.78 GB as before #2157945
       round(3623651 / ($this->exactTestCases['1 MB']), 2) . ' MB' => 3623651, // megabytes
       round(67234178751368124 / ($this->exactTestCases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
       round(235346823821125814962843827 / ($this->exactTestCases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
@@ -39,13 +42,13 @@ protected function setUp() {
   }
 
   /**
-   * Checks that format_size() returns the expected string.
+   * Checks that FormatBytesSize::format() returns the expected string.
    */
   public function testCommonFormatSize() {
     foreach ([$this->exactTestCases, $this->roundedTestCases] as $test_cases) {
       foreach ($test_cases as $expected => $input) {
         $this->assertEqual(
-          ($result = format_size($input, NULL)),
+          ($result = FormatBytesSize::format($input, NULL)),
           $expected,
           $expected . ' == ' . $result . ' (' . $input . ' bytes)'
         );
@@ -54,13 +57,13 @@ public function testCommonFormatSize() {
   }
 
   /**
-   * Cross-tests Bytes::toInt() and format_size().
+   * Cross-tests Bytes::toInt() and FormatBytesSize::format().
    */
   public function testCommonParseSizeFormatSize() {
     foreach ($this->exactTestCases as $size) {
       $this->assertEqual(
         $size,
-        ($parsed_size = Bytes::toInt($string = format_size($size, NULL))),
+        ($parsed_size = Bytes::toInt($string = FormatBytesSize::format($size, NULL))),
         $size . ' == ' . $parsed_size . ' (' . $string . ')'
       );
     }
diff --git a/core/tests/Drupal/KernelTests/Core/Image/ToolkitGdTest.php b/core/tests/Drupal/KernelTests/Core/Image/ToolkitGdTest.php
index bb2e481..6ba2ae3 100644
--- a/core/tests/Drupal/KernelTests/Core/Image/ToolkitGdTest.php
+++ b/core/tests/Drupal/KernelTests/Core/Image/ToolkitGdTest.php
@@ -417,9 +417,9 @@ public function testManipulations() {
   }
 
   /**
-   * Tests that GD resources are freed from memory.
+   * Tests that memory is allocated and released properly.
    */
-  public function testResourceDestruction() {
+  public function testMemoryAllocation() {
     // Test that an Image object going out of scope releases its GD resource.
     $image = $this->imageFactory->get(drupal_get_path('module', 'simpletest') . '/files/image-test.png');
     $res = $image->getToolkit()->getResource();
@@ -438,6 +438,15 @@ public function testResourceDestruction() {
     $this->assertFalse(is_resource($old_res));
     // Check if a new resource has been created successfully.
     $this->assertTrue(is_resource($new_res));
+
+    // Test creation of an image that will exceed the memory available.
+    $old_res = $image->getToolkit()->getResource();
+    $this->assertFalse($image->createNew(200000, 200000));
+    $new_res = $image->getToolkit()->getResource();
+    // Check that a new resource has not been created, and the old one is still
+    // valid.
+    $this->assertEqual($new_res, $old_res);
+    $this->assertTrue(is_resource($old_res));
   }
 
   /**
diff --git a/core/tests/Drupal/Tests/Component/Utility/BytesTest.php b/core/tests/Drupal/Tests/Component/Utility/BytesTest.php
index 35872ac..281b964 100644
--- a/core/tests/Drupal/Tests/Component/Utility/BytesTest.php
+++ b/core/tests/Drupal/Tests/Component/Utility/BytesTest.php
@@ -3,6 +3,7 @@
 namespace Drupal\Tests\Component\Utility;
 
 use Drupal\Component\Utility\Bytes;
+use Drupal\Component\Utility\BytesUnitAndSize;
 use Drupal\Tests\UnitTestCase;
 
 /**
@@ -57,4 +58,49 @@ public function providerTestToInt() {
     ];
   }
 
+  /**
+   * Tests \Drupal\Component\Utility\Bytes::toUnitAndSize().
+   *
+   * @param int $size
+   *   The value for the size argument for
+   *   \Drupal\Component\Utility\Bytes::toUnitAndSize().
+   * @param \Drupal\Component\Utility\BytesUnitAndSize $expected_unit_and_size
+   *   The expected return value from
+   *   \Drupal\Component\Utility\Bytes::toUnitAndSize().
+   *
+   * @dataProvider providerTestToUnitAndSize
+   * @covers ::toUnitAndSize
+   */
+  public function testToUnitAndSize($size, BytesUnitAndSize $expected_unit_and_size = NULL) {
+    $this->assertEquals($expected_unit_and_size, Bytes::toUnitAndSize($size));
+  }
+
+  /**
+   * Provides data for ::testToUnitAndSize.
+   *
+   * @return array[]
+   *   An array of arrays, each containing the argument for
+   *   \Drupal\Component\Utility\Bytes::toUnitAndSize(): size and the expected
+   *   return value.
+   */
+  public function providerTestToUnitAndSize() {
+    return [
+      [0, new BytesUnitAndSize(0, 'B')],
+      [1, new BytesUnitAndSize(1, 'B')],
+      [-1, NULL],
+      [768, new BytesUnitAndSize(768, 'B')],
+      [Bytes::KILOBYTE, new BytesUnitAndSize(1, 'KB')],
+      [pow(Bytes::KILOBYTE, 2), new BytesUnitAndSize(1, 'MB')],
+      [pow(Bytes::KILOBYTE, 3), new BytesUnitAndSize(1, 'GB')],
+      [pow(Bytes::KILOBYTE, 4), new BytesUnitAndSize(1, 'TB')],
+      [pow(Bytes::KILOBYTE, 5), new BytesUnitAndSize(1, 'PB')],
+      [pow(Bytes::KILOBYTE, 6), new BytesUnitAndSize(1, 'EB')],
+      [pow(Bytes::KILOBYTE, 7), new BytesUnitAndSize(1, 'ZB')],
+      [pow(Bytes::KILOBYTE, 8), new BytesUnitAndSize(1, 'YB')],
+      [23476892, new BytesUnitAndSize(22.39, 'MB')],
+      [79691776, new BytesUnitAndSize(76, 'MB')],
+      [81862076662, new BytesUnitAndSize(76.24, 'GB')],
+      [4053371676, new BytesUnitAndSize(3.77, 'GB')],
+    ];
+  }
 }
diff --git a/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php b/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php
new file mode 100644
index 0000000..22375e5
--- /dev/null
+++ b/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php
@@ -0,0 +1,160 @@
+<?php
+
+namespace Drupal\Tests\Component\Utility;
+
+use Drupal\Component\Utility\Bytes;
+use Drupal\Component\Utility\EnvironmentMemory;
+use Drupal\Tests\UnitTestCase;
+
+/**
+ * Test PHP memory helper class.
+ *
+ * @group Utility
+ *
+ * @coversDefaultClass \Drupal\Component\Utility\EnvironmentMemory
+ */
+class EnvironmentMemoryTest extends UnitTestCase {
+
+  /**
+   * Test getting memory limit via ini_get().
+   *
+   * @covers ::getTotal
+   * @covers ::setTotal
+   */
+  public function testGetTotalFromIni() {
+    $limit = ini_get('memory_limit');
+    $limit = (!$limit || $limit == -1) ? EnvironmentMemory::UNLIMITED : Bytes::toInt($limit);
+    $memory = new EnvironmentMemory();
+    $this->assertEquals($limit, $memory->getTotal());
+  }
+
+  /**
+   * Test getting memory limit after being changed via setTotal().
+   *
+   * @covers ::getTotal
+   * @covers ::setTotal
+   */
+  public function testGetTotalFromSetTotal() {
+    $memory = new EnvironmentMemory();
+    $memory->setTotal('100MB');
+    $this->assertEquals(104857600, $memory->getTotal());
+  }
+
+  /**
+   * @covers ::checkLimit
+   *
+   * @dataProvider providerTestCheckLimit
+   *
+   * @param string $required
+   *   The required memory argument for
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkLimit().
+   * @param string $custom_memory_limit
+   *   The custom memory limit argument for
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkLimit().
+   * @param bool $expected
+   *   The expected return value from
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkLimit().
+   */
+  public function testCheckLimit($required, $custom_memory_limit, $expected) {
+    $memory = new EnvironmentMemory();
+    $memory->setTotal($custom_memory_limit);
+    $this->assertEquals($expected, $memory->checkLimit($required));
+  }
+
+  /**
+   * Provides data for ::testCheckLimit().
+   *
+   * @return array
+   *   An array of arrays, each containing the arguments for
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkLimit():
+   *   required and memory_limit, and the expected return value.
+   */
+  public function providerTestCheckLimit() {
+    $memory_limit = ini_get('memory_limit');
+    $twice_avail_memory = ($memory_limit * 2) . 'MB';
+
+    return [
+      // Minimal amount of memory should be available.
+      ['30MB', NULL, TRUE],
+      // Exceed a custom (unlimited) memory limit.
+      [$twice_avail_memory, EnvironmentMemory::UNLIMITED, TRUE],
+      // Exceed a custom memory limit.
+      ['30MB', '16MB', FALSE],
+      // Available = required.
+      ['30MB', '30MB', TRUE],
+    ];
+  }
+
+  /**
+   * Test available memory based on current process memory usage.
+   *
+   * @covers ::checkAvailable
+   * @covers ::getUsed
+   */
+  public function testCheckAvailableCurrent() {
+    $limit = ini_get('memory_limit');
+    $limit = (!$limit || $limit == -1) ? EnvironmentMemory::UNLIMITED : Bytes::toInt($limit);
+    if ($limit > 0) {
+      $memory = new EnvironmentMemory();
+      $free_memory = $limit - memory_get_usage(TRUE);
+      $this->assertTrue($memory->checkAvailable($free_memory - Bytes::toInt('4k')));
+      $this->assertFalse($memory->checkAvailable($free_memory + Bytes::toInt('4k')));
+    }
+  }
+
+  /**
+   * Test available memory based on simulated memory usage.
+   *
+   * @covers ::checkAvailable
+   *
+   * @dataProvider providerTestCheckAvailable
+   *
+   * @param string $custom_memory_limit
+   *   A custom memory limit argument for
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkAvailable().
+   * @param string $used_memory
+   *   A mocked value for used memory.
+   * @param string $required
+   *   The required memory argument for
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkAvailable().
+   * @param bool $expected
+   *   The expected return value from
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkAvailable().
+   */
+  public function testCheckAvailable($custom_memory_limit, $used_memory, $required, $expected) {
+    $mock_builder = $this->getMockBuilder('Drupal\Component\Utility\EnvironmentMemory');
+    $memory = $mock_builder
+      ->setMethods(['getUsed'])
+      ->getMock();
+    $memory->expects($this->any())
+      ->method('getUsed')
+      ->will($this->returnValue(Bytes::toInt($used_memory)));
+
+    $memory->setTotal($custom_memory_limit);
+    $this->assertEquals($expected, $memory->checkAvailable($required));
+  }
+
+  /**
+   * Provides data for ::testCheckAvailable().
+   *
+   * @return array[]
+   *   An array of arrays, each containing the arguments for
+   *   \Drupal\Component\Utility\EnvironmentMemory::checkAvailable():
+   *   memory_limit, used_memory, required memory and the expected
+   *   return value.
+   */
+  public function providerTestCheckAvailable() {
+    $currently_available = Bytes::toInt(ini_get('memory_limit')) - memory_get_usage(TRUE);
+    return [
+      // 30MB should be available with limit of 60MB and usage of 10MB.
+      ['60MB', '10MB', '30MB', TRUE],
+      // Limit = required + used.
+      ['40MB', '30MB', '10MB', TRUE],
+      // Exceed memory limit.
+      ['20MB', '10MB', '30MB', FALSE],
+      // Exceed memory limit by 1 byte.
+      ['20MB', '20MB', '1', FALSE],
+    ];
+  }
+
+}
diff --git a/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php b/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php
index 708eee9..8922400 100644
--- a/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php
+++ b/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php
@@ -11,6 +11,9 @@
  * @group Utility
  *
  * @coversDefaultClass \Drupal\Component\Utility\Environment
+ *
+ * @deprecated in Drupal 8.4.x, will be removed before Drupal 9.0.0.
+ *   Use \Drupal\Component\Utility\EnvironmentMemory.
  */
 class EnvironmentTest extends UnitTestCase {
 
