light9
9/23/2013 - 3:09 PM

Configurable background color when cropping to larger dimensions

Configurable background color when cropping to larger dimensions

Index: imageapi_gd.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/imageapi/imageapi_gd.module,v
retrieving revision 1.13.2.7
diff -u -r1.13.2.7 imageapi_gd.module
--- imageapi_gd.module  17 Apr 2009 00:15:21 -0000	1.13.2.7
+++ imageapi_gd.module	8 Oct 2009 21:05:23 -0000
@@ -27,6 +27,15 @@
     '#default_value' => variable_get('imageapi_jpeg_quality', 75),
     '#field_suffix' => '%',
   );
+  $form['imageapi_crop_background'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Crop background'),
+    '#description' => t('Hex string specifying the background color to use when cropping images. If not provided, will use the default. Examples: "ABC", "ABCD", "AABBCC", "AABBCCDD".'),
+    '#size' => 10,
+    '#maxlength' => 8,
+    '#default_value' => variable_get('imageapi_crop_background', ''),
+    '#field_prefix' => '#',
+  );
   return system_settings_form($form);
 }
 
@@ -93,9 +102,22 @@
  *   TRUE or FALSE, based on success.
  */
 function imageapi_gd_image_crop(&$image, $x, $y, $width, $height) {
+  // Create an image with the new width and height.
   $res = imageapi_gd_create_tmp($image, $width, $height);
 
-  if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) {
+  // Fill the background color if desired.
+  $background = variable_get('imageapi_crop_background', '');
+  if (!empty($background)) {
+    $background = imageapi_hex2rgba($background);
+    $background = imagecolorallocatealpha($res, $background[0], $background[1], $background[2], $background[3]);
+    imagefill($res, 0, 0, $background);
+  }
+
+  // Copy the source image to our new destination image. We use
+  // $image->info['width] instead of $width because we are copying
+  // using the source image's width and height, not the destination
+  // width and height.
+  if (!imagecopyresampled($res, $image->resource, -$x, -$y, 0, 0, $image->info['width'], $image->info['height'], $image->info['width'], $image->info['height'])) {
     return FALSE;
   }