You are here

function image_prepare in Image 5

Same name and namespace in other branches
  1. 5.2 image.module \image_prepare()

Implementation of hook_prepare().

1 call to image_prepare()
image_attach_nodeapi in contrib/image_attach/image_attach.module
Implementation of hook_nodeapi().

File

./image.module, line 325

Code

function image_prepare(&$node, $field_name) {
  if (is_null($field_name)) {
    $field_name = 'image';
  }
  if ($file = file_check_upload($field_name)) {

    // Ensure the file is an image.
    $image_info = image_get_info($file->filepath);
    if (!$image_info || empty($image_info['extension'])) {
      form_set_error($field_name, t('Uploaded file is not a valid image. Only JPG, PNG and GIF files are allowed.'));
      return;
    }

    // Save the file to the temp directory.
    $file = file_save_upload($field_name, _image_filename($file->filename, IMAGE_ORIGINAL, TRUE));
    if (!$file) {
      return;
    }

    // Resize the original.
    $aspect_ratio = $image_info['height'] / $image_info['width'];
    $original_size = image_get_sizes(IMAGE_ORIGINAL, $aspect_ratio);
    if (!empty($original_size['width']) && !empty($original_size['height'])) {
      $result = image_scale($file->filepath, $file->filepath, $original_size['width'], $original_size['height']);
      if ($result) {
        clearstatcache();
        $file->filesize = filesize($file->filepath);
        drupal_set_message(t('The original image was resized to fit within the maximum allowed resolution of %width x %height pixels.', array(
          '%width' => $original_size['width'],
          '%height' => $original_size['height'],
        )));
      }
    }

    // Check the file size limit.
    if ($file->filesize > variable_get('image_max_upload_size', 800) * 1024) {
      form_set_error($field_name, t('The image you uploaded was too big. You are only allowed upload files less than %max_size but your file was %file_size.', array(
        '%max_size' => format_size(variable_get('image_max_upload_size', 800) * 1024),
        '%file_size' => format_size($file->filesize),
      )));
      file_delete($file->filepath);
      return;
    }

    // We're good to go.
    $node->images[IMAGE_ORIGINAL] = $file->filepath;
    $node->rebuild_images = FALSE;
    $node->new_file = TRUE;

    // Call hook to allow other modules to modify the original image.
    module_invoke_all('image_alter', $node, $file->filepath, IMAGE_ORIGINAL);
    _image_build_derivatives($node, TRUE);
  }
}