减少多个上传的图像大小

时间:2013-03-05 17:44:14

标签: php

我想要一个用户可以一次上传多张图片的网站,如何减少单个用户上传的多张图片的尺寸。
我的代码中的DS是初始化文件中的DIRECTORY_SEPARATOR定义。

    if(isset($_POST['submitImage'])){       
        $file = $_FILES['upload'];
        $errors = array();

        if(empty($file)){
            $errors[] = ' The file could not be empty ';
        }else{  

            foreach( $file['name'] as $key => $value ){
                $extensions = array("jpeg","jpg","png"); 
                $file_ext=explode('.',$file['name'][$key])  ;
                $file_ext=end($file_ext);

                if(in_array($file_ext,$extensions ) === false){
                    $errors[]="extension not allowed";
                }else{

                    $filetmp = $file['tmp_name'][$key];
                    $terget_path = SITE_ROOT.'j2reimage'.DS;
                    $dat = strftime("%Y-%m-%d %H:%M:%S", time());

                    if(file_exists($terget_path)){
                        move_uploaded_file( $filetmp, $terget_path.$file['name'][$key]);                
                        mysql_query("insert into 4j2memberimage values ('', $memmem->id,'{$file['name'][$key]}', '$dat')"); 

                    //end of if file_exists     
                    }else{
                        $errors[] = ' Upload extention could not be locate';            
                    }
                }
                    //redirect_to('inb.php');                   
            }
        }





}

1 个答案:

答案 0 :(得分:0)

来自PHP.net Originaly发表在评论中,但由于修复了OP问题而转而回答。

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>