• Jetzt anmelden. Es dauert nur 2 Minuten und ist kostenlos!

Imagemagick Thumbnails

maria1

Mitglied
Hallo,

Ich versuche gerade etwas zu Coden. Es geht um einen Remote-Image Upload und der Thumbnail funktion von imagemagick.

So soll es laufen:
-> Kopiere Bild von URL (funktioniert)
-> Eintragen in DB (funktioniert ist aber ausgeklammert)
-> Thumbnails erstellen

Ich habe auch ein normales Upload-Script ebenfalls mit der Thumb funktion und das Funktioniert !

Hier der Code:

index.php
Code:
<?php
include('connect_database.php');
    $url = $_POST["url"];
    echo "<div id='abuse_content'>";
    if($url)
    {
    $file = fopen($url,"rb");
    if($file)
    {
    $directory = "./file/"; // Directory to upload files to.
    $valid_exts = array("jpg","jpeg","gif","png"); // default image only extensions
    $ext = end(explode(".",strtolower(basename($url))));
    
    if(in_array($ext,$valid_exts)){
    $rand = rand(10000,99999);
    $filename = $rand . basename($url);
    $newfile = fopen($directory . $filename, "wb"); // creating new file on local server


    if($newfile)
    {
    while(!feof($file))
    {
    // Write the url file to the directory.
    fwrite($newfile,fread($file,1024 * 8),1024 * 8); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
    }
    
    include('uploader_url_thumb.php');
    
    $newfilename = "file/$filename";
    $key = mt_rand(99999,999999);
    $img = getimagesize($newfilename);
    $width = $img[0];
    $height = $img[1];
    $extension = "no";
    $date = date('Y-d-m');
    $size = "10";


    // schreibe in die datenbank mysql_real_escape_string ist empfehlenswert um seine daten gegen sql injections abzusichern 
    $sql_befehl = mysql_query("INSERT INTO file (fileid, filename, filesize, extension, date, width, height, secretkey) VALUES ('', '".mysql_real_escape_string($filename)."', '".mysql_real_escape_string($size)."', '".mysql_real_escape_string($extension)."', '".mysql_real_escape_string($date)."', '".mysql_real_escape_string($width)."', '".mysql_real_escape_string($height)."', '".mysql_real_escape_string($key)."')");
    $lastid = mysql_insert_id();


    echo"<div id='getdetails'>";
    
    //Output small thumb
    echo "
    <div id='output_image'>
    <a href='$newfilename' target='_blank'><img src='$newfilename' height='$height' width='$width' alt=''></a><br />
    $width x $height
    </div>
    "; 
    
     echo "
    <ul>
    <li class='delete_image'><a href='index.php?page=delete_now&key=$keyy'>Delete the image</a></li>
    <li class='fullscreen_image'><a href='$newfilename' target='_blank'>See fullscreen</a></li>
    </ul>
    <input type='text' value='http://michimi2007.vacau.com/$newfilename'/>
    <input type='text' value='<a href=\"http://michimi2007.vacau.com/index.php?page=view&id=$ffid\"><img src=\"http://michimi2007.vacau.com/$newname\" border=\"0\" alt=\"www.Pic-It.com\" /></a>'
    <input type='text' value='{[}URL=http://michimi2007.vacau.com/index.php?page=view&id=$ffid{]}{[}IMG{]}http://michimi2007.vacau.com/$newname{[}/IMG{]}{[}/URL{]}'/>
    
    </div>
    ";


    } else { echo 'Could not establish new file ('.$downloads.$rand.basename($url).') on local server. Be sure to CHMOD your directory to 777.'; }
    } else { echo 'Invalid file type. Please try another file.'; }
    } else { echo 'Could not locate the file: '.$url.''; }
    } else { echo 'Invalid URL entered. Please try again.'; }
    echo "</div>";


?>

Post zu lange...
 
Werbung:
uploader_url_thumb.php

Code:
<?php
require('config.php');








/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$filepath = $newfile;


