<?php

class AppHerramientasImagen{

	/**
	 * @file
	 * GD2 toolkit for image manipulation within Drupal.
	 */
	
	/**
	 * @addtogroup image
	 * @{
	 */
	
	/**
	 * Retrieve settings for the GD2 toolkit.
	 */
	public static function image_gd_settings() {
	  if (image_gd_check_settings()) {
	    $form['status'] = array(
	      '#markup' => t('The GD toolkit is installed and working properly.')
	    );
	
	    $form['image_jpeg_quality'] = array(
	      '#type' => 'textfield',
	      '#title' => t('JPEG quality'),
	      '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality but bigger files.'),
	      '#size' => 10,
	      '#maxlength' => 3,
	      '#default_value' => variable_get('image_jpeg_quality', 75),
	      '#field_suffix' => t('%'),
	    );
	    $form['#element_validate'] = array('image_gd_settings_validate');
	
	    return $form;
	  }
	  else {
	    form_set_error('image_toolkit', t('The GD image toolkit requires that the GD module for PHP be installed and configured properly. For more information see <a href="@url">PHP\'s image documentation</a>.', array('@url' => 'http://php.net/image')));
	    return FALSE;
	  }
	}
	
	/**
	 * Validate the submitted GD settings.
	 */
	public static function image_gd_settings_validate($form, &$form_state) {
	  // Validate image quality range.
	  $value = $form_state['values']['image_jpeg_quality'];
	  if (!is_numeric($value) || $value < 0 || $value > 100) {
	    form_set_error('image_jpeg_quality', t('JPEG quality must be a number between 0 and 100.'));
	  }
	}
	
	/**
	 * Verify GD2 settings (that the right version is actually installed).
	 *
	 * @return
	 *   A boolean indicating if the GD toolkit is available on this machine.
	 */
	public static function image_gd_check_settings() {
	  if ($check = get_extension_funcs('gd')) {
	    if (in_array('imagegd2', $check)) {
	      // GD2 support is available.
	      return TRUE;
	    }
	  }
	  return FALSE;
	}
	
	/**
	 * Scale an image to the specified size using GD.
	 *
	 * @param $image
	 *   An image object. The $image->resource, $image->info['width'], and
	 *   $image->info['height'] values will be modified by this call.
	 * @param $width
	 *   The new width of the resized image, in pixels.
	 * @param $height
	 *   The new height of the resized image, in pixels.
	 * @return
	 *   TRUE or FALSE, based on success.
	 *
	 * @see image_resize()
	 */
	public static function image_gd_resize(stdClass $image, $width, $height) {
	  $res = self::image_gd_create_tmp($image, $width, $height);
	
	  if (!imagecopyresampled($res, $image->resource, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) {
	    return FALSE;
	  }
	
	  imagedestroy($image->resource);
	  // Update image object.
	  $image->resource = $res;
	  $image->info['width'] = $width;
	  $image->info['height'] = $height;
	  return TRUE;
	}
	
	/**
	 * Rotate an image the given number of degrees.
	 *
	 * @param $image
	 *   An image object. The $image->resource, $image->info['width'], and
	 *   $image->info['height'] values will be modified by this call.
	 * @param $degrees
	 *   The number of (clockwise) degrees to rotate the image.
	 * @param $background
	 *   An hexadecimal integer specifying the background color to use for the
	 *   uncovered area of the image after the rotation. E.g. 0x000000 for black,
	 *   0xff00ff for magenta, and 0xffffff for white. For images that support
	 *   transparency, this will default to transparent. Otherwise it will
	 *   be white.
	 * @return
	 *   TRUE or FALSE, based on success.
	 *
	 * @see image_rotate()
	 */
	public static function image_gd_rotate(stdClass $image, $degrees, $background = NULL) {
	  // PHP installations using non-bundled GD do not have imagerotate.
	  if (!function_exists('imagerotate')) {
	    watchdog('image', 'The image %file could not be rotated because the imagerotate() function is not available in this PHP installation.', array('%file' => $image->source));
	    return FALSE;
	  }
	
	  $width = $image->info['width'];
	  $height = $image->info['height'];
	
	  // Convert the hexadecimal background value to a color index value.
	  if (isset($background)) {
	    $rgb = array();
	    for ($i = 16; $i >= 0; $i -= 8) {
	      $rgb[] = (($background >> $i) & 0xFF);
	    }
	    $background = imagecolorallocatealpha($image->resource, $rgb[0], $rgb[1], $rgb[2], 0);
	  }
	  // Set the background color as transparent if $background is NULL.
	  else {
	    // Get the current transparent color.
	    $background = imagecolortransparent($image->resource);
	
	    // If no transparent colors, use white.
	    if ($background == 0) {
	      $background = imagecolorallocatealpha($image->resource, 255, 255, 255, 0);
	    }
	  }
	
	  // Images are assigned a new color palette when rotating, removing any
	  // transparency flags. For GIF images, keep a record of the transparent color.
	  if ($image->info['extension'] == 'gif') {
	    $transparent_index = imagecolortransparent($image->resource);
	    if ($transparent_index != 0) {
	      $transparent_gif_color = imagecolorsforindex($image->resource, $transparent_index);
	    }
	  }
	
	  $image->resource = imagerotate($image->resource, 360 - $degrees, $background);
	
	  // GIFs need to reassign the transparent color after performing the rotate.
	  if (isset($transparent_gif_color)) {
	    $background = imagecolorexactalpha($image->resource, $transparent_gif_color['red'], $transparent_gif_color['green'], $transparent_gif_color['blue'], $transparent_gif_color['alpha']);
	    imagecolortransparent($image->resource, $background);
	  }
	
	  $image->info['width'] = imagesx($image->resource);
	  $image->info['height'] = imagesy($image->resource);
	  return TRUE;
	}
	
	/**
	 * Crop an image using the GD toolkit.
	 *
	 * @param $image
	 *   An image object. The $image->resource, $image->info['width'], and
	 *   $image->info['height'] values will be modified by this call.
	 * @param $x
	 *   The starting x offset at which to start the crop, in pixels.
	 * @param $y
	 *   The starting y offset at which to start the crop, in pixels.
	 * @param $width
	 *   The width of the cropped area, in pixels.
	 * @param $height
	 *   The height of the cropped area, in pixels.
	 * @return
	 *   TRUE or FALSE, based on success.
	 *
	 * @see image_crop()
	 */
	public static function image_gd_crop(stdClass $image, $x, $y, $width, $height) {
	  $res = self::image_gd_create_tmp($image, $width, $height);
	
	  if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) {
	    return FALSE;
	  }
	
	  // Destroy the original image and return the modified image.
	  imagedestroy($image->resource);
	  $image->resource = $res;
	  $image->info['width'] = $width;
	  $image->info['height'] = $height;
	  return TRUE;
	}
	
	/**
	 * Convert an image resource to grayscale.
	 *
	 * Note that transparent GIFs loose transparency when desaturated.
	 *
	 * @param $image
	 *   An image object. The $image->resource value will be modified by this call.
	 * @return
	 *   TRUE or FALSE, based on success.
	 *
	 * @see image_desaturate()
	 */
	public static function image_gd_desaturate(stdClass $image) {
	  // PHP installations using non-bundled GD do not have imagefilter.
	  if (!function_exists('imagefilter')) {
	    watchdog('image', 'The image %file could not be desaturated because the imagefilter() function is not available in this PHP installation.', array('%file' => $image->source));
	    return FALSE;
	  }
	
	  return imagefilter($image->resource, IMG_FILTER_GRAYSCALE);
	}
	
	/**
	 * GD helper function to create an image resource from a file.
	 *
	 * @param $image
	 *   An image object. The $image->resource value will populated by this call.
	 * @return
	 *   TRUE or FALSE, based on success.
	 *
	 * @see image_load()
	 */
	public static function image_gd_load(stdClass $image) {
	  $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
	  $function = 'imagecreatefrom' . $extension;
	  if(function_exists($function)){
	  	
	  }
	  return $function($image->source);
	}
	
	/**
	 * GD helper to write an image resource to a destination file.
	 *
	 * @param $image
	 *   An image object.
	 * @param $destination
	 *   A string file URI or path where the image should be saved.
	 * @return
	 *   TRUE or FALSE, based on success.
	 *
	 * @see image_save()
	 */
	public static function image_gd_save(stdClass $image, $destination) {
	  $scheme = self::file_uri_scheme($destination);
	  // Work around lack of stream wrapper support in imagejpeg() and imagepng().
	  if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
	    // If destination is not local, save image to temporary local file.
	    $local_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL);
	    if (!isset($local_wrappers[$scheme])) {
	      $permanent_destination = $destination;
	      $destination = drupal_tempnam('temporary://', 'gd_');
	    }
	    // Convert stream wrapper URI to normal path.
	    $destination = drupal_realpath($destination);
	  }
	
	  $extension = str_replace('jpg', 'jpeg', $image->info['extension']);
	  $function = 'image' . $extension;
	  if (!function_exists($function)) {
	    return FALSE;
	  }
	  if ($extension == 'jpeg') {
	    $success = $function($image->resource, $destination, variable_get('image_jpeg_quality', 75));
	  }
	  else {
	    // Always save PNG images with full transparency.
	    if ($extension == 'png') {
	      imagealphablending($image->resource, FALSE);
	      imagesavealpha($image->resource, TRUE);
	    }
	    $success = $function($image->resource, $destination);
	  }
	  // Move temporary local file to remote destination.
	  if (isset($permanent_destination) && $success) {
	    return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
	  }
	  return $success;
	}
	
	/**
	 * Create a truecolor image preserving transparency from a provided image.
	 *
	 * @param $image
	 *   An image object.
	 * @param $width
	 *   The new width of the new image, in pixels.
	 * @param $height
	 *   The new height of the new image, in pixels.
	 * @return
	 *   A GD image handle.
	 */
	public static function image_gd_create_tmp(stdClass $image, $width, $height) {
	  $res = imagecreatetruecolor($width, $height);
	
	  if ($image->info['extension'] == 'gif') {
	    // Grab transparent color index from image resource.
	    $transparent = imagecolortransparent($image->resource);
	
	    if ($transparent >= 0) {
	      // The original must have a transparent color, allocate to the new image.
	      $transparent_color = imagecolorsforindex($image->resource, $transparent);
	      $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
	
	      // Flood with our new transparent color.
	      imagefill($res, 0, 0, $transparent);
	      imagecolortransparent($res, $transparent);
	    }
	  }
	  elseif ($image->info['extension'] == 'png') {
	    imagealphablending($res, FALSE);
	    $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127);
	    imagefill($res, 0, 0, $transparency);
	    imagealphablending($res, TRUE);
	    imagesavealpha($res, TRUE);
	  }
	  else {
	    imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255));
	  }
	
	  return $res;
	}
	
	/**
	 * Get details about an image.
	 *
	 * @param $image
	 *   An image object.
	 * @return
	 *   FALSE, if the file could not be found or is not an image. Otherwise, a
	 *   keyed array containing information about the image:
	 *   - "width": Width, in pixels.
	 *   - "height": Height, in pixels.
	 *   - "extension": Commonly used file extension for the image.
	 *   - "mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
	 *
	 * @see image_get_info()
	 */
	public static function image_gd_get_info(stdClass $image) {
	  $details = FALSE;
	  $data = getimagesize($image->source);
	
	  if (isset($data) && is_array($data)) {
	    $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
	    $extension = isset($extensions[$data[2]]) ?  $extensions[$data[2]] : '';
	    $details = array(
	      'width'     => $data[0],
	      'height'    => $data[1],
	      'extension' => $extension,
	      'mime_type' => $data['mime'],
	    );
	  }
	
	  return $details;
	}
	
	/**
	 * @} End of "addtogroup image".
	 */
	
	
	/**
	 * @file
	 * API for manipulating images.
	 */
	
	/**
	 * @defgroup image Image toolkits
	 * @{
	 * Functions for image file manipulations.
	 *
	 * Drupal's image toolkits provide an abstraction layer for common image file
	 * manipulations like scaling, cropping, and rotating. The abstraction frees
	 * module authors from the need to support multiple image libraries, and it
	 * allows site administrators to choose the library that's best for them.
	 *
	 * PHP includes the GD library by default so a GD toolkit is installed with
	 * Drupal. Other toolkits like ImageMagick are available from contrib modules.
	 * GD works well for small images, but using it with larger files may cause PHP
	 * to run out of memory. In contrast the ImageMagick library does not suffer
	 * from this problem, but it requires the ISP to have installed additional
	 * software.
	 *
	 * Image toolkits are discovered based on the associated module's
	 * hook_image_toolkits. Additionally the image toolkit include file
	 * must be identified in the files array in the module.info file. The
	 * toolkit must then be enabled using the admin/config/media/image-toolkit
	 * form.
	 *
	 * Only one toolkit may be selected at a time. If a module author wishes to call
	 * a specific toolkit they can check that it is installed by calling
	 * image_get_available_toolkits(), and then calling its functions directly.
	 */
	
	/**
	 * Gets a list of available toolkits.
	 *
	 * @return
	 *   An array with the toolkit names as keys and the descriptions as values.
	 */
	public static function image_get_available_toolkits() {
		// hook_image_toolkits returns an array of toolkit names.
		//$toolkits = module_invoke_all('image_toolkits');
	
		$output = array();
		
		//foreach ($toolkits as $name => $info) {
			// Only allow modules that aren't marked as unavailable.
			//if ($info['available']) {
				$output['gd'] = 'gd';
			//}
		//}*/
	
		return $output;
	}
	
	/**
	 * Gets the name of the currently used toolkit.
	 *
	 * @return
	 *   String containing the name of the selected toolkit, or FALSE on error.
	 */
	public static function image_get_toolkit() {
		static $toolkit;
	
		if (!isset($toolkit)) {
			$toolkits = self::image_get_available_toolkits();
			$toolkit = 'gd';
			if (!isset($toolkits[$toolkit]) || !function_exists('image_' . $toolkit . '_load')) {
				// The selected toolkit isn't available so return the first one found. If
				// none are available this will return FALSE.
				reset($toolkits);
				$toolkit = key($toolkits);
			}
		}
	
		return $toolkit;
	}
	
	/**
	 * Invokes the given method using the currently selected toolkit.
	 *
	 * @param $method
	 *   A string containing the method to invoke.
	 * @param $image
	 *   An image object returned by image_load().
	 * @param $params
	 *   An optional array of parameters to pass to the toolkit method.
	 *
	 * @return
	 *   Mixed values (typically Boolean indicating successful operation).
	 */
	public static function image_toolkit_invoke($method, stdClass $image, array $params = array()) {
		$function = 'image_' . $image->toolkit . '_' . $method;
		if (function_exists($function)) {
			array_unshift($params, $image);
			return call_user_func_array($function, $params);
		}
		watchdog('image', 'The selected image handling toolkit %toolkit can not correctly process %function.', array('%toolkit' => $image->toolkit, '%function' => $function), WATCHDOG_ERROR);
		return FALSE;
	}
	
	/**
	 * Gets details about an image.
	 *
	 * Drupal supports GIF, JPG and PNG file formats when used with the GD
	 * toolkit, and may support others, depending on which toolkits are
	 * installed.
	 *
	 * @param $filepath
	 *   String specifying the path of the image file.
	 * @param $toolkit
	 *   An optional image toolkit name to override the default.
	 *
	 * @return
	 *   FALSE, if the file could not be found or is not an image. Otherwise, a
	 *   keyed array containing information about the image:
	 *   - "width": Width, in pixels.
	 *   - "height": Height, in pixels.
	 *   - "extension": Commonly used file extension for the image.
	 *   - "mime_type": MIME type ('image/jpeg', 'image/gif', 'image/png').
	 *   - "file_size": File size in bytes.
	 */
	public static function image_get_info($filepath, $toolkit = FALSE) {
		$details = FALSE;
		if (!is_file($filepath) && !is_uploaded_file($filepath)) {
			return $details;
		}
	
	
		
			$image = new stdClass();
			$image->source = $filepath;
			$image->toolkit = $toolkit;
			$details = self::image_gd_get_info($image);  //image_toolkit_invoke('get_info', $image);
			if (isset($details) && is_array($details)) {
				$details['file_size'] = filesize($filepath);
			}
		
	
		return $details;
	}
	
	/**
	 * Scales an image to the exact width and height given.
	 *
	 * This function achieves the target aspect ratio by cropping the original image
	 * equally on both sides, or equally on the top and bottom. This function is
	 * useful to create uniform sized avatars from larger images.
	 *
	 * The resulting image always has the exact target dimensions.
	 *
	 * @param $image
	 *   An image object returned by image_load().
	 * @param $width
	 *   The target width, in pixels.
	 * @param $height
	 *   The target height, in pixels.
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_load()
	 * @see image_resize()
	 * @see image_crop()
	 */
	public static function image_scale_and_crop(stdClass $image, $width, $height) {
		$scale = max($width / $image->info['width'], $height / $image->info['height']);
		$x = ($image->info['width'] * $scale - $width) / 2;
		$y = ($image->info['height'] * $scale - $height) / 2;
	
		if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
			return image_crop($image, $x, $y, $width, $height);
		}
		return FALSE;
	}
	
	/**
	 * Scales image dimensions while maintaining aspect ratio.
	 *
	 * The resulting dimensions can be smaller for one or both target dimensions.
	 *
	 * @param $dimensions
	 *   Dimensions to be modified - an array with components width and height, in
	 *   pixels.
	 * @param $width
	 *   The target width, in pixels. If this value is NULL then the scaling will be
	 *   based only on the height value.
	 * @param $height
	 *   The target height, in pixels. If this value is NULL then the scaling will
	 *   be based only on the width value.
	 * @param $upscale
	 *   Boolean indicating that images smaller than the target dimensions will be
	 *   scaled up. This generally results in a low quality image.
	 *
	 * @return
	 *   TRUE if $dimensions was modified, FALSE otherwise.
	 *
	 * @see image_scale()
	 */
	public static function image_dimensions_scale(array &$dimensions, $width = NULL, $height = NULL, $upscale = FALSE) {
		$aspect = $dimensions['height'] / $dimensions['width'];
	
		// Calculate one of the dimensions from the other target dimension,
		// ensuring the same aspect ratio as the source dimensions. If one of the
		// target dimensions is missing, that is the one that is calculated. If both
		// are specified then the dimension calculated is the one that would not be
		// calculated to be bigger than its target.
		if (($width && !$height) || ($width && $height && $aspect < $height / $width)) {
			$height = (int) round($width * $aspect);
		}
		else {
			$width = (int) round($height / $aspect);
		}
	
		// Don't upscale if the option isn't enabled.
		if (!$upscale && ($width >= $dimensions['width'] || $height >= $dimensions['height'])) {
			return FALSE;
		}
	
		$dimensions['width'] = $width;
		$dimensions['height'] = $height;
		return TRUE;
	}
	
	/**
	 * Scales an image while maintaining aspect ratio.
	 *
	 * The resulting image can be smaller for one or both target dimensions.
	 *
	 * @param $image
	 *   An image object returned by image_load().
	 * @param $width
	 *   The target width, in pixels. If this value is NULL then the scaling will
	 *   be based only on the height value.
	 * @param $height
	 *   The target height, in pixels. If this value is NULL then the scaling will
	 *   be based only on the width value.
	 * @param $upscale
	 *   Boolean indicating that files smaller than the dimensions will be scaled
	 *   up. This generally results in a low quality image.
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_dimensions_scale()
	 * @see image_load()
	 * @see image_scale_and_crop()
	 */
	public static function image_scale(stdClass $image, $width = NULL, $height = NULL, $upscale = FALSE) {
		$dimensions = $image->info;
	
		// Scale the dimensions - if they don't change then just return success.
		if (!self::image_dimensions_scale($dimensions, $width, $height, $upscale)) {
			return TRUE;
		}
	
		return self::image_resize($image, $dimensions['width'], $dimensions['height']);
	}
	
	/**
	 * Resizes an image to the given dimensions (ignoring aspect ratio).
	 *
	 * @param $image
	 *   An image object returned by image_load().
	 * @param $width
	 *   The target width, in pixels.
	 * @param $height
	 *   The target height, in pixels.
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_load()
	 * @see image_gd_resize()
	 */
	public static function image_resize(stdClass $image, $width, $height) {
		$width = (int) round($width);
		$height = (int) round($height);
	
		return self::image_gd_resize($image, $width, $height);
	}
	
	/**
	 * Rotates an image by the given number of degrees.
	 *
	 * @param $image
	 *   An image object returned by image_load().
	 * @param $degrees
	 *   The number of (clockwise) degrees to rotate the image.
	 * @param $background
	 *   An hexadecimal integer specifying the background color to use for the
	 *   uncovered area of the image after the rotation. E.g. 0x000000 for black,
	 *   0xff00ff for magenta, and 0xffffff for white. For images that support
	 *   transparency, this will default to transparent. Otherwise it will
	 *   be white.
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_load()
	 * @see image_gd_rotate()
	 */
	public static function image_rotate(stdClass $image, $degrees, $background = NULL) {
		return image_toolkit_invoke('rotate', $image, array($degrees, $background));
	}
	
	/**
	 * Crops an image to a rectangle specified by the given dimensions.
	 *
	 * @param $image
	 *   An image object returned by image_load().
	 * @param $x
	 *   The top left coordinate, in pixels, of the crop area (x axis value).
	 * @param $y
	 *   The top left coordinate, in pixels, of the crop area (y axis value).
	 * @param $width
	 *   The target width, in pixels.
	 * @param $height
	 *   The target height, in pixels.
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_load()
	 * @see image_scale_and_crop()
	 * @see image_gd_crop()
	 */
	public static function image_crop(stdClass $image, $x, $y, $width, $height) {
		$aspect = $image->info['height'] / $image->info['width'];
		if (empty($height)) $height = $width / $aspect;
		if (empty($width)) $width = $height * $aspect;
	
		$width = (int) round($width);
		$height = (int) round($height);
	
		return  self::image_gd_crop($image, $x, $y, $width, $height);//image_toolkit_invoke('crop', $image, array($x, $y, $width, $height));
	}
	
	/**
	 * Converts an image to grayscale.
	 *
	 * @param $image
	 *   An image object returned by image_load().
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_load()
	 * @see image_gd_desaturate()
	 */
	public static function image_desaturate(stdClass $image) {
		return image_toolkit_invoke('desaturate', $image);
	}
	
	/**
	 * Loads an image file and returns an image object.
	 *
	 * Any changes to the file are not saved until image_save() is called.
	 *
	 * @param $file
	 *   Path to an image file.
	 * @param $toolkit
	 *   An optional, image toolkit name to override the default.
	 *
	 * @return
	 *   An image object or FALSE if there was a problem loading the file. The
	 *   image object has the following properties:
	 *    - 'source' - The original file path.
	 *    - 'info' - The array of information returned by image_get_info()
	 *    - 'toolkit' - The name of the image toolkit requested when the image was
	 *      loaded.
	 *   Image toolkits may add additional properties. The caller is advised not to
	 *   monkey about with them.
	 *
	 * @see image_save()
	 * @see image_get_info()
	 * @see image_get_available_toolkits()
	 * @see image_gd_load()
	 */
	public static function image_load($file, $toolkit = FALSE) {
		if (!$toolkit) {
			$toolkit = image_get_toolkit();
		}
		if ($toolkit) {
			$image = new stdClass();
			$image->source = $file;
			$image->info = image_get_info($file, $toolkit);
			if (isset($image->info) && is_array($image->info)) {
				$image->toolkit = $toolkit;
				if (image_toolkit_invoke('load', $image)) {
					return $image;
				}
			}
		}
		return FALSE;
	}
	
	/**
	 * Closes the image and saves the changes to a file.
	 *
	 * @param $image
	 *   An image object returned by image_load(). The object's 'info' property
	 *   will be updated if the file is saved successfully.
	 * @param $destination
	 *   Destination path where the image should be saved. If it is empty the
	 *   original image file will be overwritten.
	 *
	 * @return
	 *   TRUE on success, FALSE on failure.
	 *
	 * @see image_load()
	 * @see image_gd_save()
	 */
	public static function image_save(stdClass $image, $destination = NULL) {
		if (empty($destination)) {
			$destination = $image->source;
		}
		if ($return = image_toolkit_invoke('save', $image, array($destination))) {
			// Clear the cached file size and refresh the image information.
			clearstatcache();
			$image->info = image_get_info($destination, $image->toolkit);
	
			if (drupal_chmod($destination)) {
				return $return;
			}
		}
		return FALSE;
	}
	
	/**
	 * @} End of "defgroup image".
	 */
	
	/**
	 * Returns the scheme of a URI (e.g. a stream).
	 *
	 * @param $uri
	 *   A stream, referenced as "scheme://target".
	 *
	 * @return
	 *   A string containing the name of the scheme, or FALSE if none. For example,
	 *   the URI "public://example.txt" would return "public".
	 *
	 * @see file_uri_target()
	 */
	public static function file_uri_scheme($uri) {
		$position = strpos($uri, '://');
		return $position ? substr($uri, 0, $position) : FALSE;
	}

	public static function tiffToPng($fichero, $numeroPagina){ 
	
		//echo 'Fic:'.$fichero;
		if (!file_exists($fichero)) die('No existe el fichero: '.$fichero);
		try {
			$im = new Imagick($fichero.'['.$numeroPagina.']');
			$im->setimageformat('png');
		} catch (Excepcion $e){
			die($e);
		}
		header('Content-type:image/png');
		echo $im->getimageblob();
		die();
	}
	public static function getNumeroImagenes($fichero){
		$im = new Imagick();
		$im->setResourceLimit(imagick::RESOURCETYPE_MEMORY, 256);
$im->setResourceLimit(imagick::RESOURCETYPE_MAP, 256);
$im->setResourceLimit(imagick::RESOURCETYPE_AREA, 1512);
$im->setResourceLimit(imagick::RESOURCETYPE_FILE, 768);
$im->setResourceLimit(imagick::RESOURCETYPE_DISK, -1);
		$im->readimage($fichero);
		return $im->getNumberImages();
	}
	
	public static function tiffToPng64($fichero, $numeroPagina){
	
		//echo 'Fic:'.$fichero;
		if (!file_exists($fichero)) die('No existe el fichero: '.$fichero);
		try {
			$im = new Imagick($fichero.'['.$numeroPagina.']');
			$im->setimageformat('png');
		} catch (Excepcion $e){
			die($e);
		}
		//header('Content-type:image/png');
		$res = 'data:image/png;base64,'.base64_encode($im->getimageblob());
		echo $res;
		die();
	}
	
	
}