You are here

function _imce_unzip_scale_image in IMCE unzip 7

Same name and namespace in other branches
  1. 6 imce_unzip.module \_imce_unzip_scale_image()

Private function for scaling and saving images.

1 call to _imce_unzip_scale_image()
_imce_unzip_file_unzip in ./imce_unzip.module
Unzip the files and check extensions.

File

./imce_unzip.module, line 365
Main functions for IMCE unzip module

Code

function _imce_unzip_scale_image($imce, $file, $maxw, $maxh, $buf, $zdir) {

  // Write contents of buffer
  $temp_file_path = tempnam(realpath(file_directory_temp() . '/_imce_unzip'), 'imce');
  register_shutdown_function('file_unmanaged_delete', $temp_file_path);
  $fp = fopen($temp_file_path, "w+");
  fwrite($fp, $buf);
  fclose($fp);

  // Load and attempt to scale the image from buffer
  $image = image_load($temp_file_path);
  if (!$image || !image_scale($image, $maxw, $maxh)) {
    drupal_set_message(t('%filename cannot be resized.', array(
      '%filename' => utf8_encode($file->filename),
    ), array(
      'context' => 'error',
    )), 'error', FALSE);
    return FALSE;
  }

  // Copy scaled image to another temp file (this time with stream wrapper URI)
  if (!($tempuri = drupal_tempnam('temporary://_imce_unzip/', 'imce'))) {
    return FALSE;
  }
  register_shutdown_function('file_unmanaged_delete', $tempuri);
  if (!image_save($image, $tempuri) || !$image->info) {
    return FALSE;
  }
  $imguri = imce_dir_uri($imce) . ($zdir != '.' ? $zdir . '/' : '') . $file->filename;

  // stream wrapper URI relative to IMCE working directory
  // Create file object
  $new_file = new stdClass();
  $new_file->uri = $imguri;
  $new_file->filename = basename($new_file->uri);

  // Validate quota
  $new_file->filesize = $image->info['file_size'];
  $quotadiff = $new_file->filename == $file->filename ? -$file->filesize : 0;
  if (!imce_validate_quotas($new_file, $imce, $quotadiff)) {
    return FALSE;
  }

  // Build the rest of the file object
  $new_file->uid = $imce['uid'];
  $new_file->filemime = $image->info['mime_type'];
  $new_file->status = FILE_STATUS_PERMANENT;
  $new_file->timestamp = REQUEST_TIME;

  // Copy from temp to file uri
  $destination = $new_file->uri;
  $new_file->uri = $tempuri;
  if (!($new_file = file_copy($new_file, $destination, FILE_EXISTS_REPLACE))) {
    return FALSE;
  }
  imce_file_register($new_file);

  // Add to the list
  $new_file->width = $image->info['width'];
  $new_file->height = $image->info['height'];
  imce_add_file($new_file, $imce);

  // If entry for file already exists in database, register update
  $update = array();
  if ($_file = db_query("SELECT f.* FROM {file_managed} f WHERE f.uri = :path", array(
    ':path' => $new_file->uri,
  ))
    ->fetchObject()) {
    $new_file->fid = $_file->fid;
    $new_file->uid = $_file->uid;
    $update[] = 'fid';
  }

  // Register file in database
  drupal_write_record('file_managed', $new_file, $update);
  return $new_file;
}