// Here we will put our resizing code
if (($image_info = @getimagesize($filepath)) !== false) // Let's get some info about our image
{
  $image_width = $image_info[0]; // the _real_ width
  $image_height = $image_info[1]; // the _real_ height


  if ($image_width > $config['max_width'] || $image_height > $config['max_height'])
  {
    if($thumbpath = create_thumbnail($_FILES['url'], $image_width, $image_height)) // Will return thumbnail path on success, 'false' on error
    {
      echo 'Huge success! There is your thumbnail: <a href="'.$filepath.'"><img src="'.$thumbpath.'"/></a>';
    }
    else
    {
      echo 'Less sucess! Could not make a thumbnail, but we did <a href="'.$filepath.'">upload your file</a>!';
    }
  }
  else // Don't need to resize the file
  {
    echo 'Huge success! There is your image: <img src="'.$filepath.'"/></a>';
  }
}
else
{
  echo 'Less sucess! Could not make a thumbnail, but we did <a href="'.$filepath.'">upload your file</a>!';
}




function create_thumbnail($file, $image_width, $image_height)
{
  global $config;


  $mimetype = $file['type'];
  $filepath = $config['upload_path'] . basename($_FILES['url']['name']);
  $destination = $config['thumbnail_path'] . basename($_FILES['url']['name']);


  if ($image_width > $image_height) // if image width is longer than the height...
  {
    $thumb_width = $config['max_width']; // ...use max thumb width...
    $thumb_height = $image_height*($config['max_height']/$image_width); // ...and calculate the max thumb height
  }
  else if ($image_width < $image_height)  // if image width is shorter than the height...
  {
    $thumb_width = $image_width*($config['max_width']/$image_height); // ...calculate the max thumb width...
    $thumb_height = $config['max_height']; // ... and use max thumb height
  }
  else /* $image_width == $image_height */
  {
    $thumb_width = $config['max_width']; // just use max thumb settings
    $thumb_height = $config['max_height'];
  }


  // Only use imagemagick if defined and the passthru function not disabled
  if ($config['imagemagick_path'] && function_exists('passthru'))
  {
    $quality = '';
    $sharpen = '';
    $frame = '';
    $animation = '';
    if ( $mimetype == 'image/jpeg' )
    {
      $quality = '-quality 80'; // 80%
      /** Reduction in linear dimensions below which sharpening will be enabled */
      if ( ( $thumb_width + $thumb_height ) / ( $image_width + $image_height ) < 0.85 )
      {
        $sharpen = '-sharpen 0x0.4';
      }
    }
    elseif ($mimetype == 'image/png')
    {
      $quality = '-quality 95'; // zlib 9, adaptive filtering
    }
    elseif ($mimetype == 'image/gif')
    {
      /**
       * Force thumbnailing of animated GIFs above this size to a single
       * frame instead of an animated thumbnail. ImageMagick seems to
       * get real unhappy and doesn't play well with resource limits. :P
       * Defaulting to 1 megapixel (1000x1000)
       */
      if($image_width * $image_height > 1.0e6)
      {
        // Extract initial frame only
        $frame = '[0]';
      }
      else
      {
        // Coalesce is needed to scale animated GIFs properly
        $animation = ' -coalesce ';
      }
    }
    # Specify white background color, will be used for transparent images
    # in Internet Explorer/Windows instead of default black.


    # Note, we specify "-size {$image_width}" and NOT "-size {$image_width}x{$image_height}".
    # It seems that ImageMagick has a bug wherein it produces thumbnails of
    # the wrong size in the second case.


    if (substr($config['imagemagick_path'], -1) !== '/')
    {
      $config['imagemagick_path'] .= '/';
    }
    $cmd  =
    escapeshellcmd($config['imagemagick_path']) . 'convert' . ((defined('PHP_OS') && preg_match('#^win#i', PHP_OS)) ? '.exe' : '') .
    " {$quality} -background white -size {$image_width} ".
    escapeshellarg($filepath . $frame) .
    $animation .
    // For the -resize option a "!" is needed to force exact size,
    // or ImageMagick may decide your ratio is wrong and slice off
    // a pixel.
    ' -thumbnail ' . escapeshellarg( "{$thumb_width}x{$thumb_height}!" ) .
    " -depth 8 $sharpen " .
    escapeshellarg($destination) . ' 2>&1';


    @passthru($cmd);


    // after converting let's check the file dimensions again
    if (($thumb_info = @getimagesize($destination)) !== false)
    {
      $thumb_image_width = $thumb_info[0]; // the _real_ width
      $thumb_image_height = $thumb_info[1]; // the _real_ height
      if ($thumb_image_width <= $config['max_width'] && $thumb_image_height <= $config['max_height'])
      {
        return $destination; // Let's return the destination file path
      }
    } // Not returning 'false' yet, because we should try the GD library if ImageMagick failed
  }
  if (extension_loaded('gd'))
  {
    /* This code is greatly based on MediaWiki's thumbnail generation process */
    $typemap = array(
    'image/gif'          => array( 'imagecreatefromgif',  'palette',   'imagegif'  ),
    'image/jpeg'         => array( 'imagecreatefromjpeg', 'truecolor', 'imagejpegwrapper' ), // imagejpegwrapper() defined lower
    'image/png'          => array( 'imagecreatefrompng',  'bits',      'imagepng'  ),
    'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette',   'imagewbmp'  ),
    'image/xbm'          => array( 'imagecreatefromxbm',  'palette',   'imagexbm'  ),
    );
    if (!isset( $typemap[$mimetype] ))
    {
      return false; // If there is no MIME type defined, give up
    }


    list($loader, $color_style, $save_type) = $typemap[$mimetype];


    if (!function_exists($loader))
    {
      return false; // no function to open the file with, give up
    }
    $src_image = call_user_func( $loader, $filepath );
    $thumb = imagecreatetruecolor($thumb_width, $thumb_height);


    // Initialise the destination image to transparent instead of
    // the default solid black, to support PNG and GIF transparency nicely
    $background = imagecolorallocate( $thumb, 0, 0, 0 );
    imagecolortransparent( $thumb, $background );
    imagealphablending( $thumb, false );


    if( $color_style == 'palette' ) {
    // Don't resample for paletted GIF images.
    // It may just uglify them, and completely breaks transparency.
    imagecopyresized( $thumb, $src_image,
      0,0,0,0,
      $thumb_width, $thumb_height, $image_width, $image_height );
    } else {
    imagecopyresampled( $thumb, $src_image,
      0,0,0,0,
      $thumb_width, $thumb_height, $image_width, $image_height );
    }


    imagesavealpha( $thumb, true );


    call_user_func( $save_type, $thumb, $destination );
    imagedestroy($thumb);
    imagedestroy($src_image);
    $image_width = $thumb_width;
    $image_height = $thumb_height;
    return true;
  }
  return false;
}


function imagejpegwrapper( $dst_image, $thumb_path ) {
  imageinterlace( $dst_image );
  imagejpeg( $dst_image, $thumb_path, 95 );
}
?>

config.php
Code:
$config = array(
  'upload_path' => 'file/', // This is a directory to save our images
  'thumbnail_path' => 'file/thumbs/', // This is a directory to save our thumbnails
  'max_width' => 150, // Width of our thumbnail
  'max_height' => 150, // Height of our thumbnail
  'imagemagick_path' => '/usr/bin/' // The path to 'convert' or 'convert.exe'
 );

Leider bekomme ich das bild nicht ausgegeben...
im src steht nur <img src="Resource id #7"> ...
Was ist denn falsch ?

Danke
 
Werbung:
Hallo und danke für die Antworten !

Hier ist das Originale Script:

Code:
<?php
require('config.php');


$typeAccepted = array('image/jpeg', 'image/gif', 'image/png');
if (!in_array($_FILES['uploadedfile']['type'], $typeAccepted))
{ // It is not an image!
?>
The uploaded file is not an image! <a href="index.htm">Return to the uploading screen</a>.
<?php
  exit;
}


/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$filepath = $config['upload_path'] . basename($_FILES['uploadedfile']['name']);


if (!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $filepath))
{
  echo 'There was an error uploading the file. Try again.';
  exit;
}
else
{
// Here we will put our resizing code
if (($image_info = @getimagesize($filepath)) !== false) // Let's get some info about our image
{
  $image_width = $image_info[0]; // the _real_ width
  $image_height = $image_info[1]; // the _real_ height


  if ($image_width > $config['max_width'] || $image_height > $config['max_height'])
  {
    if($thumbpath = create_thumbnail($_FILES['uploadedfile'], $image_width, $image_height)) // Will return thumbnail path on success, 'false' on error
    {
      echo 'Huge success! There is your thumbnail: <a href="'.$filepath.'"><img src="'.$thumbpath.'"/></a>';
    }
    else
    {
      echo 'Less sucess! Could not make a thumbnail, but we did <a href="'.$filepath.'">upload your file</a>!';
    }
  }
  else // Don't need to resize the file
  {
    echo 'Huge success! There is your image: <img src="'.$filepath.'"/></a>';
  }
}
else
{
  echo 'Less sucess! Could not make a thumbnail, but we did <a href="'.$filepath.'">upload your file</a>!';
}
}


