mrpatg
mrpatg

Reputation: 10117

php upload image, rename, thumbnail, and save both

Ive been looking at the move_upload_files function, but i dont think thats what i need.

I need to upload a picture (max size 2mb png, jpg, gif only) then rename it, then create a thumbnail of it, and save both to the same directory. I figure ill upload/rename the main file first, then take that and create the thumbnail. But what functions should i be looking at to do this?

Upvotes: 1

Views: 15002

Answers (5)

Brock Hensley
Brock Hensley

Reputation: 3645

@Ian Wilkinson php.net

better quality could be obtained using imagecopyresampled()

Upvotes: 0

Ian Wilkinson
Ian Wilkinson

Reputation: 71

if(isset($_FILES['p1']) && $_FILES['p1']['tmp_name'] != ''){

    $sizes = array();
    $sizes['50'] = 50;
    $sizes['150'] = 150;
    $sizes['500'] = 500;

    $prefix = time();
    list(,,$type) = getimagesize($_FILES['p1']['tmp_name']);
    $type = image_type_to_extension($type);

    move_uploaded_file($_FILES['p1']['tmp_name'], 'uploads/'.$prefix.$type);

    $t = 'imagecreatefrom'.$type;
    $t = str_replace('.','',$t);
    $img = $t('uploads/'.$prefix.$type);

    foreach($sizes as $k=>$v){

        $width = imagesx( $img );
        $height = imagesy( $img );

        $new_width = $v;
        $new_height = floor( $height * ( $v / $width ) );

        $tmp_img = imagecreatetruecolor( $new_width, $new_height );
        imagealphablending( $tmp_img, false );
        imagesavealpha( $tmp_img, true );
        imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

        $c = 'image'.$type;
        $c = str_replace('.','',$c);
        $c( $tmp_img, 'uploads/'.$k.'_'.$prefix.$type );

    }//


}//

I use this to upload, rename and create 3 different thumbs, hope this helps someone out.

Upvotes: 7

Gabriel Sosa
Gabriel Sosa

Reputation: 7956

PHPThumb is what you need... Just search in the api for the method that allow you to save the image. regarding upload the image.. here you have a nice tutorial about it

Upvotes: 1

Mehmet Ergut
Mehmet Ergut

Reputation: 1094

Have a look at phpThumb.

Upvotes: 1

karim79
karim79

Reputation: 342635

You will at least need to look at PHP's GD functions, or better yet Imagick for creating thumbs.

There are zillions of tutorials on this, here are a couple:

Or you could just use a ready-made solution, e.g.:

Upvotes: 5

Related Questions