This article mainly introduces several PHP methods to obtain images in detail.
During the project development process, it is usually necessary to implement the function of obtaining images online or locally. Below we use simple code examples to summarize and introduce several PHP methods to obtain images.
First we need to make an image type declaration in the header of the PHP file:
<?php header("content-type:image/jpeg");
Method 1: Get the image through readfile
readfile("123123.png");
readfile: Output file
The parameter here is the path of the local image
Pass the browser test and obtain the image as follows:
Also OK Obtain online images. For example, the image path parameter can be changed to:
readfile("https://img.php.cn/upload/article/000/000/003/5a9675a3b2106284.jpg");
Obtain the image as follows:
Method 2: Use curl series functions Get images
<?php header("content-type:image/jpeg"); // 初始化 $pic = curl_init(); // 设置选项 curl_setopt($pic, CURLOPT_URL, "https://img.php.cn/upload/article/000/000/003/5a9675a3b2106284.jpg"); // 执行获取到的内容 curl_exec($pic); // 释放curl句柄 curl_close($pic);
curl_init: Initialize cURL session
curl_setopt: Set cURL transmission options
The first parameter in curl_setopt() represents the initialized value, the second parameter represents the type of the input value, and the third parameter represents the image path
curl_exec: execute cURL session
curl_close: close cURL session
Finally obtained The picture is the same as the one on the center line above.
Method 3: Get the image through file_get_contents
echo file_get_contents("123123.png");
file_get_contents: Read the entire file into a string
Note : When using the file_get_contents function, you need to use echo to output the obtained content.
Method 4: Obtain images through fopen series functions
// 打开图片文件 $file = fopen("./123123.png", 'rb+'); // 读取图片文件 echo(fread($file, filesize("./123123.png"))); // 关闭文件句柄 fclose($file);
Note: Using fopen to obtain images can only obtain offline images , if you want to get online pictures, just copy the online pictures to your local computer.
The above is a detailed explanation of the four methods of PHP to obtain images. Hope it helps those in need!
If you want to know more about PHP, you can follow the PHP Chinese website PHP Video Tutorial, everyone is welcome to refer to and learn!
The above is the detailed content of How to get images in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!