dongwang788787 2014-07-29 19:56
浏览 36
已采纳

除了上传多个文件外,调整大小和拇指功能都有效

For some reason my resize & thumbnail function only works with one file.

When I try to upload more files, for example 3, it only processes the first file correctly. It saves it in my directory, resizes it, puts on a watermark and inserts the paths into my database. The second file is only saved and resized, no thumbnail is saved and it's paths aren't inserted into my database.
The third file doesn't get processed at all and the page won't return to it's original (which it should, and display an array of the images that are uploaded).

If I comment out the thumbnail function so that it only runs the watermark/resize function, it only processes the first two files and will only put the first file into the database. Page won't return to it's original state.
If I comment out the watermark/resize function, so that it only runs the thumbnail function, it only processes the first file untill the thumbnail function (so it saves the original but won't resize it to a thumbnail and won't put an entry into the database). Page won't return to it's original state.
If I comment out both the functions, it uploads the 3 files correctly and saves the paths into the database. The page returns to it's original state.

What am I doing wrong?

index.php:

<?php

include "include/resize.php";

$file_dest = "photos/orig/";
$thumb_dest = "photos/thumbs/";

if(!empty($_FILES['files']['name'][0])){

    $files = $_FILES['files'];

    $uploaded = array();
    $bestanden = array();
    $failed = array();

    $allowedExt = array('png', 'jpg', 'gif');

    foreach($files['name'] as $position => $file_name) {
        $file_tmp = $files['tmp_name'][$position];
        $file_size = $files['size'][$position];
        $file_error = $files['error'][$position];

        $file_ext = explode('.', $file_name);
        $file_ext = strtolower(end($file_ext));

        if(in_array($file_ext, $allowedExt)){

            if($file_error == 0){

                if($file_size <= 32000000){

                    $file_name_new = uniqid('', true)."_".$file_name;
                    $file_move = $file_dest.$file_name_new;

                    if(move_uploaded_file($file_tmp, $file_move)){
                        $uploaded[$position]['naam'] = $file_name;
                        $uploaded[$position]['pad'] = $file_move;

                        $path_web = 'photos/web/'.$file_name_new;
                        $path_thumb = 'photos/thumb/'.$file_name_new;
                        watermark_image($file_move, $path_web);
                        create_thumbnail($file_move, $path_thumb, 150, 150);

                        include "include/config.php";
                        $query = "INSERT INTO galerij (name, category, orig, web, thumb, folio) VALUES ('$file_name', '', '$file_move', '', '', '')";
                        $result = mysql_query($query) or die(mysql_error());

                    }else{
                        $failed[$position] = "[{$file_name}] failed to upload.";
                    }

                }else{
                    $failed[$position] = "[{$file_name}] is too large.";
                }

            }else{
                $failed[$position] = "[P$file_name}] errored with code {$file_error}";
            }

        }else{
            $failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
        }
    }

    if(!empty($uploaded)){
        echo "<pre>";
        print_r($uploaded);
        echo "</pre>";

    }

    if(!empty($failed)){
        print_r($failed);
    }

}else{
    echo "No files were added.";
}

?>

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Tutorial</title>

<link rel="stylesheet" type="text/css" href="css/tut.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</head>

<body>

<div id="uploaded">
<?php


?>
</div>

<form action="" method="POST" enctype="multipart/form-data">
    <div>
    <input type="file" name="files[]" multiple id="file"/><p>
    <input type="submit" value="Upload" id="submit" />
    </div>
</form>

<div id="upload_progress"></div>

</body>
</html>

resize.php:

