Php img to canvas

How to put a PHP gd created image into a canvas over the top of an existing image

I am trying to create a feature on a website that allows a user to upload a pngimage using javascript and then over the top of that place a new pngimage using PHP gd that has transparent circles so that the image underneath will show though. I will then hopefully use the imagecopymerge function to merge them together. It would be great if this could all be done using AJAX, without the use of saving the users picture or the PHP gd image into a database. The user will then need to be able to save the new finished combined image to their account. The main problem I am having is how to get the PHP gd image to be shown onto the canvas that the picture is on or any other canvas. The main page

 

Step 1: Select an image to upload


Step 2: Choose a Size

 $x=50; $y+=100; > imagepng($png_image); imagedestroy($png_image); ?> 

I put my own upload.php (as a text file) in the root of my site rachelgallen.com/upload.txt — i rename images on upload. Take a look, it may be helpful.

Источник

Базовое использование

В PHP очень легко управлять объектом Imagick используя ОО интерфейс. Вот небольшой пример, как сделать миниатюру:

Пример #1 Создание миниатюры в Imagick

header ( ‘Content-type: image/jpeg’ );

$image = new Imagick ( ‘image.jpg’ );

// Если в качестве ширины или высоты передан 0,
// то сохраняется соотношение сторон
$image -> thumbnailImage ( 100 , 0 );

С использованием SPL и других OO функций поддерживаемых в Imagick, можно очень легко изменить размеры всех файлов в директории (полезно для пакетного изменения больших изображений с цифровой камеры для просмотра в Web). Здесь мы используем изменение размера, используя определённые мета-данные:

Пример #2 Создание миниатюр для всех JPG файлов в директории

