You are here

function image_gd_resize in Drupal 5

Same name and namespace in other branches
  1. 4 includes/image.inc \image_gd_resize()
  2. 6 includes/image.gd.inc \image_gd_resize()
  3. 7 modules/system/image.gd.inc \image_gd_resize()

Scale an image to the specified size using GD.

File

includes/image.inc, line 222

Code

function image_gd_resize($source, $destination, $width, $height) {
  if (!file_exists($source)) {
    return FALSE;
  }
  $info = image_get_info($source);
  if (!$info) {
    return FALSE;
  }
  $im = image_gd_open($source, $info['extension']);
  if (!$im) {
    return FALSE;
  }
  $res = imagecreatetruecolor($width, $height);
  if ($info['extension'] == 'png') {
    $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
    imagealphablending($res, FALSE);
    imagefilledrectangle($res, 0, 0, $width, $height, $transparency);
    imagealphablending($res, TRUE);
    imagesavealpha($res, TRUE);
  }
  elseif ($info['extension'] == 'gif') {

    // If we have a specific transparent color.
    $transparency_index = imagecolortransparent($im);
    if ($transparency_index >= 0) {

      // Get the original image's transparent color's RGB values.
      $transparent_color = imagecolorsforindex($im, $transparency_index);

      // Allocate the same color in the new image resource.
      $transparency_index = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);

      // Completely fill the background of the new image with allocated color.
      imagefill($res, 0, 0, $transparency_index);

      // Set the background color for new image to transparent.
      imagecolortransparent($res, $transparency_index);

      // Find number of colors in the images palette.
      $number_colors = imagecolorstotal($im);

      // Convert from true color to palette to fix transparency issues.
      imagetruecolortopalette($res, TRUE, $number_colors);
    }
  }
  imagecopyresampled($res, $im, 0, 0, 0, 0, $width, $height, $info['width'], $info['height']);
  $result = image_gd_close($res, $destination, $info['extension']);
  imagedestroy($res);
  imagedestroy($im);
  return $result;
}