How can I replace an image using a Form API? I have a form that works great for adding fields, including and image, to a node and saving it.

I want to allow users to edit their fields and change the data, including their image.  I figure there is some way to retrieve and display the current image and then allow the user to upload and save/replace the image with a new one.  I can't figure out how to show a preview of the existing image on the Edit form.  I assume somewhere I should use File_Exists_Replace, but the rest is an overwhelming mystery.  

Here is the code I use for the original form:

  $form['logo'] = array(
  '#title' =&gt; t('Image'),
  '#type' =&gt; 'managed_file',
  '#description' =&gt; t('Only image files will be allowed.'),
  '#default_value' =&gt; variable_get('logo', ''),
  '#upload_location' =&gt; 'public://misc/media',
  '#upload_validators'  =&gt; array(
    'file_validate_extensions' =&gt; array('png gif jpg jpeg'),
    'file_validate_size' =&gt; array(2*1024*1024),
    )
  );


And the submit function:

    // Load the file via file.fid.
    $file = file_load($form_state['values']['logo']);
    // Change status to permanent.
    $file-&gt;status = FILE_STATUS_PERMANENT;
    // Save.
    file_save($file);
    // Record that the module (in this example, cformtwo module) is using the file. 
    file_usage_add($file, 'cformtwo', 'node', 1);  
...
    node_submit($node);
    node_save($node);


I have spent days trying to figure out how to do this.
Your 'logo' variable will be a file id, referring to a row in the file_managed table, so you can use the file_load() function to load the file object, create an image with the details, and attach it to your form field.

This is a (very) basic example:

$logo = variable_get('logo');

$image = '';
if ($logo) {
  // Load the file object
  $file = file_load($logo);

  // Get a thumbnail of the image (just an example)
  $args = array('style_name' =&gt; 'thumbnail', 'path' =&gt; $file-&gt;uri, 'alt' =&gt; 'Alt text');
  $image = theme('image_style', $args);
}

// Prepend it to your field
$form['logo'] = array(
  '#title' =&gt; t('Image'),
  '#type' =&gt; 'managed_file',
  '#description' =&gt; t('Only image files will be allowed.'),
  '#default_value' =&gt; $logo,
  '#upload_location' =&gt; 'public://misc/media',
  '#upload_validators'  =&gt; array(
    'file_validate_extensions' =&gt; array('png gif jpg jpeg'),
    'file_validate_size' =&gt; array(2*1024*1024),
  ),
  '#prefix' =&gt; $image
);