Итак, я поставил себе задачу создать умеренно гибкий, но, что самое важное, многократно используемый PHP-скрипт обработчика для проектов загрузки изображений.Пока я путешествовал, я столкнулся с вопросом об ограничении памяти PHP, который я разместил в stackoverflow (можно найти здесь: Ограничение памяти PHP ), и удивительные и полезные ответы, которые я получил, заставили меня осознать, что я в основном отстой в оптимизациимои PHP скрипты.Я подумал, что опубликую то, что у меня есть, в качестве моего «многоразового» обработчика PHP-форм для загрузки сценариев и приветствую любые отзывы, которые могут понадобиться умным разработчикам для повышения производительности или повсеместного улучшения.
Чтобы суммировать, что должен делать этот обработчик:1) Разрешить загрузку изображений2) Сохраните полноразмерную версию изображения с измененным размером до желаемой ширины.3) Сохраните уменьшенную версию изображения, размер которого изменяется до желаемой ширины.4) Поместите водяной знак на оба изображения.
Я использую два сценария с открытым исходным кодом, чтобы помочь с изменением размера и нанесением водяных знаков.Насколько эффективно я их использую, я не уверен, но они работают и довольно удобны для пользователя.
Simple Image PHP Script:
http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
Zubrak's Thumbnail Script:
http://www.zubrag.com/scripts/watermark-image.php
Вот мой обработчик:
<?php
// If a file is being uploaded, do somethin' about it!:
if (!empty($_FILES)) {
// CONFIGURE:
// How many pixels wide should the full size image be?
$fullSizeWidth = 800;
// How many pixels wide should the thumbnail image be?
$thumbnailWidth = 100;
// What is the path to the image upload directory?
$pathToImageDirectory = "path/to/image/directory/";
// Create an array of allowable extension types:
$validExtensions = array('jpg', 'jpeg', 'png');
// What will the thumbnail version's suffix be?
$thumbnailSuffix = "_thumbnail";
// What is the path to your watermark image file?
$pathToWatermark = "path/to/watermark/watermark.png";
// INCLUDE NEEDED FILES
// Require the simpleImage class for basic image modifications
require_once('simpleImage.php');
// Require the Zubrag_watermark class for adding your watermark to images
require_once('Zubrag_watermark.php');
// GET THE USER DATA FROM THE FORM (for demo we'll just say they're submitting an image file only):
// Get the file's temporary name:
$tempFile = $_FILES['file']['tmp_name'];
// Get the file's original name:
$userFileName = $_FILES['file']['name'];
// Get the file's extension:
$extension = strtolower(end(explode(".", $userFileName)));
// UPLOAD DESITNATION:
// Re-name the image something cool (We'll just hash it for now):
$theImageName = sha1($userFileName);
// Create the full sized image destination by combining it all
$imageDestination = $pathToImageDirectory . $theImageName . "." . $extension;
// Create the thumbnail sized image destination by combining it all
$thumbnailDestination = $pathToImageDirectory . $theImageName . $thumbnailSuffix . "." . $extension;
// VALIDATE THE IMAGE:
// Check to see if the uploaded file has an acceptable extension
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
// If the extension is valid and the image is valid, accept the file, resize it, and watermark it:
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile,$imageDestination)) {
// RESIZE THE IMAGES
// Create simpleImage object
$image = new SimpleImage();
// Load the uploaded file to memory
$image->load($imageDestination);
// Resize the image to desired full size width
$image->resizeToWidth($fullSizeWidth);
// Save the image's full sized version
$image->save($imageDestination);
// Resize the image to the desired thumbnail width
$image->resizeToWidth($thumbnailWidth);
// Save the image's thumbnail sized version
$image->save($thumbnailDestination);
// Free the image from memory (note: I added this function to the simpleImage class -- it's simply: imagedestroy($this->image);)
$image->Free();
// WATERMARK THE IMAGES
// Load the full size image into memory
$watermark = new Zubrag_watermark($imageDestination);
// Apply the watermark
$watermark->ApplyWatermark($pathToWatermark);
// Save the watermarked full-sized file
$watermark->SaveAsFile($imageDestination);
// Free the full sized image from memory
$watermark->Free();
// Load the thumbnail sized image into memory
$watermark = new Zubrag_watermark($thumbnailDestination);
// Apply the watermark
$watermark->ApplyWatermark($pathToWatermark);
// Save the thumbnail-sized File
$watermark->SaveAsFile($thumbnailDestination);
// Free the image from memory
$watermark->Free();
}
} else {
// Error handling for an image that did not pass validation
echo "So we're basically thinking you tried to upload something that wasn't an image.";
}
} else {
// Error handling for running this script without a file being uploaded
echo "You should probably upload a file next time.";
}
Спасибо всем ...Любая помощь / мысли / дебаты / отзывы будут очень признательны.