国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Problem How to output images in PHP? (Detailed explanation of the legend)

How to output images in PHP? (Detailed explanation of the legend)

Oct 19, 2021 pm 03:44 PM
php image

In the previous article, I brought you "How to upload files in PHP? You’ll understand after reading it! 》, which introduces you in detail how to upload files in PHP. This article will take a look at the relevant knowledge of image processing in PHP. I hope it will be helpful to everyone!

How to output images in PHP? (Detailed explanation of the legend)

Image processing is something that is often encountered in PHP work. We encounter many scenarios where images need to be processed, such as image verification codes, image watermarks, etc. In fact, the focus of learning image processing is to learn the functions of the GD system in PHP. Image processing in PHP requires the support of the GD library, so let's first take a look at the relevant knowledge about the GD library.

GD library

The GD library can be understood as a function library for creating graphics images. The GD library actually It is written in C language and can be used in PHP. In addition to PHP, it can also be used in Perl and other languages. The GD library provides many interfaces for processing images.

GD is used in PHP The library can draw various graphics images, statistical charts, and image verification codes on the page, which can also be implemented using the GD library.

The example is as follows:

<?php
phpinfo();
?>

After input, in the output result, if the two options shown below appear, it means that the current machine supports image processing through GD:

How to output images in PHP? (Detailed explanation of the legend)

Or you can use:

<?php
    print_r(gd_info());
?>

After input, run it. If the output result is as shown in the figure below, it also means that the current machine supports processing through GD image.

How to output images in PHP? (Detailed explanation of the legend)

If it is not installed, you can also just change the "extension=php_gd2.dll" item in the php.ini configuration file under the Windows system The previous comment deletion method is completed.

In PHP, the operation of processing images through the GD library is generally divided into 4 basic steps:

  • Create canvas

  • Draw image

  • Output image

  • Release resources

We will complete it through these four steps Now that you know the basic operations on images, let’s take a look at how to operate them.

Create canvas

All our drawing and image processing need to be completed on a background image, which is the canvas, which can be understood as For images, we have a temporary area in memory as a canvas to store image information. Future image operations will be performed on this area, which is the canvas.

imagecreate() and imagecreatetruecolor() are used to create canvas. Their syntax format is as follows:

imagecreate(int $width, int $height)
imagecreatetruecolor(int $width, int $height)

Among them, $width It means that the width of the created canvas can also be understood as the width of the image. $height means that the height of the created canvas is also the height of the image.

Both of these two functions can be used to create a canvas, but the difference is that they can The range of colors accommodated varies.

The example is as follows:

<?php
    $img = @imagecreatetruecolor(120, 20) or die(&#39;畫布創(chuàng)建失?。?amp;#39;);
?>

Since a canvas is just created and there is nothing on it, the browser will not output the canvas, but it can be passed through imagesx() and imagesy( ) to get the width and height of the image:

<?php
    $img = @imagecreatetruecolor(120, 20) or die(&#39;畫布創(chuàng)建失??!&#39;);
    echo &#39;畫布的寬度為:&#39;.imagesx($img).&#39;像素&#39;;
    echo &#39;<br>畫布的高度為:&#39;.imagesy($img).&#39;像素&#39;;
?>

Output result:

How to output images in PHP? (Detailed explanation of the legend)

From this we have completed creating a canvas.

In addition to using the above two functions to create a canvas, you can also create images through files or URLs in the following ways:

  • ##imagecreatefromgif() : Create a new image through a GIF file or URL

  • imagecreatefromjpeg() : Create a new image through a JPEG file or UR

  • imagecreatefrompng() : Create a new image through a PNG file or URL

  • ##imagecreatefromwbmp()

    : Create a new image through a WBMP file or URL An image

Output imageIn the above example, we have successfully created the canvas, which is different in PHP Format images also require different functions for output. The different functions are as follows:

  • imagegif()

    : Output a GIF format image to the browser or File

  • imagejpeg()

    : Output a JPEG format image to the browser or file

  • imagepng( )

    : Output a PNG format image to a browser or file

  • Their syntax format is as follows:

imagegif(resource $image[, string $filename])
imagejpeg(resource $image[, string $filename[, int $quality]])
imagepng(resource $image[, string $filename])

其中,$image為創(chuàng)建的一個圖像資源;$filename表示為參數(shù),用來設(shè)置文件需要保存的路徑。

示例如下:

首先我在根目錄中已經(jīng)保存了一個名為php.png的圖像文件

<?php
    header(&#39;Content-type:image/jpeg&#39;);
    $image= imagecreatefrompng(&#39;php.png&#39;);
    imagepng($image);
?>

輸出結(jié)果:

How to output images in PHP? (Detailed explanation of the legend)

通過imagecreatefrompng()函數(shù)和imagepng()成功的輸出了一個格式為png的圖片。

釋放圖像資源

通過上述示例已經(jīng)成功的輸出了圖片,在圖片的資源使用完成后,通常需要釋放圖像處理時所占用的內(nèi)存,那應(yīng)該怎樣操作呢?

在PHP中我們通過imagedestroy() 函數(shù)來釋放圖像資源,語法格式如下:

imagedestroy(resource $image)

其中$image表示需要釋放資源的圖像

示例如下:

<?php
    header(&#39;Content-type:image/jpeg&#39;);
    $image= imagecreatefrompng(&#39;php.png&#39;);
    imagepng($image);
    imagedestroy($image);
?>

因為釋放圖像資源的操作是沒有輸出內(nèi)容的,所以就不列出輸出結(jié)果了。

推薦學(xué)習(xí):《PHP視頻教程

The above is the detailed content of How to output images in PHP? (Detailed explanation of the legend). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

See all articles