function create_thumbnail($file, $image_width, $image_height)
{
  global $config;


  $mimetype = $file['type'];
  $filepath = $config['upload_path'] . basename($_FILES['uploadedfile']['name']);
  $destination = $config['thumbnail_path'] . basename($_FILES['uploadedfile']['name']);


  if ($image_width > $image_height) // if image width is longer than the height...
  {
    $thumb_width = $config['max_width']; // ...use max thumb width...
    $thumb_height = $image_height*($config['max_height']/$image_width); // ...and calculate the max thumb height
  }
  else if ($image_width < $image_height)  // if image width is shorter than the height...
  {
    $thumb_width = $image_width*($config['max_width']/$image_height); // ...calculate the max thumb width...
    $thumb_height = $config['max_height']; // ... and use max thumb height
  }
  else /* $image_width == $image_height */
  {
    $thumb_width = $config['max_width']; // just use max thumb settings
    $thumb_height = $config['max_height'];
  }


  // Only use imagemagick if defined and the passthru function not disabled
  if ($config['imagemagick_path'] && function_exists('passthru'))
  {
    $quality = '';
    $sharpen = '';
    $frame = '';
    $animation = '';
    if ( $mimetype == 'image/jpeg' )
    {
      $quality = '-quality 80'; // 80%
      /** Reduction in linear dimensions below which sharpening will be enabled */
      if ( ( $thumb_width + $thumb_height ) / ( $image_width + $image_height ) < 0.85 )
      {
        $sharpen = '-sharpen 0x0.4';
      }
    }
    elseif ($mimetype == 'image/png')
    {
      $quality = '-quality 95'; // zlib 9, adaptive filtering
    }
    elseif ($mimetype == 'image/gif')
    {
      /**
       * Force thumbnailing of animated GIFs above this size to a single
       * frame instead of an animated thumbnail. ImageMagick seems to
       * get real unhappy and doesn't play well with resource limits. :P
       * Defaulting to 1 megapixel (1000x1000)
       */
      if($image_width * $image_height > 1.0e6)
      {
        // Extract initial frame only
        $frame = '[0]';
      }
      else
      {
        // Coalesce is needed to scale animated GIFs properly
        $animation = ' -coalesce ';
      }
    }
    # Specify white background color, will be used for transparent images
    # in Internet Explorer/Windows instead of default black.


    # Note, we specify "-size {$image_width}" and NOT "-size {$image_width}x{$image_height}".
    # It seems that ImageMagick has a bug wherein it produces thumbnails of
    # the wrong size in the second case.


    if (substr($config['imagemagick_path'], -1) !== '/')
    {
      $config['imagemagick_path'] .= '/';
    }
    $cmd  =
    escapeshellcmd($config['imagemagick_path']) . 'convert' . ((defined('PHP_OS') && preg_match('#^win#i', PHP_OS)) ? '.exe' : '') .
    " {$quality} -background white -size {$image_width} ".
    escapeshellarg($filepath . $frame) .
    $animation .
    // For the -resize option a "!" is needed to force exact size,
    // or ImageMagick may decide your ratio is wrong and slice off
    // a pixel.
    ' -thumbnail ' . escapeshellarg( "{$thumb_width}x{$thumb_height}!" ) .
    " -depth 8 $sharpen " .
    escapeshellarg($destination) . ' 2>&1';


    @passthru($cmd);


    // after converting let's check the file dimensions again
    if (($thumb_info = @getimagesize($destination)) !== false)
    {
      $thumb_image_width = $thumb_info[0]; // the _real_ width
      $thumb_image_height = $thumb_info[1]; // the _real_ height
      if ($thumb_image_width <= $config['max_width'] && $thumb_image_height <= $config['max_height'])
      {
        return $destination; // Let's return the destination file path
      }
    } // Not returning 'false' yet, because we should try the GD library if ImageMagick failed
  }
  if (extension_loaded('gd'))
  {
    /* This code is greatly based on MediaWiki's thumbnail generation process */
    $typemap = array(
    'image/gif'          => array( 'imagecreatefromgif',  'palette',   'imagegif'  ),
    'image/jpeg'         => array( 'imagecreatefromjpeg', 'truecolor', 'imagejpegwrapper' ), // imagejpegwrapper() defined lower
    'image/png'          => array( 'imagecreatefrompng',  'bits',      'imagepng'  ),
    'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette',   'imagewbmp'  ),
    'image/xbm'          => array( 'imagecreatefromxbm',  'palette',   'imagexbm'  ),
    );
    if (!isset( $typemap[$mimetype] ))
    {
      return false; // If there is no MIME type defined, give up
    }


    list($loader, $color_style, $save_type) = $typemap[$mimetype];


    if (!function_exists($loader))
    {
      return false; // no function to open the file with, give up
    }
    $src_image = call_user_func( $loader, $filepath );
    $thumb = imagecreatetruecolor($thumb_width, $thumb_height);


    // Initialise the destination image to transparent instead of
    // the default solid black, to support PNG and GIF transparency nicely
    $background = imagecolorallocate( $thumb, 0, 0, 0 );
    imagecolortransparent( $thumb, $background );
    imagealphablending( $thumb, false );


    if( $color_style == 'palette' ) {
    // Don't resample for paletted GIF images.
    // It may just uglify them, and completely breaks transparency.
    imagecopyresized( $thumb, $src_image,
      0,0,0,0,
      $thumb_width, $thumb_height, $image_width, $image_height );
    } else {
    imagecopyresampled( $thumb, $src_image,
      0,0,0,0,
      $thumb_width, $thumb_height, $image_width, $image_height );
    }


    imagesavealpha( $thumb, true );


    call_user_func( $save_type, $thumb, $destination );
    imagedestroy($thumb);
    imagedestroy($src_image);
    $image_width = $thumb_width;
    $image_height = $thumb_height;
    return true;
  }
  return false;
}


