Обработка изображений в PHP

Активный
Статус
Сообщения
516
Лайки
32

8

месяц на сайте

Руководство по работе с изображениями в PHP с использованием библиотеки GD.

Создание изображения

Код:
<?php
// Создание пустого изображения
$width = 400;
$height = 300;
$image = imagecreate($width, $height);

// Установка цветов
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$red = imagecolorallocate($image, 255, 0, 0);

// Рисование
imageline($image, 0, 0, $width, $height, $black);
imagerectangle($image, 50, 50, 150, 150, $red);

// Вывод
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>

Загрузка и изменение размера

Код:
<?php
function resizeImage($source, $destination, $newWidth, $newHeight) {
    $info = getimagesize($source);
    $mime = $info['mime'];
    
    switch ($mime) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $image = imagecreatefrompng($source);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($source);
            break;
        default:
            return false;
    }
    
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $info[0], $info[1]);
    
    switch ($mime) {
        case 'image/jpeg':
            imagejpeg($newImage, $destination, 90);
            break;
        case 'image/png':
            imagepng($newImage, $destination);
            break;
        case 'image/gif':
            imagegif($newImage, $destination);
            break;
    }
    
    imagedestroy($image);
    imagedestroy($newImage);
    return true;
}

resizeImage('source.jpg', 'resized.jpg', 800, 600);
?>

Обрезка изображения

Код:
<?php
function cropImage($source, $destination, $x, $y, $width, $height) {
    $image = imagecreatefromjpeg($source);
    $cropped = imagecrop($image, ['x' => $x, 'y' => $y, 'width' => $width, 'height' => $height]);
    
    if ($cropped !== false) {
        imagejpeg($cropped, $destination, 90);
        imagedestroy($cropped);
    }
    
    imagedestroy($image);
    return $cropped !== false;
}

cropImage('source.jpg', 'cropped.jpg', 100, 100, 200, 200);
?>

Добавление водяного знака

Код:
<?php
function addWatermark($source, $destination, $watermarkText) {
    $image = imagecreatefromjpeg($source);
    $width = imagesx($image);
    $height = imagesy($image);
    
    // Цвет для текста
    $textColor = imagecolorallocate($image, 255, 255, 255);
    $shadowColor = imagecolorallocate($image, 0, 0, 0);
    
    // Позиция (правый нижний угол)
    $fontSize = 5;
    $textWidth = imagefontwidth($fontSize) * strlen($watermarkText);
    $textHeight = imagefontheight($fontSize);
    $x = $width - $textWidth - 10;
    $y = $height - $textHeight - 10;
    
    // Тень
    imagestring($image, $fontSize, $x + 1, $y + 1, $watermarkText, $shadowColor);
    // Текст
    imagestring($image, $fontSize, $x, $y, $watermarkText, $textColor);
    
    imagejpeg($image, $destination, 90);
    imagedestroy($image);
    return true;
}

addWatermark('source.jpg', 'watermarked.jpg', 'Copyright 2024');
?>

Создание миниатюр

Код:
<?php
function createThumbnail($source, $destination, $maxSize = 200) {
    $info = getimagesize($source);
    $width = $info[0];
    $height = $info[1];
    
    // Вычисление нового размера с сохранением пропорций
    if ($width > $height) {
        $newWidth = $maxSize;
        $newHeight = ($height / $width) * $maxSize;
    } else {
        $newHeight = $maxSize;
        $newWidth = ($width / $height) * $maxSize;
    }
    
    $mime = $info['mime'];
    switch ($mime) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $image = imagecreatefrompng($source);
            break;
        default:
            return false;
    }
    
    $thumbnail = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
    imagejpeg($thumbnail, $destination, 85);
    imagedestroy($image);
    imagedestroy($thumbnail);
    return true;
}

createThumbnail('large.jpg', 'thumb.jpg', 200);
?>

Применение фильтров

Код:
<?php
function applyFilter($source, $destination, $filter) {
    $image = imagecreatefromjpeg($source);
    
    switch ($filter) {
        case 'grayscale':
            imagefilter($image, IMG_FILTER_GRAYSCALE);
            break;
        case 'negate':
            imagefilter($image, IMG_FILTER_NEGATE);
            break;
        case 'brightness':
            imagefilter($image, IMG_FILTER_BRIGHTNESS, 20);
            break;
        case 'contrast':
            imagefilter($image, IMG_FILTER_CONTRAST, -20);
            break;
        case 'blur':
            imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR);
            break;
        case 'emboss':
            imagefilter($image, IMG_FILTER_EMBOSS);
            break;
    }
    
    imagejpeg($image, $destination, 90);
    imagedestroy($image);
    return true;
}

applyFilter('source.jpg', 'filtered.jpg', 'grayscale');
?>

Создание капчи

Код:
<?php
session_start();

function generateCaptcha() {
    $width = 200;
    $height = 50;
    $image = imagecreate($width, $height);
    
    // Цвета
    $bg = imagecolorallocate($image, 240, 240, 240);
    $textColor = imagecolorallocate($image, 0, 0, 0);
    $lineColor = imagecolorallocate($image, 200, 200, 200);
    
    // Генерация кода
    $code = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 6);
    $_SESSION['captcha'] = $code;
    
    // Линии
    for ($i = 0; $i < 5; $i++) {
        imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
    }
    
    // Текст
    imagestring($image, 5, 50, 15, $code, $textColor);
    
    header('Content-Type: image/png');
    imagepng($image);
    imagedestroy($image);
}

generateCaptcha();
?>

Объединение изображений

Код:
<?php
function mergeImages($image1, $image2, $destination, $x, $y) {
    $img1 = imagecreatefromjpeg($image1);
    $img2 = imagecreatefromjpeg($image2);
    
    $width1 = imagesx($img1);
    $height1 = imagesy($img1);
    $width2 = imagesx($img2);
    $height2 = imagesy($img2);
    
    // Создание нового изображения
    $merged = imagecreatetruecolor($width1, $height1);
    imagecopy($merged, $img1, 0, 0, 0, 0, $width1, $height1);
    imagecopy($merged, $img2, $x, $y, 0, 0, $width2, $height2);
    
    imagejpeg($merged, $destination, 90);
    imagedestroy($img1);
    imagedestroy($img2);
    imagedestroy($merged);
    return true;
}

mergeImages('background.jpg', 'logo.png', 'merged.jpg', 100, 100);
?>

Поворот изображения

Код:
<?php
function rotateImage($source, $destination, $angle) {
    $image = imagecreatefromjpeg($source);
    $rotated = imagerotate($image, $angle, 0);
    
    imagejpeg($rotated, $destination, 90);
    imagedestroy($image);
    imagedestroy($rotated);
    return true;
}

rotateImage('source.jpg', 'rotated.jpg', 45);
?>

Извлечение информации об изображении

Код:
<?php
function getImageInfo($filename) {
    $info = getimagesize($filename);
    
    return [
        'width' => $info[0],
        'height' => $info[1],
        'mime' => $info['mime'],
        'bits' => $info['bits'],
        'channels' => $info['channels'] ?? null
    ];
}

$info = getImageInfo('image.jpg');
echo "Ширина: " . $info['width'] . "\n";
echo "Высота: " . $info['height'] . "\n";
echo "Тип: " . $info['mime'] . "\n";
?>

Обработка изображений - важная часть веб-разработки. Библиотека GD предоставляет все необходимые инструменты для работы с графикой.
 

1 человек читают эту тему (Всего: 1, Пользователей: 0, Гостей: 1)

Сверху