diff --git a/core/includes/common.inc b/core/includes/common.inc
index 5d62aad..65dfd95 100644
--- a/core/includes/common.inc
+++ b/core/includes/common.inc
@@ -249,40 +249,28 @@ function check_url($uri) {
  *   A translated string representation of the size.
  */
 function format_size($size, $langcode = NULL) {
-  if ($size < Bytes::KILOBYTE) {
-    return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', array(), array('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);
-    }
+  $options = ['langcode' => $langcode];
+  $value = Bytes::toUnitAndSize($size);
+  $args = ['@size' => $value['size']];
+  switch ($value['unit']) {
+    case 'B':
+      return new PluralTranslatableMarkup($value['size'], '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/lib/Drupal/Component/Utility/Bytes.php b/core/lib/Drupal/Component/Utility/Bytes.php
index 4d331ea..1b7d8c6 100644
--- a/core/lib/Drupal/Component/Utility/Bytes.php
+++ b/core/lib/Drupal/Component/Utility/Bytes.php
@@ -44,4 +44,36 @@ public static function toInt($size) {
     }
   }
 
+  /**
+   * Returns unit of measurement and size of a byte quantity.
+   *
+   * This method returns an array with 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 array
+   *   An associative array with the following keys:
+   *   - 'unit': unit of measurement (string)
+   *   - 'size': size (float, rounded to 2 decimals).
+   *   An empty array if the input value is negative.
+   *
+   * @see format_size
+   */
+  public static function toUnitAndSize($size) {
+    if ($size < 0) {
+      return [];
+    }
+    foreach (['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) {
+      if (round($size, 2) < self::KILOBYTE) {
+        break;
+      }
+      $size = $size / self::KILOBYTE;
+    }
+    return ['unit' => $unit, 'size' => round($size, 2)];
+  }
+
 }
diff --git a/core/lib/Drupal/Component/Utility/Environment.php b/core/lib/Drupal/Component/Utility/Environment.php
index 087bcad..6ab61b4 100644
--- a/core/lib/Drupal/Component/Utility/Environment.php
+++ b/core/lib/Drupal/Component/Utility/Environment.php
@@ -9,6 +9,9 @@
 
 /**
  * Provides PHP environment helper methods.
+ *
+ * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0. Use
+ *   \Drupal\Component\Utility\EnvironmentMemory instead.
  */
 class Environment {
 
@@ -28,18 +31,21 @@ class Environment {
    * @return bool
    *   TRUE if there is sufficient memory to allow the operation, or FALSE
    *   otherwise.
+   *
+   * @deprecated in Drupal 8.1.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..7c22588
--- /dev/null
+++ b/core/lib/Drupal/Component/Utility/EnvironmentMemory.php
@@ -0,0 +1,130 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Component\Utility\EnvironmentMemory.
+ */
+
+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 eab55c1..0abd2d4 100644
--- a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitBase.php
+++ b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitBase.php
@@ -137,6 +137,10 @@ public function apply($operation, array $arguments = array()) {
       $this->logger->warning($e->getMessage(), array());
       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 9e21c03..a67501b 100644
--- a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationBase.php
+++ b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationBase.php
@@ -190,6 +190,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 779deef..3ff986b 100644
--- a/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationInterface.php
+++ b/core/lib/Drupal/Core/ImageToolkit/ImageToolkitOperationInterface.php
@@ -34,6 +34,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/modules/system/src/Plugin/ImageToolkit/GDToolkit.php b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
index 3314623..574e03e 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php
@@ -7,7 +7,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;
@@ -139,7 +141,9 @@ public function setResource($resource) {
    */
   public function getResource() {
     if (!is_resource($this->resource)) {
-      $this->load();
+      if (!$this->load()) {
+        return NULL;
+      };
     }
     return $this->resource;
   }
@@ -181,6 +185,24 @@ protected function load() {
       return FALSE;
     }
 
+    // Check if there are memory limitations to load the image.
+    $unavailable_memory = $this->unavailableMemoryCheck($this->getWidth(), $this->getHeight());
+    if ($unavailable_memory) {
+      // If yes, 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' => $unavailable_memory['required']['size'],
+        '%req_unit' => $unavailable_memory['required']['unit'],
+        '%free_size' => $unavailable_memory['free']['size'],
+        '%free_unit' => $unavailable_memory['free']['unit'],
+        '%tot_size' => $unavailable_memory['total']['size'],
+        '%tot_unit' => $unavailable_memory['total']['unit'],
+        '%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);
@@ -436,4 +458,54 @@ public function extensionToImageType($extension) {
   protected static function supportedTypes() {
     return array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
   }
+
+  /**
+   * Ensures 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 array[]
+   *   An empty array if the memory is available. If not enough memory is
+   *   available, an associative array 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 unavailableMemoryCheck($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 [];
+    }
+    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 d582c68..df9b397 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php
@@ -84,6 +84,12 @@ protected function validateArguments(array $arguments) {
    * {@inheritdoc}
    */
   protected function execute(array $arguments) {
+    // Check if there are memory limitations to perform the operation.
+    $unavailable_memory = $this->getToolkit()->unavailableMemoryCheck($arguments['width'], $arguments['height']);
+    if ($unavailable_memory) {
+      throw new \RuntimeException("Not enough memory (required: {$unavailable_memory['required']['size']} {$unavailable_memory['required']['unit']}, free: {$unavailable_memory['free']['size']} {$unavailable_memory['free']['unit']}, total: {$unavailable_memory['total']['size']} {$unavailable_memory['total']['unit']}) 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 c77ff31..5df5f10 100644
--- a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php
+++ b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php
@@ -8,6 +8,7 @@
 namespace Drupal\system\Plugin\ImageToolkit\Operation\gd;
 
 use Drupal\Component\Utility\Color;
+use Drupal\Component\Utility\Rectangle;
 
 /**
  * Defines GD2 rotate operation.
@@ -98,6 +99,14 @@ protected function execute(array $arguments) {
       return FALSE;
     }
 
+    // Check if there are memory limitations to perform the operation.
+    $rect = new Rectangle($this->getToolkit()->getWidth(), $this->getToolkit()->getHeight());
+    $rect = $rect->rotate($arguments['degrees']);
+    $unavailable_memory = $this->getToolkit()->unavailableMemoryCheck($rect->getBoundingWidth(), $rect->getBoundingHeight());
+    if ($unavailable_memory) {
+      throw new \RuntimeException("Not enough memory (required: {$unavailable_memory['required']['size']} {$unavailable_memory['required']['unit']}, free: {$unavailable_memory['free']['size']} {$unavailable_memory['free']['unit']}, total: {$unavailable_memory['total']['size']} {$unavailable_memory['total']['unit']}) to perform the image '{$this->getPluginId()}' operation");
+    }
+
     // Stores the original GD resource.
     $original_res = $this->getToolkit()->getResource();
 
diff --git a/core/modules/system/src/Tests/Common/SizeUnitTest.php b/core/modules/system/src/Tests/Common/SizeUnitTest.php
index 1cc5d0e..4fcc751 100644
--- a/core/modules/system/src/Tests/Common/SizeUnitTest.php
+++ b/core/modules/system/src/Tests/Common/SizeUnitTest.php
@@ -24,6 +24,7 @@ protected function setUp() {
     parent::setUp();
     $kb = Bytes::KILOBYTE;
     $this->exactTestCases = array(
+      '0 bytes' => 0,
       '1 byte' => 1,
       '1 KB'   => $kb,
       '1 MB'   => $kb * $kb,
@@ -37,6 +38,7 @@ protected function setUp() {
     $this->roundedTestCases = array(
       '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 #2583041
       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
diff --git a/core/modules/system/src/Tests/Image/ToolkitGdTest.php b/core/modules/system/src/Tests/Image/ToolkitGdTest.php
index 1c61235..4de86a9 100644
--- a/core/modules/system/src/Tests/Image/ToolkitGdTest.php
+++ b/core/modules/system/src/Tests/Image/ToolkitGdTest.php
@@ -401,9 +401,9 @@ 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();
@@ -422,6 +422,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(20000, 20000));
+    $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/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..20708fe
--- /dev/null
+++ b/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php
@@ -0,0 +1,223 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Tests\system\Unit\Plugin\ImageToolkit\GdToolkitTest.
+ */
+
+namespace Drupal\Tests\system\Unit\Plugin\ImageToolkit;
+
+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::unavailableMemoryCheck, for mocking.
+   *
+   * @var array
+   */
+  protected $unavailableMemoryFalse = [];
+
+  /**
+   * Result for GDToolkit::unavailableMemoryCheck, for mocking.
+   *
+   * @var array
+   */
+  protected $unavailableMemoryTrue = [
+    'free' => ['unit' => 'MB', 'size' => 10],
+    'required' => ['unit' => 'MB', 'size' => 20],
+    'total' => ['unit' => 'MB', 'size' => 20],
+  ];
+
+  /**
+   * @inheritdoc
+   */
+  protected function setUp() {
+    // Use the Druplicon image.
+    $this->source = __DIR__ . '/../../../../../../simpletest/files/image-test.jpg';
+  }
+
+  /**
+   * 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(['unavailableMemoryCheck']);
+    $this->toolkit->expects($this->any())
+      ->method('unavailableMemoryCheck')
+      ->will($this->returnValue($this->unavailableMemoryFalse));
+
+    $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(['unavailableMemoryCheck']);
+    $this->toolkit->expects($this->any())
+      ->method('unavailableMemoryCheck')
+      ->will($this->returnValue($this->unavailableMemoryTrue));
+
+    // 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(['unavailableMemoryCheck', 'getToolkitOperation', 'apply']);
+    $this->setToolkitOperationMock('CreateNew', $this->toolkit);
+    $this->toolkit->expects($this->any())
+      ->method('unavailableMemoryCheck')
+      ->will($this->onConsecutiveCalls($this->unavailableMemoryFalse, $this->unavailableMemoryTrue));
+    $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(['unavailableMemoryCheck', 'getToolkitOperation', 'apply']);
+    $this->setToolkitOperationMock('Rotate', $this->toolkit);
+    $this->toolkit->expects($this->any())
+      ->method('unavailableMemoryCheck')
+      ->will($this->onConsecutiveCalls($this->unavailableMemoryFalse, $this->unavailableMemoryTrue));
+    $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/Tests/Component/Utility/BytesTest.php b/core/tests/Drupal/Tests/Component/Utility/BytesTest.php
index 8e72b6c..347bff2 100644
--- a/core/tests/Drupal/Tests/Component/Utility/BytesTest.php
+++ b/core/tests/Drupal/Tests/Component/Utility/BytesTest.php
@@ -62,4 +62,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 array $expected_unit_and_size
+   *   The expected return value from
+   *   \Drupal\Component\Utility\Bytes::toUnitAndSize().
+   *
+   * @dataProvider providerTestToUnitAndSize
+   * @covers ::toUnitAndSize
+   */
+  public function testToUnitAndSize($size, array $expected_unit_and_size) {
+    $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, ['unit' => 'B', 'size' => 0]],
+      [1, ['unit' => 'B', 'size' => 1]],
+      [-1, []],
+      [768, ['unit' => 'B', 'size' => 768]],
+      [Bytes::KILOBYTE, ['unit' => 'KB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 2), ['unit' => 'MB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 3), ['unit' => 'GB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 4), ['unit' => 'TB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 5), ['unit' => 'PB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 6), ['unit' => 'EB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 7), ['unit' => 'ZB', 'size' => 1]],
+      [pow(Bytes::KILOBYTE, 8), ['unit' => 'YB', 'size' => 1]],
+      [23476892, ['unit' => 'MB', 'size' => 22.39]],
+      [79691776, ['unit' => 'MB', 'size' => 76]],
+      [81862076662, ['unit' => 'GB', 'size' => 76.24]],
+      [4053371676, ['unit' => 'GB', 'size' => 3.77]],
+    ];
+  }
 }
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..7f243a5
--- /dev/null
+++ b/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php
@@ -0,0 +1,165 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\Tests\Component\Utility\EnvironmentMemoryTest.
+ */
+
+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 72f04f7..32d756f 100644
--- a/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php
+++ b/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php
@@ -16,6 +16,9 @@
  * @group Utility
  *
  * @coversDefaultClass \Drupal\Component\Utility\Environment
+ *
+ * @deprecated in Drupal 8.1.x, will be removed before Drupal 9.0.0.
+ *   Use \Drupal\Component\Utility\EnvironmentMemory.
  */
 class EnvironmentTest extends UnitTestCase {
 
