2016-06-22 8 views
0

Я читал, что с помощью библиотеки gd я могу изменить размер изображения, но я не могу найти правильный способ сделать это. То, что я пытаюсь найти, - это функция, которая изменяет размер - загружает изображение (в/выгружает/изменяет размер) и возвращает путь к размеру изображения, чтобы сохранить его в базе данных для последующего использования. Я попытался использовать некоторые функции, которые я нашел, но я делаю что-то неправильно. У меня установлен wamp64 в моих окнах 7, а в моем phpinfo() похоже, что gd включен. Это doesn; t должен быть gd, я могу использовать любую функцию, которая изменяет размер изображения. Любой намек будет полезен.изменение размера изображения с помощью GD

GD Support enabled 
GD Version bundled (2.1.0 compatible) 
FreeType Support enabled 
FreeType Linkage with freetype 
FreeType Version 2.5.5 
GIF Read Support enabled 
GIF Create Support enabled 
JPEG Support enabled 
libJPEG Version 9 compatible 
PNG Support enabled 
libPNG Version 1.5.18 
WBMP Support enabled 
XPM Support enabled 
libXpm Version 30411 
XBM Support enabled 
WebP Support enabled 

Это является файл PHP я использую, чтобы загрузить мои изображения и хранить информацию о них в базе данных:

<?php 
// just in case, let's turn on the errors 
include_once("config.php"); 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

if ($_SERVER['REQUEST_METHOD'] === 'POST') { 
    $file = isset($_FILES['fileToUpload']['tmp_name']) ? $_FILES['fileToUpload'] : null; 
    // start validation 
    try { 
     // check if file was NOT provided 
     if (!$file || 
      !file_exists($file['tmp_name']) || 
      !is_uploaded_file($file['tmp_name']) || 
      $file['error'] !== UPLOAD_ERR_OK) { 
      throw new Exception('No file was given.'); 
     } 
     // check if file is NOT an image 
     $size = getimagesize($file['tmp_name']); 
     if ($size === false) { 
      throw new Exception('File is not an image.'); 
     } 
     // check if file already exists 
     $target_dir = 'uploads/'; 
     $target_file = $target_dir . basename($file['name']); 
     if (file_exists($target_file)) { 
      throw new Exception('File already exists.'); 
     } 
     // check file size is too large 
     if ($file['size'] > 2000000) { 
      throw new Exception('File is too large.'); 
     } 
     // check file extension is NOT accepted 
     $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); 
     if (!in_array($extension, ['jpg', 'png', 'gif'])) { 
      throw new Exception('Only JPEG, PNG & GIF files are allowed.'); 
     } 
     // if it passes all checks, try uploading file 
     //changing the files name 
     $temp = explode(".", $_FILES["fileToUpload"]["name"]); // edw 
     $newfilename = round(microtime(true)) . '.' . end($temp); // edw 
     $target_file_renamed = $target_dir . $newfilename; //edw 
     if (!move_uploaded_file($file['tmp_name'], $target_file_renamed)) { 
      throw new Exception('There was an error uploading your file.'); 
     } 
     // if we reach this point, then everything worked out! 
     //echo 'The file ' . basename($file['name']) . ' has been uploaded.'; 


     //code to resize and save image to uploads/resized and get the path 

     //code to insert into database with pdo 
     session_start(); 
     try{ 
     $con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD); 
     $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

     //Code to get photo_category_id 
     $sth = $con->prepare('SELECT photo_category_id FROM photo_categories WHERE photo_category = :parameter'); 
     $sth->bindParam(':parameter', $_POST['category'], PDO::PARAM_STR); 
     $sth->execute(); 
     $idis = $sth->fetchColumn(); //echo $idis will return the photo_category_id 

     //Code to update the photos table 
     $likes = 0; 
     $sql = "INSERT INTO photos(photo_name, photo_text, photo_path, photo_lat, photo_lng, photo_likes, username, photo_category_id) 
     VALUES(:name, :text, :path, :lat, :lng, :likes, :username, :category)"; 
     $stmt = $con->prepare($sql); 
     $stmt->bindValue("name", basename($file['name']), PDO::PARAM_STR); 
     $stmt->bindValue("text", $_POST['description'], PDO::PARAM_STR); 
     $stmt->bindValue("path", $target_file_renamed, PDO::PARAM_STR); 
     $stmt->bindValue("lat", $_POST['lat'], PDO::PARAM_INT); 
     $stmt->bindValue("lng", $_POST['lng'], PDO::PARAM_INT); 
     $stmt->bindValue("likes", $likes, PDO::PARAM_INT); 
     $stmt->bindValue("username", $_SESSION["user"]->username, PDO::PARAM_STR); 
     $stmt->bindValue("category", $idis, PDO::PARAM_INT); 
     $stmt->execute(); 



     echo 'The file has been uploaded!'; 
     //echo 'The file ' . basename($file['name']) . ' has been uber fully uploaded.'; 
     }catch (PDOException $e) { 
     echo $e->getMessage(); 
     } 
    } catch (Exception $e) { 
     echo $e->getMessage(); //by doing echo here we get the message in javascript alert(data);... 
    } 
} 
?> 
+1

Смотрите, если это помогает: http://stackoverflow.com/questions/28002244/crop-resize-image-function-using-gd-library – Rasclatt

+0

Это решило мою проблему. спасибо большое :) –

+0

Нет проблем. Не стесняйтесь повышать этот ответ, если он работает;) – Rasclatt

ответ

0

Я не могу увидеть любой код, используя для reszing изображения в этом коде, Вот простой способ изменения размера изображения, пожалуйста, сохраните путь изображения в db для будущего использования.

<?php 

/* 
* PHP GD 
* resize an image using GD library 
*/ 

// File and new size 
//the original image has 800x600 
$filename = 'images/picture.jpg'; 
//the resize will be a percent of the original size 
$percent = 0.5; 

// Content type 
header('Content-Type: image/jpeg'); 

// Get new sizes 
list($width, $height) = getimagesize($filename); 
$newwidth = $width * $percent; 
$newheight = $height * $percent; 

// Load 
$thumb = imagecreatetruecolor($newwidth, $newheight); 
$source = imagecreatefromjpeg($filename); 

// Resize 
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 

// Output and free memory 
//the resized image will be 400x300 
imagejpeg($thumb); 
imagedestroy($thumb);`enter code here` 
?>