Итак, я был в этой миссии, чтобы создать умеренно гибкий, но, что самое важное, перезаписываемый скрипт PHP-скрипта для проектов по загрузке изображений. Когда я путешествовал, я столкнулся с вопросом ограничения памяти PHP, который я разместил в stackoverflow (можно найти здесь: PHP Memory Limit), и потрясающие и полезные ответы, которые я получил, заставили меня понять, что я в основном отвлекаюсь на оптимизацию своих PHP-скриптов. Я подумал, что я бы опубликовал то, что у меня сейчас есть, как мой обработчик 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.";
}
Спасибо всем ... Любая помощь/мысли/дебаты/обратная связь будет очень ценна.
Так что на самом деле вопрос ... «Можете ли вы, люди, пара-программа?» – ZJR
Рассмотрите ответы в этом вопросе: http://stackoverflow.com/questions/12661/efficient-jpeg-image-resizing -в-PHP/4613341 # 4613341 –