简体   繁体   English

上传前获取图像的宽度和高度

[英]Get width and height of an image before uploading

I have been trying this code: 我一直在尝试这段代码:

$file_tmp = $_FILES['video_imagen']['tmp_name'];
list($width, $height) = getimagesize($file_tmp);

But it gives me an error. 但这给了我一个错误。 I'm not able to fix it 我无法修复它

UPDATED 更新

Here you have the PHP code that I have developed. 在这里,您有我开发的PHP代码。 How can I fix it. 我该如何解决。 I have been searching for solutions in different forums... 我一直在不同的论坛中寻找解决方案...

I get this error 我得到这个错误

Notice: getimagesize(): Read error! 注意:getimagesize():读取错误! in C:\\wamp\\www\\tapeHD\\include\\php\\database.php on line 282 在第282行的C:\\ wamp \\ www \\ tapeHD \\ include \\ php \\ database.php中

    public static function SubirVideo($titulo, $video_directorio, $imagen_directorio, $user, $descripcion){
        //ID AUTO INCREMENT
        $sql = "INSERT INTO video(nombre, directorio, imagen, visitas, likes, usuario_id, fecha_subida, descripcion) VALUES ($titulo, $video_directorio, $imagen_directorio, 0, 0, $user, NOW(), $descripcion)";
        $resultado = self::Conexion($sql);
        return $resultado;
    }

    public static function SubirVideoErrores(){
        $error = "";

        if(isset($_POST["boton_upload_video"])){
            $uploadImagen = $_FILES['video_imagen']['name'];
            $tipoImagen = $_FILES['video_imagen']['type'];

            $uploadVideo = $_FILES['video_file']['name'];
            $tipoVideo = $_FILES['video_file']['type'];

            $titulo = $_POST["video_title"];
            $descripcion = $_POST["video_description"];

            $directorio = $_SERVER['DOCUMENT_ROOT']."/tapeHD/include/database/usuarios/".$_SESSION["usuario"]."/videos";

            if($tipoImagen == "image/jpeg"){
                $file_tmp = $_FILES['video_imagen']['tmp_name'];
                list($width, $height) = getimagesize($file_tmp);

                if($_FILES['video_imagen']['size'] < (1024000)){
                    if($width != 320 && $height != 180){
                        $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe de ser 320x180</div></div></div>";
                    } else {
                        if($tipoVideo == "video/mp4"){
                            move_uploaded_file($_FILES['video_file']['tmp_name'], $directorio."/".$uploadVideo);
                            move_uploaded_file($_FILES['video_imagen']['tmp_name'], $directorio."/".$uploadImagen);
                            $video_directorio = "include/database/usuarios/".$_SESSION["usuario"]."/videos/".$uploadVideo;
                            $imagen_directorio = "include/database/usuarios/".$_SESSION["usuario"]."/videos/".$uploadImagen;
                            DataBase::SubirVideo($titulo, $video_directorio, $imagen_directorio, $_SESSION["usuario"], $descripcion);
                            $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>Tu video ha sido subido</div></div></div>";
                        } else {
                            $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>El video debe estar en formato .mp4</div></div></div>";
                        }
                    }
                } else {
                    $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen pesa demasiado</div></div></div>";
                }
            } else {
                $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe ser .jpg </div></div></div>";
            }
        }
        return $error;  
    }

HTML 的HTML

            <div class="upload_video_fields">
                <div class="container">
                    <form action="upload.php" method="POST" enctype="multipart/form-data">
                        <div class="video_form left">
                            <input type="text" id="video_title" name="video_title" placeholder="Título del video..." required />
                            <textarea id="video_description" name="video_description" placeholder="Descripción del video..." cols="40" rows="6" aria-required="true" required></textarea>

                        </div>

                        <div class="video_form right">
                            <input type="file" id="video_imagen" name="video_imagen" required />

                            <input type="file" id="video_file" name="video_file" required />
                        </div>
                        <input type="submit" id="boton_upload_video" name="boton_upload_video" class="btn" value="Subir" />
                    </form>
                </div>

                <div class="upload_progress"><div class="bar"></div></div>
            </div>

