Custom Upload Image in Ckfinder , After then We Can Create a Element picture in CKEDITOR, Help Me Optimize Website Speed

Hôm nay tôi chia sẻ với các bạn cách để custom một tấm hình khi upload bằng ckfinder lên website, Custom ở đây các bạn có thể hiểu là => Tôi sẽ custom lại thẻ phần tử html và insert ngược lại nội dung trong ckeditor

Thông thường ckfinder khi upload ảnh lên nó sẽ sinh ra thẻ <img />, nay tôi custom nó lại thành như sau:

<picture>
            <source type="image/webp" setsrc="${imageSrcUrl}.webp">
            <img src="${imageSrcUrl}.webp" alt="" style="height:333px; width:500px">
 </picture>

Ah quên nói các bạn là, để có hình webp bạn cũng phải kết hợp việc chuyển hình từ jpg, png => webp nhé, chứ không phải custom là nó ra webp liên, mà ta cần phải convert nó ra hình webp trước rồi mới custom lại đường dẫn hình chứa file webp đó

Các bạn có thể tìm hiểu thêm tại đây:

Get The Image In The Content. Then Convert The Image To Webp. Help Me Optimize Website Speed ( bạn xem link này, có chỉ cách bạn convert hình sang webp)

+ Sử dụng rosell-dk/webp-convert ( bạn có thể convert hình đến webp)

Sau khi có hình webp và biết cách convert hình đến webp, thì bạn tiến hành kết hợp với việc custom nó như đoạn code sau:

Dưới đây là đoạn code khi thực hiện custom nó

<script>

    // bat su kien chon file ckfinder

    CKEDITOR.on('dialogDefinition', function(ev) {
        // Take the dialog name and its definition from the event data
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;
        var editor = ev.editor;
        if (dialogName == 'image') {
         dialogDefinition.onOk = function(e) {

          var imageSrcUrl = e.sender.originalElement.$.src;

          //goi ajax resize luon
          
          const xhttp = new XMLHttpRequest();
          xhttp.onload = function() {
            // location.reload();
            imageSrcUrl = imageSrcUrl.replace("/hinhanh/", "/webp/");
            var hkt_html = `<picture>
            <source type="image/webp" setsrc="${imageSrcUrl}.webp">
            <img src="${imageSrcUrl}.webp" alt="" style="height:333px; width:500px">
            </picture>`;
            var imgHtml = CKEDITOR.dom.element.createFromHtml(hkt_html);
            editor.insertElement(imgHtml);

          }
          xhttp.open("POST", "/getWebp.php");
          xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xhttp.send("UrlHinh="+imageSrcUrl);
        };
      }
    });
</script>

Các bạn chú ý bên trên mình có viết một ajax với method="post" gửi đến file getWebp.php

1. Trong file getWebp.php nó nhận một đường link hình ảnh, sau đó nó convert ảnh đó sang webp và lưu vào thư mục webp

2. Sau khi hình ảnh đã được convert sang webp, ajax nó sẽ gọi lại hàm xhttp.onload để xử lý việc thêm thẻ <picture> vào ckeditor

Đây File getWebp.php

<?php

include "DB.php";
$db = new DB;
$UrlHinh = $_GET['UrlHinh'];
if ($UrlHinh != '') {
    $db->hkt_resize($UrlHinh, 200, 155);
    $db->hkt_resize($UrlHinh, 120, 95);
     $db->hkt_resize($UrlHinh, 150, 100);
    $db->hkt_resize($UrlHinh, 400, 320);
    $db->hkt_saveWebp($UrlHinh);
     $db->hkt_saveWebp(str_replace("/hinhanh/", "/resize/200x155/", $UrlHinh));
     $db->hkt_saveWebp(str_replace("/hinhanh/", "/resize/120x95/", $UrlHinh));
     $db->hkt_saveWebp(str_replace("/hinhanh/", "/resize/150x100/", $UrlHinh));
    $db->
hkt_saveWebp(str_replace("/hinhanh/", "/resize/400x320/", $UrlHinh));
}

Tiếp tục là file class DB.php ( giúp xử lý việc convert)

<?php 
//wp-admin dir
 class DB{
    public function hkt_saveWebp($UrlHinh)
    {
    	// echo $UrlHinh;echo "</br>";
    	// echo $UrlHinh;
    	// echo "</br>";
    	// echo $_SERVER['DOCUMENT_ROOT'] ;echo "</br>";
    	$file_name = basename($UrlHinh);
    	$path_get_content = $_SERVER['DOCUMENT_ROOT'] ."/". str_replace("https://hoanguyenit.com/", "", $UrlHinh);
    	// echo $path_get_content;echo "</br>";
    	$path_to = str_replace($file_name, "", $path_get_content);

    	if (strpos($path_to, "/resize/")) {
            // neu hien tai hinh anh nam trong thu muc resize
    		$path_to = str_replace("/resize/", "/webp/", $path_to);
    	} else {
    		$path_to = str_replace("/hinhanh/", "/webp/", $path_to);
    	}
    	// echo $path_get_content;echo "</br>";
    	// echo $path_to;echo "</br>";
        //kiem tra duong dan file
    	if (!file_exists($path_to)) {
    		mkdir($path_to, 0777, true);
    	}

        //filename : duong dan thu muc
    	$image = imagecreatefromstring(file_get_contents($path_get_content));
    	ob_start();
    	imagejpeg($image, NULL, 100);
    	$content1 = ob_get_contents();
    	ob_end_clean();
    	imagedestroy($image);
    	$content2 = imagecreatefromstring($content1);
    	$output = $path_to . $file_name . ".webp";
    	// exit();
    	imagewebp($content2, $output);
    	imagedestroy($content2);
    	// echo 1;exit();
    }


    public function hkt_resize($UrlHinh,$newWidth,$newHeight){
    	$file_name = basename($UrlHinh);
    	$path_get_content = $_SERVER['DOCUMENT_ROOT'] ."/". str_replace("https://hoanguyenit.com/", "", $UrlHinh);
    	list($width,$height,$type)= getimagesize($path_get_content);
    	// echo strtolower(image_type_to_mime_type($type));exit();
    	$newImage = imagecreatetruecolor($newWidth,$newHeight);

    	// kiem tra file nhap vao
    	switch(strtolower(image_type_to_mime_type($type)))
		{
			case 'image/jpeg':
			$source = imagecreatefromjpeg($path_get_content);
			break;
			case 'image/jpg':
			$source = imagecreatefromjpeg($path_get_content);
			break;      
			case 'image/png':
			$source = imagecreatefrompng($path_get_content);
			break;
			case 'image/gif':
			$source = imagecreatefromgif($path_get_content);
			break;
			default:
			return false;
		}

    	imagecopyresized($newImage, $source,0,0,0,0,$newWidth, $newHeight,$width,$height);

    	$path_to = str_replace($file_name, "", $path_get_content);
    	$path_to = str_replace("/hinhanh/", "/resize/{$newWidth}x{$newHeight}/", $path_to);

    	if (!file_exists($path_to)) {
    		mkdir($path_to, 0777, true);
    	}

    	//save image
    	imagejpeg($newImage,$path_to.$file_name);
    }

  

 }

Vậy là xong, mọi người có thể thử xem nhé

Mà thật nói webp nó giúp bạn tối ưu website của bạn rất nhiều, giúp web load nhẹ hơn, tối ưu hình ảnh hơn. 

 

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!)