Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save liber87/050267aff85d1e6b5c7b43c246029e8d to your computer and use it in GitHub Desktop.

Select an option

Save liber87/050267aff85d1e6b5c7b43c246029e8d to your computer and use it in GitHub Desktop.
Convert jpg/png on webp on content modx
<?php
if (!function_exists('imageWebp')) return;
set_time_limit(200);
define('MODX_API_MODE', true);
define('IN_MANAGER_MODE', false);
include_once("index.php");
$modx->db->connect();
if (empty ($modx->config)) {
$modx->getSettings();
}
$res = $modx->db->query('Select id,content from '.$modx->getFullTableName('site_content'));
while($row = $modx->db->getRow($res)){
$content = $row['content'];
preg_match_all('/<img[^>]+>/i',$content, $result);
if (count($result)) {
foreach($result[0] as $img_tag) {
preg_match('/(src)=("[^"]*")/i',$img_tag, $img[$img_tag]);
$img_real = str_replace('"','',$img[$img_tag][2]);
$img_real = str_replace('./','',$img_real);
$full = MODX_BASE_PATH.$img_real;
$info = getimagesize($full);
$ex = $info['mime'];
if (($ex=='image/jpeg') or ($ex=='image/png')) {
if ($ex=='image/jpeg') $webp = imageCreateFromJpeg($full);
if ($ex=='image/png') $webp = imageCreateFromPng($full);
imageWebp($webp, $full . '.' . 'webp', 100);
imagedestroy($webp);
$content = str_replace($img_real,$img_real.'.webp',$content);
}
}
}
$modx->db->update(['content'=>$content],$modx->getFullTableName('site_content'),'id='.$row['id']);
}
echo 'Complete!';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment