修改图像大小调整脚本以接受PNG并将新图像添加到数组

时间:2019-01-21 15:00:34

标签: php

我有一个脚本,可以在上传后调整图像大小。它在JPG上效果很好,但是我如何修改它也可以接受PNG?然后如何将生成的图像放入准备好附加到电子邮件的新数组中?

// upload original files //
$target_dir = "uploads/";
$file1 = $_FILES["uploaded_file1"]["name"];
$file2 = $_FILES["uploaded_file2"]["name"];
$file3 = $_FILES["uploaded_file3"]["name"];
$file4 = $_FILES["uploaded_file4"]["name"];
$file5 = $_FILES["uploaded_file5"]["name"];
$target_file1 = $target_dir . basename($_FILES["uploaded_file1"]["name"]);
$target_file2 = $target_dir . basename($_FILES["uploaded_file2"]["name"]);
$target_file3 = $target_dir . basename($_FILES["uploaded_file3"]["name"]);
$target_file4 = $target_dir . basename($_FILES["uploaded_file4"]["name"]);
$target_file5 = $target_dir . basename($_FILES["uploaded_file5"]["name"]);
move_uploaded_file($_FILES["uploaded_file1"]["tmp_name"], $target_file1);
move_uploaded_file($_FILES["uploaded_file2"]["tmp_name"], $target_file2);
move_uploaded_file($_FILES["uploaded_file3"]["tmp_name"], $target_file3);
move_uploaded_file($_FILES["uploaded_file4"]["tmp_name"], $target_file4);
move_uploaded_file($_FILES["uploaded_file5"]["tmp_name"], $target_file5);

// create arrays //
$filearray = array($file1,$file2,$file3,$file4,$file5);
$target_filearray = array($target_file1,$target_file2,$target_file3,$target_file4,$target_file5);
$typearray = array("Boiler", "Gas Meter", "Pipe work", "Flue", "Other");

// resize image //
$length = count($filearray);
for ($i = 0; $i < $length; $i++) {
        if (!empty($filearray[$i])){
            $ext = pathinfo($filearray[$i], PATHINFO_EXTENSION);
            $new_file = img_resize("./uploads/", $filearray[$i], $name . " - " . $typearray[$i] . "." . $ext, 1920);
        }
        else {
          // skip this file //
        }
}
function img_resize($path,$tmp_name,$new_name,$new_width){
    list($width, $height) = getimagesize($path . $tmp_name);
    $new_height = abs($new_width * $height / $width);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($path . $tmp_name);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagejpeg($image_p, $path . $new_name);
    return $path . $new_name;
}

// store resized files for attaching //
$filearrayresized = array();

非常感谢您的帮助! 海伦

2 个答案:

答案 0 :(得分:0)

更改

$image = imagecreatefromjpeg($path . $tmp_name);

收件人

$image = imagecreatefromstring(file_get_contents($path . $tmp_name));

对此代码进行了一些更改,将数组定义移至此处并在循环中将新文件推送到其中

// resize image //
$filearrayresized = array();

$length = count($filearray);
for ($i = 0; $i < $length; $i++) {
        if (!empty($filearray[$i])){
            $ext = pathinfo($filearray[$i], PATHINFO_EXTENSION);
            $new_file = img_resize("./uploads/", $filearray[$i], $name . " - " . $typearray[$i] . "." . $ext, 1920);

            $filearrayresized[] = $new_file;

        }
        else {
          // skip this file //
       }
 }

附加到电子邮件是整个问题,因为我认为这是它自己的主题...

答案 1 :(得分:0)

您可以修改该函数,以使对getimagesize的调用返回type属性,然后在创建jpeg或png时使用image_type_to_mime_type派生逻辑。可以很容易地扩展为也包括gif或bmp图像。

我还没有测试以下btw

function img_resize( $path, $tmp_name, $new_name, $new_width ){
    list( $width, $height, $type, $attr ) = getimagesize( $path . $tmp_name );
    $new_height = abs( $new_width * $height / $width );
    $image_p = imagecreatetruecolor($new_width, $new_height);

    switch( image_type_to_mime_type( $type ) ){
        case IMG_PNG:
            $image = imagecreatefrompng( $path . $tmp_name );
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagepng($image_p, $path . $new_name);  
        break;
        case IMG_JPEG:
        case IMG_JPG:

            $image = imagecreatefromjpeg($path . $tmp_name );
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_p, $path . $new_name);         
        break;
    }
    return $path . $new_name;
}

