Редактирование изображений на php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

Intervention/image

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Intervention Image is a PHP image handling and manipulation library providing an easier and expressive way to create, edit, and compose images. The package includes ServiceProviders and Facades for easy Laravel integration.

Build Status

Supported Image Libraries

// open an image file $img = Image::make('public/foo.jpg'); // resize image instance $img->resize(320, 240); // insert a watermark $img->insert('public/watermark.png'); // save image in desired format $img->save('public/bar.jpg');

Refer to the official documentation to learn more about Intervention Image.

Contributions to the Intervention Image library are welcome. Please note the following guidelines before submitting your pull request.

  • Follow PSR-2 coding standards.
  • Write tests for new functions and added features
  • API calls should work consistently with both GD and Imagick drivers
Читайте также:  Возможности форм в html

Intervention Image is licensed under the MIT License.

Источник

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

Библиотека GD дает возможность работать с изображениями в PHP. Подробнее о функциях на php.net.

Далее представлены примеры как изменить размер, вырезать часть изображения и т.д. Все примеры универсальные и работают с разными типами файлов без изменений кода, у PNG файлов сохраняется прозрачность.

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

Итак, есть исходное изображение PNG 400x400px:

С помощью функции getimagesize() получим ширину, высоту и тип, далее откроем его функциями в зависимости от типа:

$filename = __DIR__ . '/donut.png'; $info = getimagesize($filename); $width = $info[0]; $height = $info[1]; $type = $info[2]; switch ($type)

Изменение размера изображения (resize)

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

// Размеры новой фотки. $w = 200; $h = 0; if (empty($w)) < $w = ceil($h / ($height / $width)); >if (empty($h)) < $h = ceil($w / ($width / $height)); >$tmp = imageCreateTrueColor($w, $h); if ($type == 1 || $type == 3) < imagealphablending($tmp, true); imageSaveAlpha($tmp, true); $transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127); imagefill($tmp, 0, 0, $transparent); imagecolortransparent($tmp, $transparent); >$tw = ceil($h / ($height / $width)); $th = ceil($w / ($width / $height)); if ($tw < $w) < imageCopyResampled($tmp, $img, ceil(($w - $tw) / 2), 0, 0, 0, $tw, $h, $width, $height); >else < imageCopyResampled($tmp, $img, 0, ceil(($h - $th) / 2), 0, 0, $w, $th, $width, $height); >$img = $tmp;

Результат

$w = 200;
$h = 0;
$w = 200;
$h = 100;
$w = 100;
$h = 200;

Обрезать изображение (crop)

Пример вырезает из исходного изображения часть размером $w на $h .
$x и $y задают начальные координаты в пикселях или процентах.

$w = 200; $h = 200; $x = '100%'; $y = '100%'; if (strpos($x, '%') !== false) < $x = intval($x); $x = ceil(($width * $x / 100) - ($w / 100 * $x)); >if (strpos($y, '%') !== false) < $y = intval($y); $y = ceil(($height * $y / 100) - ($h / 100 * $y)); >$tmp = imageCreateTrueColor($w, $h); if ($type == 1 || $type == 3) < imagealphablending($tmp, true); imageSaveAlpha($tmp, true); $transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127); imagefill($tmp, 0, 0, $transparent); imagecolortransparent($tmp, $transparent); >imageCopyResampled($tmp, $img, 0, 0, $x, $y, $width, $height, $width, $height); $img = $tmp;

Результат

$x = 0;
$y = 0;
$x = ‘50%’;
$y = ‘0%’;
$x = ‘100%’;
$y = ‘0%’;

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

Функция imagerotate() поворачивает изображение на заданный угол против часовой стрелки, отрицательный угол меняет направление поворота.

// Поворот против часовой стрелки на 45°. $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127); $img = imagerotate($img, 45, $transparent); // Поворот по часовой стрелки на 90° $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127); $img = imagerotate($img, -90, $transparent);

Поворот на не ровный угол увеличит ширину и высоту фото:

Зеркальное отражение

imageflip($img, IMG_FLIP_HORIZONTAL);

Imageflip() зеркалит изображение, могут быть следующие параметры:

IMG_FLIP_HORIZONTAL По горизонтали
IMG_FLIP_VERTICAL По вертикали
IMG_FLIP_BOTH По горизонтали и вертикали

Добавление фона

Актуально для PNG с прозрачностью. Скрипт вставит на задний фон картинку с положением $x и $y . Размер основного изображения не изменится.

$file = __DIR__ . '/donut_bg.jpg'; // Положение фона. $x = '50%'; $y = '50%'; $info = getimagesize($file); switch ($info[2]) < case 1: $bg = imageCreateFromGif($file); break; case 2: $bg = imageCreateFromJpeg($file); break; case 3: $bg = imageCreateFromPng($file); break; >if (strpos($x, '%') !== false) < $x = intval($x); $x = ceil(($info[0] * $x / 100) - ($width / 100 * $x)); >if (strpos($y, '%') !== false) < $y = intval($y); $y = ceil(($info[1] * $y / 100) - ($height / 100 * $y)); >$tmp = imageCreateTrueColor($width, $height); imagecopy($tmp, $bg, 0, 0, $x, $y, $width, $height); imagedestroy($bg); imagecopy($tmp, $img, 0, 0, 0, 0, $width, $height); $img = $tmp;

Фильтры

imagefilter($img, $filtertype, $arg1, $arg2);

Функция imagefilter() применяет фильтр к изображению.
В параметре $filtertype указывается константа применяемого фильтра, а в следующих его настройки.

Читайте также:  Deep learning with python tensorflow

IMG_FILTER_NEGATE

Инвертирует цвета изображения.

