Get the image in the content. Then convert the image to webp. Help me optimize website speed

Hôm nay mình chia sẻ với các bạn cách để lấy những hình ảnh trong nội dung bài viết. Chỉ chọn những hình có kích thước lớn hoặc bao nhiêu tuỳ thuộc vào website đó hình ảnh bài viết là khoảng bao nhiêu

Tại cũng đang tối ưu website trên trang https://pagespeed.web.dev/ vì thế chia sẻ với mọi người luôn

Okay , let's go

Đầu tiên mình sẽ code một cái function để chuyển đổi webp , hãy tạo file resize.php và code dùng code bên dưới đây

<?php


function resize_img($remoteImageUrl,$opacity) {
    // Remote image URL

    
    // Get the image data from the remote URL
    $imageData = file_get_contents($remoteImageUrl);

    // Create an image resource from the image data
    $image = imagecreatefromstring($imageData);
    
    // Get the current dimensions of the image
    $width = imagesx($image);
    $height = imagesy($image);
    
    // Calculate the aspect ratio of the original image
    $aspectRatio = $width / $height;
    
    // Calculate the new dimensions while maintaining the aspect ratio
    if ($aspectRatio > 1) {
        if (isset($_GET["w"]) && isset($_GET["h"])) {

            $newWidth = $_GET["w"];
            $newHeight = $_GET["w"] / $aspectRatio;
        } else {
            $newWidth = $width;
            $newHeight = $width / $aspectRatio;
        }
    } else {
        if (isset($_GET["w"]) && isset($_GET["h"])) {

            $newWidth = $_GET["h"] * $aspectRatio;
            $newHeight = $_GET["h"];
        } else {
            $newWidth = $height * $aspectRatio;
            $newHeight = $height;
        }
        
    }
    
    // Create a new image with the target dimensions
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // Resize the original image to the new dimensions
    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    // Apply opacity effect to the resized image
    imagefilter($resizedImage, IMG_FILTER_COLORIZE, 0, 0, 0, 127 * (100 - $opacity) / 100);
    // Output the resized image directly to the browser
    header('Cache-Control: max-age=31536000');
    header('Content-Type: image/webp');
    imagejpeg($resizedImage, null, 100);
    
    // Free up memory by destroying the image resources
    imagedestroy($image);
    imagedestroy($resizedImage);

}

$link = str_replace(' ', '%20',$_GET['url']);
resize_img($link,"40");
?>

Đoạn code mình có viết một function , đồng thời chèn 2 tham số($link,$opacity)

+ $link : là đường dẫn url của tấm hình nhé 

+ $opacity : là giá trị làm mờ tấm hình

+ header('Content-Type: image/webp') : mình muốn hình nó là thể loại webp

Okay, giờ ta cần đọc nội dung trong dữ liệu bài viết, lấy những tấm hình có kích thước lớn và loại hình cần lấy là (jpg.png), sau đó chuyển nó về thể loại webp

Nếu các bạn chưa xem bài viết này thì vào xem lại nhé : Crawler Content After Then Insert A Class To Image Url Using PHP

Okay, giờ làm thôi, ah nhớ $row['NoiDung'] là cột dữ liệu trong table của bạn đó nhé

//check img
					$array = array();
					if (preg_match_all('/<img[^>]*src="([^"]+)"/i', $row['NoiDung'], $matches)) {
						foreach ($matches[1] as $key => $value) {
							$extension = strtolower(pathinfo($value, PATHINFO_EXTENSION));
							if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'png') {
								array_push($array, $value);
							}
							
						}
					}
					 /** get size img*/
					$array_link_img = array();
					if(count($array)>0){
						for($i=0;$i<count($array);$i++){
							list($width, $height) = getimagesize($array[$i]);
							if($width>400 && $height>200){
								array_push($array_link_img,$array[$i]);
							}
						   // echo "width:".$width."/height:".$height;
						   // echo "<br/>";
						}
					}
			 
					if(count($array_link_img)>0){
						$data_replace = array();
						for($k=0;$k<count($array_link_img);$k++){

							 $bien = "https://example.com/resize.php?url=".$array_link_img[$k];
							 array_push($data_replace,$bien);
						}
					  
					 
						$row['NoiDung'] = str_replace($array_link_img,$data_replace,$row['NoiDung']);
						
					
						 
					}
	
					echo $row['NoiDung'];
				//end check img
					

Đoạn code bên trên cũng tương tự như bài viết Crawler Content After Then Insert A Class To Image Url Using PHP . Mình cũng có giải thích trong bài viết trước rồi, bạn có thể xem lại nhé

Bạn chú ý ở phần này: Chỉ chọn những hình jpg, png

$extension = strtolower(pathinfo($value, PATHINFO_EXTENSION));
if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'png') {
	array_push($array, $value);
}

Với đoạn code sau đây, chúng ta cần chèn url hình đến địa chỉ link chứa file resize.php

$bien = "https://example.com/resize.php?url=".$array_link_img[$k];

Okay, vậy là xong. Bạn có thể thử rồi đó

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)