Url to png php

Saving an Image from URL in PHP

Sometimes, need to download an image from a particular URL and use it into the project. It’s easy to go to the page and use right click button and save the image. But what if you wanted to do it programmatically? The reasons may vary person to person, developer to developer. If set of hundreds of image URLs given and somehow want to save them into the machine, or need to use this concept into the projects. Then definitely not going to download each one of those files manually.

There are two different approaches to download image from url which are listed below:

Both of these approaches come with their own set of merits and demerits.

Using Basic File Handling: This is the fundamental and easiest way to accomplish the task. Just like any other file, start with the creation of an empty file and open it in “write” mode. After that, fetch the content from source URL and paste it into this file. And it is as simple as it sounds.

Читайте также:  Ширина блока

From the script, you can figure out on your own about what it does.

  • Declaring two variables named as $url and $img, representing the source URL and destination file respectively.
  • Use file_put_contents() function to write a string to a file that takes two arguments. One is the file name (or path) and the other is the content for that file.
  • Use file_get_contents() function to read a file into a string.

Note: It save the image to the server with given name logo.png.

Now the only problem with this method is that it requires allow_url_fopen configuration to be set, which is set to 1 by default. But sometimes, project requirements don’t allow to have this option. This may be because of some preventive security measures or just a design principle. In such cases, there is another method to save image.

Using HTTP library, cURL: Strictly speaking, cURL is not just an HTTP library. It has got several other data transferring protocols as well. As our image is on an HTTP server, we will limit ourselves to this small section of this library.