$images = new Imagick ( glob ( ‘images/*.JPG’ ));

// Передаём 0 в thumbnailImage для сохранения соотношения сторон
$image -> thumbnailImage ( 1024 , 0 );

Этот пример создаёт отражение изображения. Отражение создаётся зеркальным отображением и наложением градиента на нём. Затем оригинальное изображение и его отражение накладываются на холст.

Пример #3 Создание отражения

/* Чтение изображения */
$im = new Imagick ( «test.png» );

/* Миниатюра изображения */
$im -> thumbnailImage ( 200 , null );

/* Создание рамки для изображения */
$im -> borderImage (new ImagickPixel ( «white» ), 5 , 5 );

/* Клонируем изображение и зеркально поворачиваем его */
$reflection = $im -> clone ();
$reflection -> flipImage ();

/* Создаём градиент. Это будет наложением для отражения */
$gradient = new Imagick ();

/* Градиент должен быть достаточно большой для изображения и его рамки */
$gradient -> newPseudoImage ( $reflection -> getImageWidth () + 10 , $reflection -> getImageHeight () + 10 , «gradient:transparent-black» );

/* Наложение градиента на отражение */
$reflection -> compositeImage ( $gradient , imagick :: COMPOSITE_OVER , 0 , 0 );

/* Добавляем прозрачность. Требуется ImageMagick 6.2.9 или выше */
$reflection -> setImageOpacity ( 0.3 );

/* Создаём пустой холст */
$canvas = new Imagick ();

/* Холст должен быть достаточно большой, чтобы вместить оба изображения */
$width = $im -> getImageWidth () + 40 ;
$height = ( $im -> getImageHeight () * 2 ) + 30 ;
$canvas -> newImage ( $width , $height , new ImagickPixel ( «black» ));
$canvas -> setImageFormat ( «png» );

/* Наложение оригинального изображения и отражения на холст */
$canvas -> compositeImage ( $im , imagick :: COMPOSITE_OVER , 20 , 10 );
$canvas -> compositeImage ( $reflection , imagick :: COMPOSITE_OVER , 20 , $im -> getImageHeight () + 10 );

/* Вывод изображения */
header ( «Content-Type: image/png» );
echo $canvas ;
?>

Результатом выполнения данного примера будет что-то подобное:

Пример вывода: Создание отражения изображения

Этот пример иллюстрирует как использовать заливку во время рисования.

Пример #4 Заливка текста градиентом

/* Создание нового объекта imagick */
$im = new Imagick ();

/* Создание нового изображения. Будет использоваться как шаблон заливки */
$im -> newPseudoImage ( 50 , 50 , «gradient:red-black» );

/* Создаём объект imagickdraw */
$draw = new ImagickDraw ();

/* Запускаем новый шаблон с названием «gradient» */
$draw -> pushPattern ( ‘gradient’ , 0 , 0 , 50 , 50 );

/* Смешиваем градиент с шаблоном */
$draw -> composite ( Imagick :: COMPOSITE_OVER , 0 , 0 , 50 , 50 , $im );

/* Закрываем шаблон */
$draw -> popPattern ();

/* Используем шаблон с названием «gradient» для заливки */
$draw -> setFillPatternURL ( ‘#gradient’ );

/* Устанавливаем размер шрифта в 52 */
$draw -> setFontSize ( 52 );

/* Добавляем свой текст */
$draw -> annotation ( 20 , 50 , «Hello World!» );

/* Создаём новый объект холста и белое изображение */
$canvas = new Imagick ();
$canvas -> newImage ( 350 , 70 , «white» );

/* Рисуем ImagickDraw на холсте */
$canvas -> drawImage ( $draw );

/* устанавливаем чёрную рамку шириной 1px вокруг изображения */
$canvas -> borderImage ( ‘black’ , 1 , 1 );

/* Устанавливаем формат PNG */
$canvas -> setImageFormat ( ‘png’ );

/* Вывод изображения */
header ( «Content-Type: image/png» );
echo $canvas ;
?>

Результатом выполнения данного примера будет что-то подобное:

Пример вывода: Заливка текста градиентом

Работа с анимированными GIF-изображениями

Пример #5 Чтение GIF изображения и изменение размера всех фреймов

/* Создание нового объекта imagick и чтение в GIF */
$im = new Imagick ( «example.gif» );

/* Изменение размера всех фреймов */
foreach ( $im as $frame ) /* фреймы 50×50 */
$frame -> thumbnailImage ( 50 , 50 );

/* Устанавливаем виртуальный холст для коррекции размера */
$frame -> setImagePage ( 50 , 50 , 0 , 0 );
>

/* Обратите внимание, writeImages вместо writeImage */
$im -> writeImages ( «example_small.gif» , true );
?>

Работа с примитивом «эллипс» и пользовательскими шрифтами

Пример #6 Create a PHP logo

/* Установка ширины и высоты в пропорции логотипа PHP */
$width = 400 ;
$height = 210 ;

/* Создание объекта Imagick с поддержкой прозрачности */
$img = new Imagick ();
$img -> newImage ( $width , $height , new ImagickPixel ( ‘transparent’ ));

/* Новый объект ImagickDraw для отрисовки эллипса */
$draw = new ImagickDraw ();
/* Установка пурпурного цвета заливки для эллипса */
$draw -> setFillColor ( ‘#777bb4’ );
/* Задание размеров эллипса */
$draw -> ellipse ( $width / 2 , $height / 2 , $width / 2 , $height / 2 , 0 , 360 );
/* Отрисовка эллипса */
$img -> drawImage ( $draw );

/* Сброс цвета заливки с пурпурного на черный для текста (заметьте, что мы используем объект ImagickDraw повторно) */
$draw -> setFillColor ( ‘black’ );
/* Задание обводки границы белым цветом */
$draw -> setStrokeColor ( ‘white’ );
/* Задание толщины обводки */
$draw -> setStrokeWidth ( 2 );
/* Задание кернинга (отрицательные значения означают, что буквы будут ближе друг к другу) */
$draw -> setTextKerning (- 8 );
/* Задание шрифта и его размера, которые используются в логотипе PHP */
$draw -> setFont ( ‘Handel Gothic.ttf’ );
$draw -> setFontSize ( 150 );
/* Центрирование текста вертикально и горизонтально */
$draw -> setGravity ( Imagick :: GRAVITY_CENTER );

/* Добавление текста «php» со смещением по Y на -10 на холст (внутри эллипса) */
$img -> annotateImage ( $draw , 0 , — 10 , 0 , ‘php’ );
$img -> setImageFormat ( ‘png’ );

/* Установка соответвующего заголовка для PNG и вывод изображения */
header ( ‘Content-Type: image/png’ );
echo $img ;
?>

Результатом выполнения данного примера будет что-то подобное:

Источник

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

josefburger/PhpCanvas

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

Canvas — PHP Graphic Library

The library is intended to simplify the work with graphical library (GD). For a better understanding here is an example for generating thumbnails:

$canvas = Canvas::createFromImage('/gallery/photos/pic-01.jpg'); $canvas->resize(150, null); $canvas->generateJpeg('/gallery/thumbnails/pic-01.jpg');

There are two ways for creating new canvas:

    creating new image — create new blank canvas of given dimensions.

$canvas = Canvas::create(500, 300);
$canvas = Canvas::createFromImage('/gallery/photos/pic-01.jpg');

Canvas library can work with JPEG and PNG files (other will be added in future). Library can output the image to the browser or save them to file. The last option is to use BASE64 output.

    browser output — easy way to generate temporary images.

header('Content-type: image/png'); // you must send header to inform browser that the source is an image $canvas->generatePng();
$canvas->generatePng('new-image.png');
$image = $canvas->generatePngBase64(); echo '$image . '" alt="Image" />';

The library contains functions for drawing on the canvas. The functions are:

    drow a line — drow a line form the first point to the second point

$canvas->line($startX, $startY, $endX, $endY);
$canvas->rectangle($leftUpperX, $leftUpperY, $rightBottomX, $rightBottomY);
$canvas->polygon(Array( $pointAx, $pointAy, $pointBx, $pointBy, $pointCx, $pointCy, . ));
$canvas->ellipse($centerX, $centerY, $width, $height);
$canvas->arc($centerX, $centerY, $width, $height, $start, $end)

All drawing methods (except the classic line) can be used in variant, where is the shape filled with the color.

$canvas->filledRectangle(. ); $canvas->filledPolygon(. ); $canvas->filledEllipse(. ); $canvas->filledArc(. $style);

Flip, rotate, resize functions

$canvas->resize($newWidth, $newHeight); $canvas->resizeByPercent(50); // resize to 50%
$canvas->resize(250, null); // width will be 250px and the height will be calculated
$canvas->addCanvas($newCanvas, $x, $y, $opacity); // left upper corner of new canvas will be on x, y coordinates on the parent canvas

About

Источник

Читайте также:  Create dto in java
Оцените статью