<?php
    function watermark_image($file, $destination){

        $watermark = imagecreatefrompng('images/watermerk.png');

        $width = 800;
        $height = 800;

        $source = getimagesize($file);  

        $source_mime = $source['mime']; 


        if($source_mime == 'image/png'){
            $image = imagecreatefrompng($file);
            }else if($source_mime == 'image/jpeg'){
            $image = imagecreatefromjpeg($file);
            } else if($source_mime == 'image/gif'){
                $image = imagecreatefromgif($file);
            }

        list($file_width, $file_height) = getimagesize($file);

        $file_ratio = $file_width/$file_height;

        if ($width/$height > $file_ratio) {
            $width = $height*$file_ratio;
            } else {
             $height = $width/$file_ratio;
            }

        $new_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $file_width, $file_height);

        $file_x = imagesx($new_image);
        $file_y = imagesy($new_image);

        $logo_x = imagesx($watermark);
        $logo_y = imagesy($watermark);

        $pos_x = 1;
        $pos_y = $file_y - $logo_y + 1;


        imagecopy($new_image, $watermark, $pos_x, $pos_y, 0, 0, $logo_x, $logo_y);
        imagepng($new_image, $destination);

        imagedestroy($new_image);
        imagedestroy($image);
        imagedestroy($watermark);   


/*==============================================================================*/

        function create_thumbnail($path, $save, $width, $height){
            $info = getimagesize($path);
            $size = array($info[0], $info[1]);

            if($info['mime'] == 'image/png'){
                $src = imagecreatefrompng($path);
            }else if($info['mime'] == 'image/jpeg'){
                $src = imagecreatefromjpeg($path);
            }else if($info['mime'] == 'image/gif'){
                $src = imagecreatefromgif($path);
            }else{
                return false;
            }


            $thumb = imagecreatetruecolor($width, $height);

            $src_aspect = $size[0] / $size[1];
            $thumb_aspect = $width / $height;

            if($src_aspect < $thumb_aspect){

                $scale = $width / $size[0];
                $new_size = array($width, $width / $src_aspect);
                $src_pos = array(0, ($size[1] * $scale - $height) / $scale / 2);

            }else if($src_aspect > $thumb_aspect){

                $scale = $height / $size[1];
                $new_size = array($height * $src_aspect, $height);
                $src_pos = array(($size[0] * $scale - $width) / $scale / 2, 0);
            }else{
                $new_size = array($width, $height);
                $src_pos = array(0, 0);
            }

            $new_size[0] = max($new_size[0], 1);
            $new_size[1] = max($new_size[1], 1);

            imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);

            if($save == false){
                return imagepng($thumb);

            }else{
                return imagepng($thumb, $save);
            }
        }
    }


?>

config.php:

<?php 

//database credentials
$username = "root";
$password = "root";
$hostname = "localhost"; 

//connection to the database
mysql_connect($hostname, $username, $password) or die(mysql_error()); 
mysql_select_db('imandra') or die(mysql_error()); 
//echo "Connected to MySQL";
?>

SQL query to get the same database:

-- phpMyAdmin SQL Dump
-- version 4.1.9
-- http://www.phpmyadmin.net
--
-- Machine: localhost:8889
-- Gegenereerd op: 29 jul 2014 om 22:01
-- Serverversie: 5.5.34-log
-- PHP-versie: 5.5.10

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- Databank: `imandra`
--

-- --------------------------------------------------------

--
-- Tabelstructuur voor tabel `galerij`
--

CREATE TABLE `galerij` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `category` varchar(200) NOT NULL,
  `orig` varchar(200) NOT NULL,
  `web` varchar(200) NOT NULL,
  `thumb` varchar(200) NOT NULL,
  `folio` varchar(200) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `name` (`name`,`category`,`orig`,`thumb`,`folio`),
  KEY `web` (`web`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
  • 写回答

1条回答 默认 最新

  • dongtui9168 2014-07-29 21:30
    关注

    The problem is a redeclaration of the function create_thumbnail. This is why it happens:

    function watermark_image($file, $destination){
        /*
            code
        */  
    
        function create_thumbnail($path, $save, $width, $height){
            /*
                code
            */
        }
    }
    

    You declare create_thumbnail inside the watermark_image function. The parent function will be included once in your code due to the include command. If you run the watermark_image the first time it will also declare the function create_thumbnail for the first time and everything is currently fine. But if you run the parent function again, it tries to declare create_thumbnail again and this causes an error.

    To fix this you need to declare the sub function as an independent function outside of watermark_image:

    function watermark_image($file, $destination){
        /*
            code
        */
    }
    
    function create_thumbnail($path, $save, $width, $height){
        /*
            code
        */
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错