For multiple file uploads the following is from the manual - just in case you haven't found it. 对于多个文件上传,以下内容来自手册-以防万一您找不到它。 I hope that this provides sufficient guidance when trying to access the variables after upload. 我希望这在上载后尝试访问变量时能提供足够的指导。

-----------------------------------
Example #1 Uploading multiple files
-----------------------------------
<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

When the above form is submitted, the arrays $_FILES['userfile'] , $_FILES['userfile']['name'] , and $_FILES['userfile']['size'] will be initialized.Each of these will be a numerically indexed array of the appropriate values for the submitted files. 提交上述表单后,将初始化数组$_FILES['userfile']$_FILES['userfile']['name']$_FILES['userfile']['size'] 。每个数组将是已提交文件的适当值的数字索引数组。

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. 例如,假设提交文件名/home/test/review.html/home/test/xwp.out In this case, $_FILES['userfile']['name'][0] would contain the value review.html , and $_FILES['userfile']['name'][1] would contain the value xwp.out . 在这种情况下, $_FILES['userfile']['name'][0]将包含值review.html ,而$_FILES['userfile']['name'][1]将包含值xwp.out

Similarly, $_FILES['userfile']['size'][0] would contain review.html 's file size, and so forth. 同样, $_FILES['userfile']['size'][0]将包含review.html的文件大小,依此类推。

The sql in the Subirvideo function looks incorrect as none of the values have quotes around them. Subirvideo函数中的sql看起来不正确,因为这些值周围都没有引号。 Technically there is no need for the quotes around the integer values but can do no harm. 从技术上讲,不需要在整数值前后使用引号,但不会造成任何损害。 I added in the exit statement to the sql so that you can check the result though you say it is fine now. 我在exit语句中添加了sql,以便尽管现在说还可以,但可以检查结果。 The main method SubirVideoErrores has some additional code to resize the uploaded image to the specified max dimensions ( whilst hopefully mantaining the aspect ratio ) 主要方法SubirVideoErrores具有一些附加代码,可将上传的图像调整为指定的最大尺寸(同时希望保持宽高比)

public static function SubirVideo( $titulo, $video_directorio, $imagen_directorio, $user, $descripcion ){
    /* note: 
       Ensure that $titulo and $descripcion are properly escaped to avoid issues with quote marks etc
    */
    $sql = "INSERT INTO `video` ( `nombre`, `directorio`, `imagen`, `visitas`, `likes`, `usuario_id`, `fecha_subida`, `descripcion` )
            VALUES
            ( '$titulo', '$video_directorio', '$imagen_directorio', '0', '0', '$user', now(), '$descripcion' )";

    /* Remove if the exit( sql ) if it looks correct */
    exit( $sql );
    $resultado = self::Conexion( $sql );
    return $resultado;
}

