Posts tagged with imagefield

Avatar-eric-london
Created by Eric.London on 2010-08-28
Tags:
New Comment
 
Please note: the content on this page orginates from ericlondon.com.
I created a Drupal site to host my photography in CCK Imagefield nodes and used Lucene to enhance my search functionality. By default Drupal's search results are text-based so I decided to add some code to show image thumbnails in my search results. I checked out Drupal Lucene's hooks and decided to implement a hook_luceneapi_result_alter() function in my existing module.

<?php
function MYMODULE_luceneapi_result_alter(&$result, $module, $type = NULL) {
  
  // check for node results
  if ($type == 'node') {
  
    // check node type
    if ($result['node']->type == 'image') {
    
      // define an imagecache image path for image thumbnail
      $imagecache_path_thumbnail = file_directory_path() . '/imagecache/thumbnail' . str_replace(file_directory_path(),'',$result['node']->field_image[0]['filepath']);      
      
      // define an imagecache image path for image (large)
      $imagecache_path_large = file_directory_path() . '/imagecache/large' . str_replace(file_directory_path(),'',$result['node']->field_image[0]['filepath']);
    
      // define theme_image() variables
      $alt = check_plain($result['node']->title);
      $title = check_plain($result['node']->title);
      // add rel=lightbox to enable lightbox2 module
      $attributes = array(
        'rel' => 'lightbox',
      );
      // let imagecache define the size
      $getsize = FALSE;
      // generate the image hml
      $image_html = theme('image', $imagecache_path_thumbnail, $alt, $title, $attributes, $getsize);      
    
      if ($image_html) {
                
        // define lightbox link
        $image_link = l(
          $image_html,
          $imagecache_path_large,
          array(
            'html' => true,
            'attributes' => array(
              'rel' => 'lightbox',
            )
          )
        );

        // add data to the result variable, passed by reference
        $result['image_thumbnail'] = $image_link;
        
      }
    
    }
  
  }

}
?>


The above code adds additional data to my search results variables. I then implemented a hook_preprocess_search_result() function in my theme's template.php file to pass this data to the search-result.tpl.php template file.

<?php
function MYTHEME_preprocess_search_result(&$variables) {

  // ...snip...

  // check for lucene node search results
  if ($variables['type']=='luceneapi_node') {

    // check for image
    if ($variables['result']['image_thumbnail']) {    

      // pass additional data to theme template file
      $variables['image_thumbnail'] = $variables['result']['image_thumbnail'];

    }
    
  }

}
?>


And in my theme's search-result.tpl.php template file, I added the following PHP to show the new variable.


<div class="search-result <?php print $search_zebra; ?>">

  <?php if($image_thumbnail): ?>
    <?php print $image_thumbnail; ?>
  <?php endif; ?>

  <!-- ...snip... -->


I also added a few lines of CSS in my theme's style.css file to tidy up the layout.


.search-results.luceneapi_node-results .search-result {
  clear: both;
}

.search-results.luceneapi_node-results .search-result img {
  float: left;
  margin: 0px 20px 20px 0px;
}


The visual results can be seen here on my photo gallery.

Visual search results
Avatar-eric-london
Created by Eric.London on 2010-06-14
Tags:
New Comment
 
Please note: the content on this page orginates from ericlondon.com.
In this tutorial I'll show you how to upload an image using the Forms API, create a new node, and attach the image to the CCK (filefield/imagefield) field. I wrote this code to work with the modules I primarily use for image processing: cck, filefield, imageapi, imagecache, imagefield, mimedetect, and transliteration.

After I installed those modules, I created a new node type (admin/content/types/add) called "Image" and added a single imagefield field.

Image node fields

Next, I created a custom module with a hook_menu() implementation:

<?php

// NOTE: this variable is used through the code,
// so I thought it would be better to put it in a constant
define('IMAGE_UPLOAD_CONTAINER', 'image_upload');

/**
 * Implements hook_menu()
 */
function helper_menu() {

  // create a blank array of menu items
  $items = array();
  
  // define page callback for upload form
  // NOTE: you'll want to restrict permission better [see: access arguments]
  $items['upload'] = array(
    'title' => t('Upload'),
    'description' => t('Upload'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('helper_page_callback_upload_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  
  // return menu items
  return $items;

}
?>


I defined the form function page callback:

<?php

/**
 * Implements page callback for upload form
 */
function helper_page_callback_upload_form() {

  // create an empty form array
  $form = array();
  
  // set the form encoding type
  $form['#attributes']['enctype'] = "multipart/form-data";
  
  // add a file upload file
  $form[IMAGE_UPLOAD_CONTAINER] = array(
    '#type' => 'file',
    '#title' => t('Upload an image'),
  );
   
  // add a submit button
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  
  // return form array
  return $form;

}
?>


This page callback function results in the following form:

Image node form

Then I added the form validation and submit handler functions:

<?php

/**
 * Implements form validation handler
 */
function helper_page_callback_upload_form_validate($form, &$form_state) {

  // if a file was uploaded, process it.
  if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][IMAGE_UPLOAD_CONTAINER])) {

    // validate file extension
    // NOTE: you can ellaborate on this code and add additional validation
    if ($_FILES['files']['type'][IMAGE_UPLOAD_CONTAINER] != 'image/jpeg') {
      form_set_error(IMAGE_UPLOAD_CONTAINER, 'Invalid file extension.');
      return;
    }

    // attempt to save the uploaded file
    $file = file_save_upload(IMAGE_UPLOAD_CONTAINER, array(), file_directory_path());

    // set error if file was not uploaded
    if (!$file) {
      form_set_error(IMAGE_UPLOAD_CONTAINER, 'Error uploading file.');
      return;
    }
       
    // set files to form_state, to process when form is submitted
    $form_state['storage'][IMAGE_UPLOAD_CONTAINER] = $file;
       
  }
  else {
    // set error
    form_set_error(IMAGE_UPLOAD_CONTAINER, 'Error uploading file.');
    return;   
  }

}