cURL allows to make HTTP requests in PHP. Start by initializing an instance of it and setting up some of the necessary options for the request, including the URL itself. Then execute this query which returns the content of the file. After that, the rest of the procedure is the same. As soon as we get the data, put it into a file and save it.

  • In this script, we defined a function file_get_contents_curl to replicate the behaviour of file_get_contents from the previously mentioned technique.
  • Inside this function, we have initialised an instance of cURL using curl_init function in order to use it for fetching the data.
  • After that, some options need to be set using curl_setopt so that this particular example can work. This function takes three arguments
    • An instance of cURL
    • The corresponding option that need to be set
    • And the value to which option is set

    In this example, the following options are set:

    • CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not;
    • CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly.
    • There is this another option CURLOPT_URL that sets the URL for the request.

    Источник

    imagepng

    Ресурс изображения, полученный одной из функций создания изображений, например, такой как imagecreatetruecolor() .

    Путь для сохранения файла. Если не установлен или равен NULL , изображение будет выведено в поток вывода в бинарном виде.

    Замечание:

    Недопустимо передавать NULL , если не используются аргументы quality и filters .

    Степень сжатия: от 0 (нет сжатия) до 9.

    Позволяет уменьшить размер PNG файла. Это битовая маска, значением которой может быть комбинация констант PNG_FILTER_XXX. Для включения или выключения всех фильтров удобно воспользоваться константами PNG_NO_FILTER или PNG_ALL_FILTERS соответственно.

    Возвращаемые значения

    Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

    Список изменений

    Версия Описание
    5.1.3 Добавлен аргумент filters .
    5.1.2 Добавлен аргумент quality .

    Примеры

    $im = imagecreatefrompng ( «test.png» );

    header ( ‘Content-Type: image/png’ );

    imagepng ( $im );
    imagedestroy ( $im );
    ?>

    Смотрите также

    • imagegif() — Выводит изображение в браузер или пишет в файл
    • imagewbmp() — Выводит изображение в браузер или пишет в файл
    • imagejpeg() — Выводит изображение в браузер или пишет в файл
    • imagetypes() — Возвращает список типов изображений, поддерживаемых PHP сборкой
    • imagesavealpha() — Установка флага сохранения всей информации альфа компонента (в противовес одноцветной прозрачности) и сохранение PNG изображения

    Источник

    4 Ways To Convert HTML To Image In PHP

    Welcome to a tutorial on how to convert HTML to an image in PHP. So you have a PHP project that needs to convert HTML into an image? Bad news, there are no free “HTML to image” libraries at the time of writing.

    • Use the browser headless mode to open a URL and capture a screenshot.
    • Open the HTML in a browser, capture a screenshot, then send it to PHP for processing.
    • Use an online conversion service.
    • Convert HTML to PDF first, then save the PDF as an image.

    It’s kind of roundabout, but possible – Read on for the examples!

    TABLE OF CONTENTS

    DOWNLOAD & NOTES

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

    EXAMPLE CODE DOWNLOAD

    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.

    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.

    PHP HTML TO IMAGE

    All right, let us now get into the possible ways of converting HTML into an image in PHP.

    TUTORIAL VIDEO

    1) HEADLESS MODE SCREENSHOT

    // (A) SETTINGS $chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"; // path to chrome $saveas = __DIR__ . DIRECTORY_SEPARATOR . "demoA.png"; // save screenshot $size = "1080,1920"; // height, width $url = "https://code-boxx.com"; // url to access // (B) HEADLESS CHROME $cmd = 
    • This snippet simply runs chrome --headless --screenshot="demoA.png" --window-size=1080,1920 "https://code-boxx.com" in the command line.
    • “Headless mode” will open the browser but does not show it on the screen.
    • That is, silently open https://code-boxx.com and take a screenshot.

    For those who are lost – Create your own HTML file, for example, http://localhost/foo.html . Use headless mode to access that HTML file and take a screenshot, that’s your “HTML to image” conversion.

    P.S. Both Opera and Edge are also Chromium-based, capable of running in headless mode. Firefox can also run in headless mode. Not too sure about the half-eaten apple.

    2) BROWSER SCREENSHOT

    2A) HTML & JAVASCRIPT

     

    TEST PAGE

    Hello world!

    • (B1) We are using HTML2Canvas to capture a screenshot
    • (B2) Upload the screenshot to the server.

    P.S. You can create a bat (Windows) or sh (Linux/Mac) to open a web browser. For example, chrome.exe --app=http://localhost/2a-page.php . Then, set it to run on schedule, or use PHP exec() to call it on demand.

    2B) PHP

    In this example, we simply save the uploaded screenshot to a PNG file. In your project, you can pretty much do whatever you want – Save into a database, save into a cloud drive, send via email, etc…

    3) ONLINE HTML TO IMAGE SERVICE

    TEST PAGE 

    Hello world!

    HTML; // (A2) CSS $css = p < color: red; >CSS; // (B) USE API TO CREATE PNG // (B1) CURL INIT $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://hcti.io/v1/image"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ "html" => $html, "css" => $css ])); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_USERPWD, "user_id" . ":" . "api_key"); // CHANGE TO YOUR OWN! curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]); // (B2) CURL EXEC $result = curl_exec($ch); if (curl_errno($ch)) < echo curl_error($ch); >curl_close($ch); $result = json_decode($result, true); // (C) FETCH & SAVE PNG $fh = fopen("demoC.png", "w"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $result["url"]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $fh); curl_exec($ch); curl_close($ch); fclose($fh); echo "OK";
    • (A & B) Create your HTML/CSS as usual.
    • (B) Send the HTML/CSS to HCTI, create a PNG image.
    • (C) Fetch the generated image, do whatever is required – We simply save it in this example.

    P.S. Remember to sign up for a free account and change the user/password to your own in (B1).

    4) HTML TO PDF, PDF TO IMAGE

    // (A) HTML CONTENT $html = TEST PAGE 

    Hello world!

    HTML; // (B) HTML TO PDF require "vendor/autoload.php"; $mpdf = new \Mpdf\Mpdf(); $mpdf->WriteHTML($html); $mpdf->Output("demoD.pdf"); // (C) PDF TO IMAGE $image = new Imagick("demoD.pdf"); $image->setImageFormat("jpg"); $image->writeImage("demoD.jpg");
    • MPDF – The easiest way is to use Composer composer require mpdf/mpdf .
    • ImageMagick – The installation is kind of confusing, and cannot be explained in a paragraph… You will need to do some research on your own.

    But yep, this is pretty much “HTML to PDF”, then “PDF to image”.

    EXTRAS

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

    WHICH IS THE BEST METHOD?

    • Browser Screenshot (headless or not) – I am personally leaning towards this method, simply because it’s the most accurate and free.
    • Online Service – Works if you are running a command line PHP, but probably need to pay if you need to process many of such images.
    • HTML to PDF to image – Works as well, but inefficient.

    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!

    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.

    Источник

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