function imagejpegwrapper( $dst_image, $thumb_path ) {
  imageinterlace( $dst_image );
  imagejpeg( $dst_image, $thumb_path, 95 );
}
?>

Ansich will ich das nur so ändern sodass ich es mit meinem Remote Upload Script nutzen kann ...
 
Hier ist das URL-Upload Script

Code:
<?php
include('connect_database.php');
    $url = $_POST["url"];
    echo "<div id='abuse_content'>";
    if($url)
    {
    $file = fopen($url,"rb");
    if($file)
    {
    $directory = "./file/"; // Directory to upload files to.
    $valid_exts = array("jpg","jpeg","gif","png"); // default image only extensions
    $ext = end(explode(".",strtolower(basename($url))));
    
    if(in_array($ext,$valid_exts)){
    $rand = rand(10000,99999);
    $filename = $rand . basename($url);
    $newfile = fopen($directory . $filename, "wb"); // creating new file on local server


    if($newfile)
    {
    while(!feof($file))
    {
    // Write the url file to the directory.
    fwrite($newfile,fread($file,1024 * 8),1024 * 8); // write the file to the new directory at a rate of 8kb/sec. until we reach the end.
    }
    
    include('uploader_url_thumb.php');
    
    $newfilename = "file/$filename";
    $key = mt_rand(99999,999999);
    $img = getimagesize($newfilename);
    $width = $img[0];
    $height = $img[1];
    $extension = "no";
    $date = date('Y-d-m');
    $size = "10";


    // schreibe in die datenbank mysql_real_escape_string ist empfehlenswert um seine daten gegen sql injections abzusichern 
    $sql_befehl = mysql_query("INSERT INTO file (fileid, filename, filesize, extension, date, width, height, secretkey) VALUES ('', '".mysql_real_escape_string($filename)."', '".mysql_real_escape_string($size)."', '".mysql_real_escape_string($extension)."', '".mysql_real_escape_string($date)."', '".mysql_real_escape_string($width)."', '".mysql_real_escape_string($height)."', '".mysql_real_escape_string($key)."')");
    $lastid = mysql_insert_id();


    echo"<div id='getdetails'>";
    
    //Output small thumb
    echo "
    <div id='output_image'>
    <a href='$newfilename' target='_blank'><img src='$newfilename' height='$height' width='$width' alt=''></a><br />
    $width x $height
    </div>
    "; 
    
     echo "
    <ul>
    <li class='delete_image'><a href='index.php?page=delete_now&key=$keyy'>Delete the image</a></li>
    <li class='fullscreen_image'><a href='$newfilename' target='_blank'>See fullscreen</a></li>
    </ul>
    <input type='text' value='http://michimi2007.vacau.com/$newfilename'/>
    <input type='text' value='<a href=\"http://michimi2007.vacau.com/index.php?page=view&id=$ffid\"><img src=\"http://michimi2007.vacau.com/$newname\" border=\"0\" alt=\"www.Pic-It.com\" /></a>'
    <input type='text' value='{[}URL=http://michimi2007.vacau.com/index.php?page=view&id=$ffid{]}{[}IMG{]}http://michimi2007.vacau.com/$newname{[}/IMG{]}{[}/URL{]}'/>
    
    </div>
    ";


    } else { echo 'Could not establish new file ('.$downloads.$rand.basename($url).') on local server. Be sure to CHMOD your directory to 777.'; }
    } else { echo 'Invalid file type. Please try another file.'; }
    } else { echo 'Could not locate the file: '.$url.''; }
    } else { echo 'Invalid URL entered. Please try again.'; }
    echo "</div>";


?>

Die URL ist übrigens HTML5 Layout

E
DIT: Nun habe ich zwar eine Ressource aber ich bekomme diese Fehlermeldung.

convert: missing an image filename `file/thumbs/' @ error/convert.c/ConvertImageCommand/2940. Less sucess! Could not make a thumbnail, but we did upload your file!
 
Werbung:
Da kann man eigentlich nur drüber fliegen.
Keiner weiss mehr, welches File(Script) du nun verwendest und welches nicht. Original interessiert nicht, nur dass Script, dass du wirklich verwendest.
Schön wäre, wenn du auch die entsprechenden Codebuttons verwenden würdest.

Soweit ich das sehe, fehlt der Dateipfad. Du arbeitest in deinem Uploadscript mit $filename
PHP:
$newfilename = "file/$filename";
das Thumbscript aber mit $filepath
PHP:
@getimagesize($filepath))
ein
PHP:
print_r($filepath);
in deinem Thumbscript würde wahrscheinlich zeigen, dass es keine Datei gibt die man zu einem Thumb machen könnte.

In deinem Thumbscript könntest du den Pfad anpassen und aus:
PHP:
$filepath = $config['upload_path'] . basename($_FILES['uploadedfile']['name']);
das machen:
PHP:
$filepath = $newfilename;

Achte darauf, dass $newfilename den gesamten Pfad hat.

PS
die beiden Zeilen müssen natürlich getaiuscht werden, aus:
PHP:
include('uploader_url_thumb.php');          
$newfilename = "file/$filename";
wird
PHP:
$newfilename = "file/$filename";
include('uploader_url_thumb.php');
Noch besser, du rufst dein Thumb-Script nach dem setzen in der Datenbank auf.
 
Zuletzt bearbeitet von einem Moderator:
Es ist mir immer unbegreiflich, wie es Leute fertigbringen, so viel Code zu produzieren und dann wie der Ochs vorm Berge vor Fehlermeldungen zu stehen.

Das ist irgendwie so, als würde man einen Pfannkuchen machen und dann am Ende nicht wissen, wie man ihn aus der Pfanne auf den Teller bekommt.

Ist nicht böse gemeint, ich verstehe es wirklich nicht.
 
Zurück
Oben