public static function SubirVideoErrores( $force_resize=true ){
    /* set the default value of $force_resize to false if you do not wish resizing by default */
    try{
        $error = "";

        $max_width=320;
        $max_height=180;

        /* I added this so I could set a var rather than use a session for testing, ie: $session_usuario='antonio' etc */
        $session_usuario=$_SESSION["usuario"];

        if( isset( $_POST["boton_upload_video"] ) ){

            $titulo = $_POST["video_title"];
            $descripcion = $_POST["video_description"];

            $uploadImagen = $_FILES['video_imagen']['name'];
            $tipoImagen = $_FILES['video_imagen']['type'];
            $uploadVideo = $_FILES['video_file']['name'];
            $tipoVideo = $_FILES['video_file']['type'];

            /* Check for errors */
            $video_upload_error = intval( $_FILES['video_file']['error'] );
            $image_upload_error = intval( $_FILES['video_imagen']['error'] );

            if( $video_upload_error > 0 or $image_upload_error > 0 ){
                exit('There were errors during the upload process');    
            }

            if( !empty( $uploadVideo ) && !empty( $uploadImagen ) ){

               $directorio = $_SERVER['DOCUMENT_ROOT']."/tapeHD/include/database/usuarios/".$session_usuario."/videos";
               #$directorio = 'c:/temp/uploads_testing';

                if( $tipoImagen !== "image/jpeg"){
                    $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe ser de formato .jpg</div></div></div>";
                    print $error;

                } else {

                    list( $width, $height, $type, $attr ) = getimagesize( $_FILES["video_imagen"]["tmp_name"] );

                    if( $force_resize==true ){
                        /* Resize supplied mage to a maximum of 320x180 if it is larger then these sizes */
                        if( $width > $max_width or $height > $max_height ) {
                            if( $width > $height ){
                                /* landscape */
                                $aspect = $max_width / $width;
                                $new_width = $max_width;
                                $new_height = $height * $aspect;
                            } elseif( $width == $height ){
                                /* square */
                                $new_width=$max_height;
                                $new_height=$max_height;
                            } else {
                                /* portrait */
                                $aspect = $max_height / $height;
                                $new_width = $width * $aspect;
                                $new_height = $max_height;  
                            }

                            $uploadedimgpath=$directorio."/".$uploadImagen;

                            move_uploaded_file( $_FILES['video_file']['tmp_name'], $directorio."/".$uploadVideo );
                            move_uploaded_file( $_FILES['video_imagen']['tmp_name'], $uploadedimgpath );                        

                            $image = @imagecreatetruecolor( $new_width, $new_height );
                            $background_color = @imagecolorallocate( $image, 255, 255, 255 );
                            $source = @imagecreatefromjpeg( $uploadedimgpath );

                            @imagecopyresampled( $image, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height ); 
                            @imagejpeg( $image, $uploadedimgpath, 100 ); 
                            @imagedestroy( $image ); 
                            @imagedestroy( $source );

                            $width=$new_width;
                            $height=$new_height;
                        }
                    } else {
                            $uploadedimgpath=$directorio."/".$uploadImagen;

                            move_uploaded_file( $_FILES['video_file']['tmp_name'], $directorio."/".$uploadVideo );
                            move_uploaded_file( $_FILES['video_imagen']['tmp_name'], $uploadedimgpath );
                    }

                    if( $_FILES['video_imagen']['size'] > 1024000 ){
                        $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen pesa demasiado</div></div></div>";
                        print $error;

                    } else {

                        if( $width == 320 or $height == 180 ){
                            if( $tipoVideo == "video/mp4" ){

                                $video_directorio = "include/database/usuarios/".$session_usuario."/videos/".$uploadVideo;
                                $imagen_directorio = "include/database/usuarios/".$session_usuario."/videos/".$uploadImagen;

                                DataBase::SubirVideo( $titulo, $video_directorio, $imagen_directorio, $session_usuario, $descripcion );

                                $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>Tu video ha sido subido</div></div></div>";
                                print $error;
                            } else {
                                $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>El video debe estar en formato .mp4</div></div></div>";
                                print $error;
                            }
                        } else {
                            $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe de ser 320x180</div></div></div>";
                            print $error;
                        }
                    }
                }
            }
        }
    }catch( Exception $e ){
        exit( $e->getMessage() );   
    }
}

I have tested this and the image and video both get uploaded fine on my system ( with some path changes of course ) and both are readable. 我已经对此进行了测试,并且图像和视频都可以在我的系统上正常上传(当然会进行一些路径更改),并且都可读。 I can watch the uploaed video and view the uploaded image - even those that get resized. 我可以观看放大的视频并查看上传的图像-甚至那些尺寸已调整的图像。 Is the video you upload very large? 您上传的视频很大吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM