Php img src jpg

Get Image Src With PHP

There are some occasions where you need to get the attribute value in PHP from a HTML element, this can be for migration reasons or perhaps you are writing a script to scrap a website to store the values found. I was writing a script that needed to scrape a web page and pick up all the URLs for the images on the page and store the src values. You are able to load the HTML contents of the page by using the file_get_contents() on a URL. Once you get the HTML for an image tag, you then need to take this HTML and pull out the value of the contents inside the src attribute. In this article we are going to use two methods on how you can do this in PHP. The first is going to use the DOMDocument object and then XPath to pull out the values of the src attribute. The second is by using a regular expression to get the contents inside the src=»» attribute.

Читайте также:  Change string array to string java

HTML DOM Document

In PHP there is a library of DOMDocument, this object allows you to provide it with a whole HTML or XML document and then use the built in method to parse this in any way you want, you can use it to get certain tags, you can create new elements or read contents of a tag. In this example we are going to have the HTML image tag.

  

Now we are going to use the DOMDocument object with XPath to get the value of the src attribute.

 $html = ' '; $doc = new DOMDocument(); $doc->loadHTML($html); $xpath = new DOMXPath($doc); $src = $xpath->evaluate("string(//img/@src)"); // will return /images/image.jpg echo $src;

The above example shows how we instantiate the DOMDocument object, then use the loadHTML() method and pass in the HTML for the image tag. We can then pass this document into a DOMXPath object so that we can not use the XPath of string(//img/@src) to get the value of the src attribute.

Preg Match

The other option you can use in this situation is to use a regular expression to search the string of the image tag for the src attribute and return the value inside the attribute tag. To get the src of the image tag we are going to use the regular expression of @src=»https://paulund.co.uk/([%5E»]+)»@.

 $html = ' '; preg_match( '@src="https://paulund.co.uk/([%5E"]+)"@' , $html, $match ); $src = array_pop($match); // will return /images/image.jpg echo $src;

Источник

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

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

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

Читайте также:  Html form add links

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

Итак, есть исходное изображение 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 указывается константа применяемого фильтра, а в следующих его настройки.

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();

Источник

Display Image From File In PHP (Simple Examples)

Welcome to a tutorial on how to display an image from a file in PHP. So you have a secured folder of images that is not publicly accessible, but still want registered users to be able to view? Yes, it is possible to do so.

To display an image from a file in PHP, simply output the necessary HTTP headers and read the image file:

  • header(«Content-Type: image/jpeg»);
  • header(«Content-Length: » . filesize («IMAGE.JPG»));
  • readfile(«IMAGE.JPG»);

That should cover the basics, but read on for a few more examples!

TLDR – QUICK SLIDES

How To Read & Display Image In PHP

TABLE OF CONTENTS

PHP DISPLAY IMAGE

All right, let us now get into the examples of displaying an image file in PHP.

EXAMPLE 1) READ FILE AND OUTPUT

  • (A) Read the EXIF information from the image file.
  • (B) Output the appropriate HTTP headers, the bare minimum is Content-Type , and Content-Length is kind of optional. But since some browsers can get naggy about the length, it is better to just include it.
  • (B) Lastly, just use readfile() to read and output the image file itself.
  • (B) To ensure that the image data is “safely and completely” delivered, we use output buffering – ob_start() and ob_end_flush() . Will leave links below if you want to follow up on output buffers.

That’s all. Accessing this script in the browser will show the image, or we can point an image tag to this PHP script:

EXAMPLE 2) BASE 64 ENCODED IMAGE

This is an alternative to reading an image file and outputting it with PHP – Yes, we can read an image file, base 64 encode it, and “directly embed” it into an tag.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Display Image From File In PHP (Simple Examples)”

I can’t get any of this to run. What do you run first 1a or 1b or . I think 1b ends up showing an empty square box in the upper left corner of the screen but clicking on it does nothing. Do you run it with localhost ? firefox ? php ?

Thanks in advance for help in getting this to run.
R

Put this tutorial aside first. Don’t break your own neck by skipping all the raw basics – Good luck!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Функция вставки изображения в PHP

Admin 08.09.2017 , обновлено: 09.09.2017 PHP, WordPress

В процессе вёрстки сайта на WordPress приходится вставлять изображения в PHP коде. Сложность заключается в том, что в echo нужно вставить другой php код.

Для этого я использую следующую конструкцию:

$img_url = get_bloginfo(‘template_url’) . ‘/assets/img/img.png’;
echo ‘ ‘;
?>

Если требуется автоматически вставлять в title и alt текущее названия раздела:

$img_url = get_bloginfo(‘template_url’) . ‘/assets/img/img.png’;
$title_attribute = single_cat_title( ‘Жанр ‘, », false );

'.$title_attribute.'

echo »;
?>

В коде выше присваиваем переменной $img_url путь к файлу изображений, которое нужно вывести. Используется функция get_bloginfo(‘template_url’), которая указывает путь до шаблона WordPress.

Вместо неё можно использовать конструкцию пути от корня сайта:

Для вывода php пути внутри изображения используется конструкции без get:

Источник

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