我开始玩了一会儿,发现我确实在上面犯了一个小错误(以为image_type_to_mime_type返回了IMG_XXX类型常量之一,但事实并非如此。这是我在玩耍时拼凑的版本。在测试中这一切似乎都可以正常工作!

<?php

    function resizeImage( $obj=object ){
        try{
            if( is_object( $obj ) ){

                $attribs=['newname','name','tmp_name','error','size','path','width'];
                foreach( $attribs as $attrib ){
                    if( !property_exists( $obj, $attrib ) ) throw new Exception( sprintf( 'Critical: %s is missing from input object', $attrib ) );
                }

                $new    = $obj->newname;
                $path   = $obj->path;
                $name   = $obj->name;
                $tmp    = $obj->tmp_name;
                $err    = $obj->error;
                $size   = $obj->size;
                $ext    = pathinfo( $name, PATHINFO_EXTENSION );
                $width  = $obj->width;


                list( $w, $h, $t, $a )=getimagesize( $tmp );
                $mime   = image_type_to_mime_type( $t );
                $height = abs( $width * ( $h / $w ) );

                $dest = imagecreatetruecolor( $width, $height );
                $target = rtrim( realpath( $path ), DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR . $new;


                switch( $mime ){
                    case 'image/jpeg':
                        $image = imagecreatefromjpeg( $tmp );
                        imagecopyresampled( $dest, $image, 0, 0, 0, 0, $width, $height, $w, $h );
                        imagejpeg( $dest, $target );
                    break;

                    case 'image/png':
                        $image = imagecreatefrompng( $tmp );
                        imagecopyresampled( $dest, $image, 0, 0, 0, 0, $width, $height, $w, $h );
                        imagepng( $dest, $target, 9 );
                    break;

                    case 'image/gif':
                        $image = imagecreatefromgif( $tmp );
                        imagecopyresampled( $dest, $image, 0, 0, 0, 0, $width, $height, $w, $h );
                        imagegif( $dest, $target );
                    break;

                    default:
                        return 'error: '.$mime.' '.$t;
                    break;
                }
                imagedestroy( $image );
                return $target;
            }
        }catch( Exception $e ){
            throw new Exception( sprintf( 'Error:%s, Line:%d',$e->getMessage(),$e->getLine() ) );
        }
    }




    $errors = [];
    $files = [];

    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){

        $width  = 1920;
        $path   = 'c:/temp/fileuploads/';
        $fields = ['uploaded_file1','uploaded_file2','uploaded_file3','uploaded_file4','uploaded_file5'];
        $types  = ['Boiler', 'Gas Meter', 'Pipe work', 'Flue', 'Other'];

        foreach( $fields as $i => $field ){
            try{
                if( !empty( $_FILES[ $field ] ) ){

                    $obj=(object)$_FILES[ $field ];
                    $ext=pathinfo( $obj->name, PATHINFO_EXTENSION );
                    $newname=sprintf( '%s-%s.%s', str_replace( sprintf( '.%s',$ext ), '', $obj->name ), $types[ $i ], $ext );

                    if( $obj->error!=UPLOAD_ERR_OK )throw new Exception( sprintf( 'File upload error: %s', $obj->name ) );


                    /* construct argument for resize function */
                    $obj->newname=$newname;
                    $obj->width=$width;
                    $obj->path=$path;

                    /* resize the image and return the path to the files array */
                    $files[]=resizeImage( $obj );
                }
            }catch( Exception $e ){
                $errors[]=$e->getMessage();
                continue;
            }
        }
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Multiple file upload and resize</title>
        <style>
            body{margin:0;padding:0;display:flex;flex-direction:column;}
            body *{box-sizing:border-box;}
            form{width:60%;height:auto;margin:auto;padding:1rem;}
            input{width:100%;margin:auto;padding:1rem;}
        </style>
    </head>
    <body>
        <form method='post' enctype='multipart/form-data'>
            <?php
                for( $i=1; $i <= 5; $i++ )printf("<input type='file' name='uploaded_file%d' />",$i);
            ?>
            <input type='submit' />
            <?php
                if( !empty( $files ) ){
                    printf('<pre><h1>Files uploaded & resized</h1>%s</pre>',print_r( $files, true ) );
                }
                if( !empty( $errors ) ){
                    printf('<pre><h1>Errors</h1>%s</pre>',print_r( $errors, true ) );
                }
            ?>
        </form>
    </body>
</html>