PHP convert image to base64 format (pros and cons)

First, the advantages and disadvantages of converting pictures to base64 format

1. Advantages

(1) The images in base64 format are in text format, occupying less memory, and the size ratio after conversion is about 1/3, which reduces the consumption of resource servers;

(2) When images in base64 format are used in web pages, there is no need to request the server to call image resources, which reduces the number of server visits.

2. Disadvantages

(1) There are many text contents in base64 format, and storing them in the database increases the pressure on the database server;

(2) Although the web page does not need to access the server for loading images, because there is too much content in base64 format, the speed of loading web pages will be reduced, which may affect the user's experience.

(3) Base64 cannot be cached. To cache, only files containing base64 can be cached, such as js or css, which is much worse than directly caching images, and generally HTML changes are frequent, so it is equivalent to not getting the benefit of caching.

2. PHP convert image to base64 format function

	/**
	* Image to base64
	* @param ImageFile String image path
	* @return image converted to base64
	*/
    function Base64EncodeImage($ImageFile) {
        if(file_exists($ImageFile) || is_file($ImageFile)){
            $base64_image = '';
            $image_info = getimagesize($ImageFile);
            $image_data = fread(fopen($ImageFile, 'r'), filesize($ImageFile));
            $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
            return $base64_image;
        }
        else{
            return false;
        }
    }

3. Practical application of base64 images

<img src="data:image/jpeg;base64,/9j/4AAQS……"/>

Because of the shortcomings of the use of base64, we will choose to use base64 images when the general image is less than 10kb, such as some emoji images. Converting too large images to base64 is not worth the loss. Of course, extreme cases are considered extreme.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325851370&siteId=291194637