如何在上传时调整多张图片的大小?

时间:2014-06-10 16:10:38

标签: php jquery resize

我有一个多上传器的代码,上传器运行良好。我要求在上传时调整其他代码来调整上传的图片大小。

以下是代码:

<div class="formItem">  
    <div id="mulitplefileuploader">Upload</div>
    <div id="status"></div>
    <script>

    $(document).ready(function()
    {
        var settings = {
            url: "uploadnew.php",
            method: "POST",
            allowedTypes:"jpg,png,gif,doc,pdf,zip",
            fileName: "myfile",
            multiple: true,
            onSuccess:function(files,data,xhr)
            {
                $("#status").html("<font color='green'>Upload is success</font>");

            },
            afterUploadAll:function()
            {
                alert("all images uploaded!!");
            },
            onError: function(files,status,errMsg)
            {       
                $("#status").html("<font color='red'>Upload is Failed</font>");
            }
        }
        $("#mulitplefileuploader").uploadFile(settings);

    });
    </script>               
</div>

这是uploadnew.php:

<?php
//If directory doesnot exists create it.
$output_dir = "uploads/";

if(isset($_FILES["myfile"]))
{
    $ret = array();

    $error =$_FILES["myfile"]["error"];
    {

        if(!is_array($_FILES["myfile"]['name'])) //single file
        {
            $RandomNum   = time();

            $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name']));
            $ImageType      = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.

            $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
            $ImageExt       = str_replace('.','',$ImageExt);
            $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
            $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

            move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $NewImageName);
             //echo "<br> Error: ".$_FILES["myfile"]["error"];

                 $ret[$fileName]= $output_dir.$NewImageName;


        }
        else
        {
            $fileCount = count($_FILES["myfile"]['name']);
            for($i=0; $i < $fileCount; $i++)
            {
                $RandomNum   = time();

                $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i]));
                $ImageType      = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.

                $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
                $ImageExt       = str_replace('.','',$ImageExt);
                $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
                $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

                $ret[$NewImageName]= $output_dir.$NewImageName;
                move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$NewImageName );




            }
        }
    }
    echo json_encode($ret);
}
?>

2 个答案:

答案 0 :(得分:0)

你可以在&#34;单个文件&#34;周围添加一个foreach($ _ FILES){}代码你已经不得不循环文件?因为它可以在一个文件或一百个文件中工作。

此外,一个合理的谷歌搜索找到了不少结果,但这里有一个选项,通过一些调整可以调整,以满足您的需求从以下网址:

http://www.gilbertocortez.com/blog/php/image-resizing-with-php

<?PHP
//Image Target
$pic = ‘images/’.$_GET['pic'];
//Set Max Sizes
$max_height = 48;
$max_width = 48;
//Get Image Size
$size= getimagesize($pic);
//Set Ratios
$width_ratio  = ($size[0] / $max_width);
$height_ratio = ($size[1] / $max_height);
if($width_ratio >=$height_ratio){
    $ratio = $width_ratio; 
} else {
    $ratio = $height_ratio;
}
//Set new size
$new_width    = ($size[0] / $ratio);
$new_height   = ($size[1] / $ratio);
//Set header
header(“Content-Type: image/jpeg”);
//Create Image
$src_img = imagecreatefromjpeg($pic);
$thumb = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($thumb, $src_img, 0,0,0,0,$new_width,$new_height,$size[0],$size[1]);
imagejpeg($thumb);
imagedestroy($src_img);
imagedestroy($thumb);
?>

答案 1 :(得分:0)

此代码对我有用:

<?php

function imgMaxHeight( $ImageName, $output_dir, $pathToResized, $resizedHeight ) {
    $info = pathinfo($output_dir . $ImageName);
    if ( strtolower($info['extension']) == 'jpg' ) {
      $img = imagecreatefromjpeg( "{$output_dir}{$ImageName}" );
      $width = imagesx( $img );
      $height = imagesy( $img );
      $new_width = floor( $width * ( $resizedHeight / $height ) );
      $new_height = $resizedHeight;
//      $new_width = $thumbWidth;
//      $new_height = floor( $height * ( $thumbWidth / $width ) );
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );
      imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      imagejpeg( $tmp_img, "{$pathToResized}{$ImageName}" );
    }else{
      $img = imagecreatefrompng( "{$output_dir}{$ImageName}" );
      $width = imagesx( $img );
      $height = imagesy( $img );
      $new_width = floor( $width * ( $resizedHeight / $height ) );
      $new_height = $resizedHeight;
//      $new_width = $thumbWidth;
//      $new_height = floor( $height * ( $thumbWidth / $width ) );
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );
      imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      imagepng( $tmp_img, "{$pathToResized}{$ImageName}" );
    }
} //END fn createThumb



//If directory does not exist, create it.
$output_dir = "uploads/";
$img_dir = "path/to/resized_images/";


if(isset($_FILES["myfile"])){
    $ret = array();
    $error =$_FILES["myfile"]["error"];

    { //UNKNOWN EXTRA OPENING BRACE - REMOVE IT

        if(!is_array($_FILES["myfile"]['name'])) //single file
        {
            $RandomNum   = time();

            $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name']));
            $ImageType      = $_FILES['myfile']['type']; //"image/png", image/jpeg etc.

            $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
            $ImageExt       = str_replace('.','',$ImageExt);
            $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
            $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

            move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $NewImageName);
            //echo "<br> Error: ".$_FILES["myfile"]["error"];


            imgMaxHeight($ImageName, $output_dir, $img_dir, '400');


            $ret[$fileName]= $output_dir.$NewImageName;
        }
        else
        {
            $fileCount = count($_FILES["myfile"]['name']);
            for($i=0; $i < $fileCount; $i++)
            {
                $RandomNum   = time();

                $ImageName      = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i]));
                $ImageType      = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc.

                $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
                $ImageExt       = str_replace('.','',$ImageExt);
                $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
                $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

                $ret[$NewImageName]= $output_dir.$NewImageName;
                move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$NewImageName );


                imgMaxHeight($ImageName, $output_dir, $img_dir, '400');


            }
        } //END IF(!is_array //single/multi files
    } //UNKNOWN EXTRA CLOSING BRACE - REMOVE IT
    echo json_encode($ret);
} //END if(isset($_FILES["myfile"]))

?>