Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

image resizer
  • woulndt it be cool to add a image resizer to the upload.php to make life easier on me? :)

    seriously! I think image uploading will be the thing that will be used more than uploading other files!

    2 someone that already has it: please post!
  • I don't have an example to show, but the thing with image resizing is that there are numerous methods to do it. There isnt really a standard way. Most of the resizing is actually done through server modules like "GD" or "imageMagik", just because they are fastest. And that is probably done through one or two commands.
  • Genu is right. There are any number of ways to to perform image processing, and it's very dependent on the the libraries you have installed. Upload processing scripts are not likely to be part of the Uploadify core, but certainly we encourage people to post their versions and implementations for the community at large to benefit and grow.

    To start here a link to a thumbnail creation script I use. You could easily modify to meet your needs of an image resizer
    http://uploadify.com/forum/viewtopic.php?f=5&t=33
  • the uploader.php file:

    1. it places the file in our uploaddir
    2. makes a smaller image of 640px in width
    3.creates a thumbnail of 100px
    4. then it deletes the sourcefile of the server.

    Hope it helps someone!

    [code=php]
        if 
    (!empty($_FILES)) {

            class Image {
                
                var $uploaddir
    ;
                var $quality = 80;
                var $ext;
                var $dst_r;
                var $img_r;
                var $img_w;
                var $img_h;
                var $output;
                var $data;
                var $datathumb;
                
                function setFile
    ($src = null) {
                    $this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
                    if(is_file($src) && ($this->ext == "JPG" OR $this->ext == "JPEG")) {
                        $this->img_r = ImageCreateFromJPEG($src);
                    } elseif(is_file($src) && $this->ext == "PNG") {
                        $this->img_r = ImageCreateFromPNG($src);      
                    
    } elseif(is_file($src) && $this->ext == "GIF") {
                        $this->img_r = ImageCreateFromGIF($src);
                    }
                    $this->img_w = imagesx($this->img_r);
                    $this->img_h = imagesy($this->img_r);
                }
                
                function resize
    ($w = 100) {
                    $h =  $this->img_h / ($this->img_w / $w);
                    $this->dst_r = ImageCreateTrueColor($w, $h);
                    imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $w, $h, $this->img_w, $this->img_h);
                    $this->img_r = $this->dst_r;
                    $this->img_h = $h;
                    $this->img_w = $w;
                }
                
                function createFile
    ($output_filename = null) {
                    if($this->ext == "JPG" OR $this->ext == "JPEG") {
                        imageJPEG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext, $this->quality);
                    } elseif($this->ext == "PNG") {
                        imagePNG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
                    } elseif($this->ext == "GIF") {
                        imageGIF($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
                    }
                    $this->output = $this->uploaddir.$output_filename.'.'.$this->ext;
                }
                
                function setUploadDir
    ($dirname) {
                    $this->uploaddir = $dirname;
                }
                
                function flush
    () {
            $tempFile = $_FILES['Filedata']['tmp_name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
            $targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
                    
                    imagedestroy
    ($this->dst_r);
                    unlink($targetFile);
                    //imagedestroy($this->img_r);
                    
                
    }
                
            
    }
            
            $tempFile 
    = $_FILES['Filedata']['tmp_name'];
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
            $targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
            
            move_uploaded_file 
    ($tempFile, $targetFile);
            
            $image 
    = new Image();
            $image->setFile($targetFile);
            $image->setUploadDir($targetPath);
            $image->resize(640);
            $image->createFile(md5($tempFile));
            $image->resize(100);
            $image->createFile("s_".md5($tempFile));
            $image->flush();
        }
     [/code]
  • If you are using coldfusion you can do this:
    works in cf8 or the 2 open source coldfusion engines - Railo & OpenBD


    <cfif structkeyexists(\"form.filename\")>
    <cfscript>
    thisPath = ExpandPath(\"*.*\");
    thisDirectory = GetDirectoryFromPath(thisPath);
    FileDir = thisDirectory &amp; \"uploads\";
    </cfscript>

    <cfif not DirectoryExists(FileDir)>
    <cfdirectory action=\"create\" directory=\"#FileDir#\" mode=\"777\" >
    </cfif>

    <cffile action=\"upload\" filefield=\"fileData\" destination=\"#FileDir#\" nameconflict=\"makeunique\" mode=\"777\">
    <cfimage action=\"resize\" height=\"100\" width=\"100\" source=\"#FileDir##file.serverFile#\" destination=\"#FileDir#t_#file.serverFile#\" overwrite=\"yes\">
    <cfimage action=\"resize\" height=\"\" width=\"640\" source=\"#FileDir##file.serverFile#\" destination=\"#FileDir##file.serverFile#\" overwrite=\"yes\">

    <cfscript>
    FileDelete(FileDir &amp; file.serverFile)
    writeoutput(1);
    </cfscript>
    </cfif>
  • Hi,
    I've added this in my uploadify.php file :


    if (!empty($_FILES)) {

    class Image {

    var $uploaddir;
    var $quality = 80;
    var $ext;
    var $dst_r;
    var $img_r;
    var $img_w;
    var $img_h;
    var $output;
    var $data;
    var $datathumb;

    function setFile($src = null) {
    $this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
    if(is_file($src) &amp;&amp; ($this->ext == \"JPG\" OR $this->ext == \"JPEG\")) {
    $this->img_r = ImageCreateFromJPEG($src);
    } elseif(is_file($src) &amp;&amp; $this->ext == \"PNG\") {
    $this->img_r = ImageCreateFromPNG($src);
    } elseif(is_file($src) &amp;&amp; $this->ext == \"GIF\") {
    $this->img_r = ImageCreateFromGIF($src);
    }
    $this->img_w = imagesx($this->img_r);
    $this->img_h = imagesy($this->img_r);
    }

    function resize($w = 100) {
    $h = $this->img_h / ($this->img_w / $w);
    $this->dst_r = ImageCreateTrueColor($w, $h);
    imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $w, $h, $this->img_w, $this->img_h);
    $this->img_r = $this->dst_r;
    $this->img_h = $h;
    $this->img_w = $w;
    }

    function createFile($output_filename = null) {
    if($this->ext == \"JPG\" OR $this->ext == \"JPEG\") {
    imageJPEG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext, $this->quality);
    } elseif($this->ext == \"PNG\") {
    imagePNG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
    } elseif($this->ext == \"GIF\") {
    imageGIF($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
    }
    $this->output = $this->uploaddir.$output_filename.'.'.$this->ext;
    }

    function setUploadDir($dirname) {
    $this->uploaddir = $dirname;
    }

    function flush() {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
    $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

    imagedestroy($this->dst_r);
    unlink($targetFile);
    //imagedestroy($this->img_r);

    }

    }

    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
    $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

    move_uploaded_file ($tempFile, $targetFile);

    $image = new Image();
    $image->setFile($targetFile);
    $image->setUploadDir($targetPath);
    $image->resize(640);
    $image->createFile(md5($tempFile));
    $image->resize(100);
    $image->createFile(\"s_\".md5($tempFile));
    $image->flush();
    }



    And it doesn't work, must I change some var or so ?

    When I upload a file, it doesn't upload it...

    And this is my code where is the upload file :

    <script type=\"text/javascript\">// <![CDATA[
    $(document).ready(function() {
    $('#fileInput').uploadify({
    'uploader' : '../uploadify/uploadify.swf',
    'script' : '../uploadify/uploadify.php',
    'cancelImg' : '../uploadify/cancel.png',
    'auto' : true,
    'folder' : '../uploads'
    });
    });
    // ]]></script>


    What must I change to make this resize code to work ?

    Thx for help !
  • Hello,
    the problem come from
    function flush()

    Juste replace flush by what you want
    For example : flushe()
    Do the same at the end of the code :
    $image->flushe();


    But this code doesn't work for png resizing and certainly gif.

    I give you another way :
    <?php
    /******************************/
    /* Cadi Web &amp; Design */
    /* Réalisation de CADI */
    /* @_OPS_@ */
    /* www.cadi-software.com */
    /******************************/

    error_reporting(E_ALL);

    $width = 75;
    $height = 100;

    //$_FILES['fichier']['name'] = str_replace(\" \",\"_\",$_FILES['fichier']['name']);
    //$urltxt = \"http://\".$_SERVER[\"SERVER_NAME\"].\"/news/news_images/\";
    /*** the image file to thumbnail ***/
    $image = $urltxt.$url; // Remplacer $urltxt.$url par le chemin du dossier

    if(!file_exists($image))
    {
    echo '';
    }
    else
    {
    /*** image info ***/
    list($width_orig, $height_orig, $image_type) = getimagesize($image);

    /*** check for a supported image type ***/
    if($image_type > 4)
    {
    echo 'invalid image';
    }
    else
    {
    /*** thumb image name ***/
    $thumb = '../bureau/membre_img/thumbs/'.$url.'';
    $img = $_FILES['fichier']['name'];
    $ext = pathinfo($img, PATHINFO_EXTENSION);


    /*** maintain aspect ratio ***/
    if (($width_orig > $height_orig) &amp;&amp; ($width_orig > $width)) {
    $height = (int) (($width / $width_orig) * $height_orig);
    } elseif($height_orig > 100) {
    $height = 100;
    } else {
    $height = $height_orig;
    }
    if (($height_orig > $width_orig) &amp;&amp; ($height_orig > $height)) {
    $width = (int) (($height / $height_orig) * $width_orig);
    } elseif($width_orig > 75) {
    $width = 75;
    } else {
    $width = $width_orig;
    }

    /*** resample the image ***/
    $image_p = imagecreatetruecolor($width, $height);
    if(($ext == 'jpeg') || ($ext == 'jpg') || ($ext == 'JPEG') || ($ext == 'JPG')) {
    $image = imagecreatefromjpeg($image);
    } elseif ($ext == 'png') {
    $image = imagecreatefrompng($image);
    // fond transparent (pour les png avec transparence)
    imagesavealpha($image_p, true);
    $trans_color = imagecolorallocatealpha($image_p, 0, 0, 0, 127);
    imagefill($image_p, 0, 0, $trans_color);
    } elseif ($ext == 'gif') {
    $image = imagecreatefromgif($image);
    // fond transparent (pour les gifs avec transparence)
    $red = rand(0,255);
    $green = rand(0,255);
    $blue = rand(0,255);
    $transparent = imagecolorallocate($image_p, $red, $green, $blue);
    imagefill($image_p, 0, 0, $transparent);
    imagecolortransparent($image_p, $transparent);
    imagetruecolortopalette($image_p, false, 256);
    }
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

    /*** write the file to disc ***/
    if(!is_writeable(dirname($thumb)))
    {
    echo 'Impossible d\'enregistrer l\'image dans le dossier ' . dirname($thumb);
    }
    else
    {
    if ($ext == 'png') {
    imagepng($image_p, $thumb, 9);
    } elseif ($ext == 'gif') {
    imagegif($image_p, $thumb, 100);
    } else {
    imagejpeg($image_p, $thumb, 100);
    }
    }
    }
    }
    ?>
  • does this also work with images larger than 1MB? because i tried to upload a 1.85MB picture (which isn't too big), but it doesnt create a resized image - it only uploads the original file
    what do i have to change in order to make it work?

    edit: ok nvr mind i found it! for those who want to upload 1MB+ files, put this in the first line of the php:
    ini_set('memory_limit', '100M'); 

    it allows to upload files up 'till 100MB
  • stop spamming plz! you're ruining this great topic!
  • Kenneth,

    You just have to change this code

    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';

    to

    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';


    and also edit this code


    function flush() {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
    $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

    imagedestroy($this->dst_r);
    unlink($targetFile);
    //imagedestroy($this->img_r);

    }

    to

    function flush() {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
    $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

    imagedestroy($this->dst_r);
    unlink($targetFile);
    imagedestroy($this->img_r);

    }

    then upload resizer will work.

    Hope it helps you.

    Thanks ThCrow for nice code... i will be using it on my future project.

    Have a great day all.
  • function resizeimg($filename, $smallimage, $w, $h) {
    $ratio = $w/$h;
    $size_img = getimagesize($filename);
    if (($size_img[0] < $w) && ($size_img[1] < $h)) {
    if ($size_img[2] == 1) {$src_img = imagecreatefromgif($filename);}
    if ($size_img[2] == 2) {$src_img = imagecreatefromjpeg($filename);}
    if ($size_img[2] == 3) {$src_img = imagecreatefrompng($filename);}
    if ($size_img[2] == 1) {imagegif($src_img, $smallimage);}
    if ($size_img[2] == 2) {imagejpeg($src_img, $smallimage);}
    if ($size_img[2] == 3) {imagepng($src_img, $smallimage);}
    return true;
    }
    elseif (($size_img[0] >= $w) || ($size_img[1] >= $h)) {
    $src_ratio = $size_img[0]/$size_img[1];
    if ($ratio < $src_ratio) { $h = $w/$src_ratio;}
    else { $w = $h*$src_ratio;}
    $dest_img = imagecreatetruecolor($w, $h);
    if ($size_img[2] == 1) {$src_img = imagecreatefromgif($filename);}
    if ($size_img[2] == 2) {$src_img = imagecreatefromjpeg($filename);}
    if ($size_img[2] == 3) {$src_img = imagecreatefrompng($filename);}
    if (!imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $w, $h, $size_img[0], $size_img[1])) return false;
    $path_parts=pathinfo($smallimage);
    if ($size_img[2] == 1) {imagegif($dest_img, $smallimage);}
    if ($size_img[2] == 2) {imagejpeg($dest_img, $smallimage);}
    if ($size_img[2] == 3) {imagepng($dest_img, $smallimage);}
    $sizei = getimagesize("{$smallimage}");
    imagedestroy($dest_img);
    imagedestroy($src_img);
    return true;
    }
    }

    Implementing:

    resizeimg($tempFile, $targetFile, 1024, 1024); 1024x1024 - maximum vertical and horizontal size of image.
  • I've updated theCrow's resize function to resize the longest side, instead of just the width (for portrait style photos).

    Just replace the contents of your uploadify.php file with the code below. Cheers.


    if (!empty($_FILES)) {

    class Image {

    var $uploaddir;
    var $quality = 80;
    var $ext;
    var $dst_r;
    var $img_r;
    var $img_w;
    var $img_h;
    var $output;
    var $data;
    var $datathumb;

    function setFile($src = null) {
    $this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
    if(is_file($src) && ($this->ext == "JPG" OR $this->ext == "JPEG")) {
    $this->img_r = ImageCreateFromJPEG($src);
    } elseif(is_file($src) && $this->ext == "PNG") {
    $this->img_r = ImageCreateFromPNG($src);
    } elseif(is_file($src) && $this->ext == "GIF") {
    $this->img_r = ImageCreateFromGIF($src);
    }
    $this->img_w = imagesx($this->img_r);
    $this->img_h = imagesy($this->img_r);
    }

    function resize($largestSide = 100) {
    $width = imagesx($this->img_r);
    $height = imagesy($this->img_r);
    $newWidth = 0;
    $newHeight = 0;

    if($width > $height){
    $newWidth = $largestSide;
    $newHeight = $height * ($newWidth / $width);
    }else{
    $newHeight = $largestSide;
    $newWidth = $width * ($newHeight / $height);
    }

    $this->dst_r = ImageCreateTrueColor($newWidth, $newHeight);
    imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    $this->img_r = $this->dst_r;
    $this->img_h = $newHeight;
    $this->img_w = $newWidth;
    }

    function createFile($output_filename = null) {
    if($this->ext == "JPG" OR $this->ext == "JPEG") {
    imageJPEG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext, $this->quality);
    } elseif($this->ext == "PNG") {
    imagePNG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
    } elseif($this->ext == "GIF") {
    imageGIF($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
    }
    $this->output = $this->uploaddir.$output_filename.'.'.$this->ext;
    }

    function setUploadDir($dirname) {
    $this->uploaddir = $dirname;
    }

    function flush() {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
    $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

    imagedestroy($this->dst_r);
    unlink($targetFile);
    imagedestroy($this->img_r);

    }

    }

    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
    $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

    move_uploaded_file ($tempFile, $targetFile);

    $image = new Image();
    $image->setFile($targetFile);
    $image->setUploadDir($targetPath);
    $image->resize(800);
    $image->createFile(md5($tempFile));
    $image->flush();
    }
  • I think the best approach for image resizing would be to build it into the flash uploader. ie let the resizing take place locally BEFORE uploading. In my case I am uploading images to my site from my camera with each image being around 2-5MB in size. The server downsizes them to <100kb for web display. Now if uploadify could do the resizing first before uploading then it should be quicker on average to upload photos directly from my camera to my website. Flash could run two (or more) threads so that resizing images in the queue could be done whilst uploading others. If I get time I might break out Flash CS4 and try to add this to uploadify.fla but if someone's already done it then I would love to get a copy of that version of the SWF
  • Hi, this is my version of the uploadify.php. It changes the name of the file, giving a new random name with the function "aleatorio", and lately, resize the image before save it, with the function tamanio_nuevo_foto.

    The code:
    function aleatorio($length=15,$uc=TRUE,$n=TRUE,$sc=FALSE)

    {

    $source = 'abcdefghijklmnopqrstuvwxyz';

    if($uc==1) $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    if($n==1) $source .= '1234567890';

    if($sc==1) $source .= '|@#~$%()=^*+[]{}-_';

    if($length>0){

    $rstr = "";

    $source = str_split($source,1);

    for($i=1; $i<=$length; $i++){<br />
    mt_srand((double)microtime() * 1000000);

    $num = mt_rand(1,count($source));

    $rstr .= $source[$num-1];

    }



    }

    return $rstr;

    }
    /*crea una imagen de x.px de ancho manteniendo la proporción y la guarda en el directorio dado */
    function tamano_nuevo_foto($im_or,$ancho_nv,$dir_nv)

    {

    $img = imagecreatefromjpeg($im_or);

    $datos = getimagesize($im_or);

    $ancho = $datos[0];

    $alto = $datos[1];

    if ($ancho > $ancho_nv) //Si la imagen no lelga al máximo no la tocamos.

    {

    $prop = $alto / $ancho; /*Calculo la proporcion entre la or y la nv (lo miltiplicamos por mil para evitar problemas con decimales */

    $alto_nv = round($ancho_nv * $prop); //Sacamos la nueva altura

    }

    else

    {

    $ancho_nv = $ancho;

    $alto_nv = $alto;

    }

    $im_nv = imagecreatetruecolor($ancho_nv,$alto_nv);

    imagecopyresampled($im_nv, $img, 0, 0, 0, 0, $ancho_nv, $alto_nv, $ancho, $alto);

    imagejpeg($im_nv,$dir_nv);

    imagedestroy($im_nv);

    }


    if (!empty($_FILES)) {
    $tipo = strtolower(substr(strrchr($_FILES['Filedata']['name'], '.'),1));
    $nombre2 = aleatorio(25,TRUE,TRUE,FALSE);
    $exten = $dnd . $nombre2 . "." . $tipo;
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';

    $targetFile = str_replace('//','/',$targetPath) . $nombre2 . '.' . $tipo;

    tamano_nuevo_foto($tempFile, 600, $targetFile);


    echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);

    }

    I wish it'll be useful for somebody.
  • Hi all,

    I am working with ThCrow's solution here (huge thanks) and have two questions:
    1. How can I get the thumb file into a different folder?
    2. How can I grab the new md5 encoded name of the file so I can use it to store in an MySQL DB?

    Any help on this would be awesome and greatly appreciated.
  • Thanks alot bcode for the final version and ThCrow for the first sample. :-)
  • Is there any way to modify bcode's script so that it doesn't resize the image if it is already within the constraints of the resizing? For instance, if I set it the resize variable to 800, and upload a 90x60 image, it stretches the image to 800 pizels wide, distorting it all to hell. Thanks!