dongwen2794 2017-04-07 05:42
浏览 35

如何在使用php上传图像时压缩多个图像大小?

Below is my code which I tried but there is showing some warning errors:

Warning: getimagesize(C:\xampp\tmp\php2F0B.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\maahima\admin\uploadBulkImages.php on line 55

Warning: imagejpeg() expects parameter 1 to be resource, string given in C:\xampp\htdocs\maahima\admin\uploadBulkImages.php on line 66

I want the code to insert images in folder in bulk with compressed image.

<?php
if(isset($_FILES['file']['tmp_name'])){
    $pro_image = $_FILES['file']['tmp_name'];
    $no_of_file = count($_FILES['file']['tmp_name']);
    $name = ''; $type = ''; $size = ''; $error = '';

    for($i=0;$i < $no_of_file;$i++){
        if(! is_uploaded_file($_FILES['file']['tmp_name'][$i])){
            header("location:add_products.php?error=er8r5r");
        }
        else{
            if(move_uploaded_file($_FILES['file']['tmp_name'][$i],"../products/".$_FILES['file']['name'][$i])){
                if ($_FILES["file"]["error"][$i] > 0) { 
                    $error = $_FILES["file"]["error"];
                }
                else {
                    $image="";
                    $error = "Uploaded image should be jpg or gif or png";
                    $url = '../smallSize-Image/'.$_FILES['file']['name'][$i];
                    echo  $url;
                    $source_url=$_FILES["file"]["tmp_name"][$i];
                    $destination_url=$url;
                    $quality=12;
                    $info = getimagesize($source_url);

                    if ($info['mime'] == 'image/jpeg')
                        $image = imagecreatefromjpeg($source_url);
                    elseif ($info['mime'] == 'image/gif')
                        $image = imagecreatefromgif($source_url);
                    elseif ($info['mime'] == 'image/png')
                        $image = imagecreatefrompng($source_url);

                    imagejpeg($image, $destination_url, $quality);
                    return $destination_url;

                    $buffer = file_get_contents($url);
                    /* Force download dialog... */
                    //header("Content-Type: application/force-download");
                    //header("Content-Type: application/octet-stream");
                    //header("Content-Type: application/download");
                    // header("location:add_products.php?succcess=s8sc5s");
                    /* Don't allow caching... */
                    //  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    /* Set data type, size and filename */
                    //header("Content-Type: application/octet-stream");
                    //header("Content-Length: " . strlen($buffer));
                    //header("Content-Disposition: attachment; filename=$url");
                    /* Send our file... */
                    echo $buffer;
                }
            }
            else{
                header("location:add_products.php?error=er8r5r");
            }
        }  
    }
}
else{
}
?>
  • 写回答

1条回答 默认 最新

  • douhezi2285 2017-04-07 07:32
    关注

    Your script has a lot of illogical features. If you are going to redirect, you need to exit. You should not have a return in the middle of the script, that is somewhat random (probably this is unfinished script and it's inside another function/method?). Here are some things I would do if I were to do this.

    If you don't already have a config that has some absolute defines, I would create one and include it on every initial load page at the top.

    This is tested and works, provided it's implemented correctly and as demonstrated. Use some of it, bits of it, or none of it, but it does work:

    /config.php

    <?php
    define('DS',DIRECTORY_SEPARATOR);
    define('ROOT_DIR',__DIR__);
    define('UPLOAD_DIR',ROOT_DIR.DS.'uploads'.DS.'images');
    define('THUMB_DIR',ROOT_DIR.DS.'uploads'.DS.'thumbs');
    define('VENDOR_DIR',ROOT_DIR.DS.'vendors');
    

    I would consider making some quick functions, in this case a class/method system to complete some simple tasks.

    /vendors/Files.php

    class Files
        {
            /*
            ** @description This will turn a numbered $_FILES array to a normal one
            */
            public  static  function normalize($key = 'file')
                {
                    foreach($_FILES[$key]['tmp_name'] as $fKey => $value) {
                        $FILES[]    =   array(
                            'tmp_name'=>$_FILES[$key]['tmp_name'][$fKey],
                            'name'=>$_FILES[$key]['name'][$fKey],
                            'error'=>$_FILES[$key]['error'][$fKey],
                            'size'=>$_FILES[$key]['size'][$fKey],
                            'type'=>$_FILES[$key]['type'][$fKey]
                        );
                    }
    
                    return $FILES;
                }
            /*
            ** @description I would contain this step into an editable method for
            **              ease of use and reuse.
            */
            public  static  function compress($path, $dest, $quality = 12)
                {
                    $info   =   getimagesize($path);
    
                    if($info['mime'] == 'image/jpeg')
                        $image  =   imagecreatefromjpeg($path);
                    elseif($info['mime'] == 'image/gif')
                        $image  =   imagecreatefromgif($path);
                    elseif($info['mime'] == 'image/png')
                        $image  =   imagecreatefrompng($path);
    
                    imagejpeg($image,$dest,$quality);
                }
        }
    

    Put it all together, in this case I would maybe throw exceptions and save errors to a session. Loop through them on the add_products.php page.

    # Add our config
    include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
    # Add our file handler class (spl_autoload_register() is a better option)
    include(VENDOR_DIR.DS.'Files.php');
    # Observe for file upload
    if(!empty($_FILES['file']['tmp_name'])){
        # Use our handy convert method
        $FILES      =   Files::normalize();
        # Try here
        try {
            # Loop through our normalized file array
            foreach($FILES as $i => $file){
                # Throw error exception here
                if(!is_uploaded_file($file['tmp_name']))
                    throw new Exception('File is not an uploaded document.');
                # I like to add a create directory line or two to cover all bases
                if(!is_dir(UPLOAD_DIR)) {
                    if(!mkdir(UPLOAD_DIR,0755,true))
                        throw new Exception('Upload folder could not be created.');
                }
                # Ditto
                if(!is_dir(THUMB_DIR)) {
                    if(!mkdir(THUMB_DIR,0755,true))
                        throw new Exception('Thumb folder could not be created.');
                }
                # Create an absolute path for the full size upload
                $path   =   UPLOAD_DIR.DS.$file['name'];
                # If no errors and file is moved properly, compress and save thumb
                if(($file["error"]) == 0 && move_uploaded_file($file['tmp_name'],$path))
                    # Create a thumbnail from/after the file you moved, not the temp file
                    Files::compress($path,THUMB_DIR.DS.$file['name']);
                # Throw error on fail
                else
                    throw new Exception('An unknown upload error occurred.');
            }
        }
        # Catch, assign, redirect
        catch (Exception $e) {
            $_SESSION['errors'][]   =   $e->getMessage();
            header("location: add_products.php?error=er8r5r");
            exit;
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大