/**
 * Implements form submit handler
 */
function helper_page_callback_upload_form_submit($form, &$form_state) {
  
  // create new node object
  $new_node = (object) array(
    'type' => 'image',
    'uid' => $GLOBALS['user']->uid,
    'name' => $GLOBALS['user']->name,
    'title' => t('YOUR NODE TITLE'),
    'status' => 1,
    'field_image' => array(
      (array) $form_state['storage'][IMAGE_UPLOAD_CONTAINER],
    ),
  );
    
  // save node
  node_save($new_node);
  
  // clear form storage, to allow form to submit
  $form_state['storage'] = array();
  
  // redirect user, set message, etc!

}

?>


After using the form to upload an image, the following node was created:

New image node


Avatar-eric-london
Created by Eric.London on 2009-02-12
Tags:
New Comment
 
Please note: the content on this page orginates from ericlondon.com.
A rotating image block can easily be created by using modules that you make already have installed. If you have not already download, install, and enable the following modules:

Views
CCK
FileField
ImageField
ImageAPI
ImageCache


After you've installed these modules, you'll have to adjust the user permissions (admin/user/permissions) to ensure the correct roles have permission to view and administer these modules.

Create a new ImageCache preset (admin/build/imagecache). In my example, I named it "home_rotating". I also added a Scale action to ensure all the images are the same width. It's probably a good thing to check the region width in your theme and adjust the image width accordingly.

Define a new content type (admin/content/types/add). In my example, I named it "image_home_rotating". I left off the body field label because I am only concerned with displaying the image (no other text). Add a new field to the new content type, and choose File for the Field type and Image for the Widget. I named mine "field_image_home_rotating" and labeled it "Image". After adding the field, click on the Display Fields tab. For teaser and Full node, choose the ImageField preset you just created. This will ensure the right image size is used when viewing the node.

Create a new view (admin/build/views/add). Make sure you choose Node for View Type on the first form screen. Add two filters: one for published nodes; and one for node type, and choose the newly created node type. To get a random selection of nodes, add Sort Criteria and choose "Global: Random". Limit the Items to Display to 1. You can leave the Style set to Unformatted and the Row style to Fields. Add a new field and select the newly created image field. When adding the field, the Format setting allows you to change the ImageField preset. If it's not already set, choose your new preset. I also choose to hide the Field label on this step. Add the Block display to the view and save it.

Lastly, assign this block view to the region in your theme and add a few image nodes. As you refresh the page, the image should change.



Avatar-eric-london
Created by Eric.London on 2008-05-01
Tags:
New Comment
 
Please note: the content on this page orginates from ericlondon.com.
Recently, I was using a REST implementation to fetch images from another server. Originally, I wrote the code to save the retrieved images as attachments to a single node. I revised the code to create custom separate custom CCK nodes using the imagefield module. Here's a code snippet that programmatically creates the new nodes...

<?php
$node = new StdClass();
$node->type = 'MYNODETYPE';
$node->title = 'MYNODETITLE';
$file_temp = file_get_contents($tempFile);
$file_temp = file_save_data($file_temp, file_directory_path() .'/' . $fileName, FILE_EXISTS_RENAME);
$node->field_MYIMAGEFIELD = array(
  array(
    'fid' => 'upload',
    'title' => basename($file_temp),
    'filename' => basename($file_temp),
    'filepath' => $file_temp,
    'filesize' => filesize($file_temp),
    'filemime' => mime_content_type($file_temp),
  ),
);
$node->uid = $GLOBALS['user']->uid;
$node->status = 1;
$node->name = $GLOBALS['user']->name;

// save node
node_save($node);
?>
Avatar-eric-london
Created by Eric.London on 2008-04-25
Tags:
New Comment
 
Please note: the content on this page orginates from ericlondon.com.
I created an image node type using the CCK module imagefield. Here is how you can show a preview of the image being deleted on the confirmation page...

<?php
function MYMODULE_form_alter($form_id, &$form) {
  // ...code...
  if ($form_id == 'node_delete_confirm') {
    _MYMODULE_form_alter_node_delete_confirm_user_image($form);
  }
  // ...code...
}

function _MYMODULE_form_alter_node_delete_confirm_user_image(&$form) {
    
  // NOTE: This function assumes the file system path is set to private, which is needs to be for this application
    
  $node = node_load(arg(1));
  if ($node->type != 'user_image') return;
    
  $maxDimension = 300;
  $imagePath = file_create_path($node->field_user_image[0]['filepath']);

  // NOTE: this is a simple function I created that accepts 2 parameters (an image page and a maximum dimension) and it returns resized image dimensions
  $imageDimensions = _MYMODULE_images_resize($imagePath, $maxDimension); 
    
  // create image html
  $img = "<img style='margin: 25px;' width='{$imageDimensions['width']}' height='{$imageDimensions['height']}' src='/system/files/" . $node->field_user_image[0]['filename'] . "' />";
    
  // add image to form
  $form['image_preview'] = array(
    '#value'	=> $img,
    '#weight'	=> 10,
  );
    
}
?>


Here's a screenshot...