2012-02-10 4 views
0

Я пытаюсь изменить размер изображения, которое я загрузил с помощью формы. Я использую сцену сценария здесь: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/Изменение размера изображения с помощью php-скрипта

Я также использую следующий код для загрузки изображения:

upload.php:

<?php 

    session_start(); 
    require_once "database.php"; 
    db_connect(); 
    require_once "auth.php"; 
    $current_user = current_user(); 

    $emailstring = $current_user['email']; 

//Check to see if the type of file uploaded is a valid image type 
function is_valid_type($file) 
{ 
    //This is an array that holds all the valid image MIME types 
    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); 

    if (in_array($file['type'], $valid_types)) 
     return 1; 
    return 0; 

} 

function showContents($array) 
    { 

     echo "<pre>"; 
     print_r($array); 
     echo "</pre>"; 
    } 

//Set some constants 

//This variable is the path to the image folder where all the images are going to be stored 

//Note that there is a trailing forward slash 
$TARGET_PATH = "profile_images/"; 

//Get our POSTed variables 
$upload_picture_fileinput = $_FILES['upload_picture_fileinput']; 


//Sanitize input 
$upload_picture_fileinput['name'] = mysql_real_escape_string($upload_picture_fileinput['name']); 

//Build our target path full string. This is where the file will be moved to 
//i.e. profile_images/picture.jpg 
$TARGET_PATH .= $upload_picture_fileinput['name']; 

if(!is_valid_type($upload_picture_fileinput)) { 

    $_SESSION['error'] = "You must upload a jpeg, gif, bmp, or png"; 
    header("Location: account.php"); 
    exit; 


    } 

//attempt to move the file from its temporary directory to its new home 
if (move_uploaded_file($upload_picture_fileinput['tmp_name'], $TARGET_PATH)) { 

    $sql = "UPDATE `users` SET `profile_image_filename`='" . $upload_picture_fileinput['name'] . "' 
         WHERE email='$emailstring'"; 


    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); 

    header("Location: account.php"); 
    exit; 
} 
else 
{ 


    $_SESSION['error'] = "Could not upload file. Check read/write permissions on the directory"; 
    header("Location: account.php") ; 
    exit; 

    } 

и где моя форма:

<div class="pictures add_pictures"> 
      <div class="add_picture"> 
       <div class="upload_picture"> 
        <form action="upload.php" method="POST" enctype="multipart/form-data" name="upload_picture_form" class="upload_picture_form"> 
         <span class="add_picture_label">+ Add a Profile Picture</span> 
         <input type="file" name="upload_picture_fileinput" class="upload_picture_file_input"/> 
         <input type="hidden" name="MAX_FILE_SIZE" value="100000"/> 
         <br><br><br><br><br><br><br> 

         <input type="submit" id="submit" value="Upload" /> 
        </form> 
       </div> 
      </div> 
     </div> 

     <?php 

      $sql = "select * FROM `users` WHERE `id`='$id'"; 
      $result = mysql_query($sql) or die ("Could not access DB: " . mysql_error()); 



       $row = mysql_fetch_assoc($result); 


       echo "<p>"; 

       echo "<img src=\"profile_images/" . $row['profile_image_filename'] . "\" alt=\"\" /><br />"; 
       echo "</p>"; 



     ?> 
            //not currently working 
       <img src="/imageresize.php"/> 

Эхо выше печатает изображение в порядке, но когда я пытаюсь использовать это имя для изменения размера изображения, оно не появляется/работает.

<?php 
    session_start(); 
    require_once "database.php"; 
    db_connect(); 
    require_once "auth.php"; 
    $current_user = current_user(); 

    $resized_image = '\"profile_images/" . $row['profile_image_filename'] . "\" alt=\"\" /'; 

    header('Content-Type: image/jpg'); 
    include('SimpleImage.php'); 
    $image = new SimpleImage(); 
    $image->load($resized_image); 
    $image->resizeToWidth(300); 
    $image->output(); 


?> 

Я подключаюсь к базе данных отлично, и имя файла изображения сохраняется в моей базе данных. Я просто не знаю, почему путь к файлу выше будет печатать изображение, но не работает в сценарии изменения размера. Пожалуйста, помоги, если можешь. Спасибо.

ответ

1

Похоже, что в $ resized_image вы добавили тег html alt, который, конечно же, не должен быть частью параметра, который вы загружаете в $ image-> load ($ resized_image) ;.

меняется это

$image->load('profile_images/' . $row['profile_image_filename']); 

вместо строки, уже нацеливает HTML-рендеринга Try.

+0

Это все еще не возвращает изображение размером –

+0

нм, я изменился на вещи, и это сработало. Спасибо, Олаф! –

+0

Добро пожаловать. – Olaf

2

В приведенном ниже коде создается функция с именем createThumbs, которая получит три параметра. Первый и второй соответственно - путь к каталогу, который содержит исходные изображения, и путь к каталогу, в котором будут размещены миниатюры. Третий параметр - это ширина, которую вы хотите для уменьшенных изображений.

<?php 
    function createThumbs($pathToImages, $pathToThumbs, $thumbWidth) 
    { 
     // open the directory 
     $dir = opendir($pathToImages); 

     // loop through it, looking for any/all JPG files: 
     while (false !== ($fname = readdir($dir))) { 
     // parse path for the extension 
     $info = pathinfo($pathToImages . $fname); 
     // continue only if this is a JPEG image 
     if (strtolower($info['extension']) == 'jpg') 
     { 
      echo "Creating thumbnail for {$fname} <br />"; 

      // load image and get image size 
      $img = imagecreatefromjpeg("{$pathToImages}{$fname}"); 
      $width = imagesx($img); 
      $height = imagesy($img); 

      // calculate thumbnail size 
      $new_width = $thumbWidth; 
      $new_height = floor($height * ($thumbWidth/$width)); 

      // create a new temporary image 
      $tmp_img = imagecreatetruecolor($new_width, $new_height); 

      // copy and resize old image into new image 
      imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

      // save thumbnail into a file 
      imagejpeg($tmp_img, "{$pathToThumbs}{$fname}"); 
     } 
     } 
     // close the directory 
     closedir($dir); 
    } 
    // call createThumb function and pass to it as parameters the path 
    // to the directory that contains images, the path to the directory 
    // in which thumbnails will be placed and the thumbnail's width. 
    // We are assuming that the path will be a relative path working 
    // both in the filesystem, and through the web for links 
    createThumbs("upload/","upload/thumbs/",100); 
    ?> 
+1

+1 за хороший пост –

Смежные вопросы