imagefilter($img, IMG_FILTER_NEGATE);

IMG_FILTER_GRAYSCALE

Преобразует цвета изображения в градации серого.

imagefilter($img, IMG_FILTER_GRAYSCALE);

IMG_FILTER_COLORIZE

Преобразует цвета изображения в градации заданного цвета в формате RGB.

// Красный imagefilter($img, IMG_FILTER_COLORIZE, 0, 240, 120); // Синий imagefilter($img, IMG_FILTER_COLORIZE, 150, 240, 120); // Зеленый imagefilter($img, IMG_FILTER_COLORIZE, 90, 240, 90);
0, 240, 120
150, 240, 120
90, 240, 90

IMG_FILTER_BRIGHTNESS

Изменяет яркость изображения, диапазон от -255 до 255.

imagefilter($img, IMG_FILTER_BRIGHTNESS, 127);
-200
-100
100
200

IMG_FILTER_CONTRAST

Изменяет контрастность изображения. Уровень может быть от -100 до 100.

imagefilter($img, IMG_FILTER_CONTRAST, 100);
-100
-50
50
100

IMG_FILTER_EDGEDETECT

Использует определение границ для их подсветки.

imagefilter($img, IMG_FILTER_EDGEDETECT);

IMG_FILTER_EMBOSS

imagefilter($img, IMG_FILTER_EMBOSS);

IMG_FILTER_GAUSSIAN_BLUR

Размывает изображение по методу Гаусса.

imagefilter($img, IMG_FILTER_GAUSSIAN_BLUR);

IMG_FILTER_SELECTIVE_BLUR

Как и IMG_FILTER_GAUSSIAN_BLUR размывает изображение.

imagefilter($img, IMG_FILTER_SELECTIVE_BLUR);

IMG_FILTER_MEAN_REMOVAL

imagefilter($img, IMG_FILTER_MEAN_REMOVAL);

IMG_FILTER_SMOOTH

Делает границы более плавными, а изображение менее четким. Диапазон значений не ограничен, но наиболее заметные изменения происходят от 0 до -8.

imagefilter($img, IMG_FILTER_SMOOTH, -2);
0
-2
-4
-6

IMG_FILTER_PIXELATE

Применяет эффект пикселирования.

arg1 – задает размера блока в пикселях.
arg2 – включает усовершенствованный эффект пикселирования.

imagefilter($img, IMG_FILTER_PIXELATE, 2, true);
2
3
4
5

Сохранение

Вывод изображения в браузер

До вызова функции header() скрипт ничего не должен выводить ( echo , ?>.

switch ($type) < case 1: header('Content-Type: image/gif'); imageGif($img); break; case 2: header('Content-Type: image/jpeg'); imageJpeg($img, null, 100); break; case 3: header('Content-Type: image/x-png'); imagePng($img); break; >imagedestroy($img); exit();

Чтобы браузер отдал фото на скачивание, в начало кода нужно добавить заголовок:

header('Content-Disposition: Attachment;filename=' . basename($src)); 

Сохранение изображения в файл на сервере

switch ($type) < case 1: imageGif($img, $src); break; case 2: imageJpeg($img, $src, 100); break; case 3: imagePng($img, $src); break; >imagedestroy($img);

Вывод в браузер и сохранение в файл

switch ($type) < case 1: header('Content-Type: image/gif'); imageGif($img, $src); break; case 2: header('Content-Type: image/jpeg'); imageJpeg($img, $src, 100); break; case 3: header('Content-Type: image/x-png'); imagePng($img, $src); break; >imagedestroy($img); readfile($src); exit();

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Читайте также:  Learn to use python

PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

License

DantSu/php-image-editor

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

⭐ Star this repository to support this project. You will contribute to increase the visibility of this library 🙂

Install this library easily with composer :

composer require dantsu/php-image-editor

Create a empty image, draw on it and display it :

use \DantSu\PHPImageEditor\Image; \header('Content-type: image/png'); $image = Image::newCanvas(500, 500) ->drawRectangle(0, 0, 500, 500, '#444') ->drawRectangle(0, 350, 500, 500, '#FF8800') ->writeText('I got the power !', __DIR__ . '/resources/font.ttf', 40, '#FFFFFF', Image::ALIGN_CENTER, 310) ->drawCircle(25, 100, 100, '#FF8800') ->drawCircle(25, 100, 95, '#000000FF') ->drawCircle(475, 100, 100, '#FF8800') ->drawCircle(475, 100, 95, '#000000FF'); for($i = 0; $i 360; $i+=30) < $image ->drawArrowWithAngle(250, 200, $i, 80, 2, '#FF8800') ->drawArrowWithAngle(250, 200, ($i + 15), 50, 2, '#FF8800'); > $image ->crop(450, 300, Image::ALIGN_CENTER, Image::ALIGN_MIDDLE) ->displayPNG();

Sample 1

Apply a watermark on a photo and save it :

use \DantSu\PHPImageEditor\Image; Image::fromPath(__DIR__ . '/resources/photo.jpg') ->downscaleAndCrop(1920, 1080, Image::ALIGN_CENTER, Image::ALIGN_BOTTOM) ->pasteOn( Image::fromPath(__DIR__ . '/resources/watermark.png')->downscaleProportion(300, 300), Image::ALIGN_RIGHT, Image::ALIGN_TOP ) ->saveJPG(__DIR__ . '/my-image.jpg', 70);

Sample 2

See DantSu\PHPImageEditor\Image documentation class for more details.

Please fork this repository and contribute back using pull requests.

Any contributions, large or small, major features, bug fixes, are welcomed and appreciated but will be thoroughly reviewed.

About

PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

Источник

Оцените статью