Freelancer_Titon
Member
Hello,
I'm trying to develop an add-on for XenForo 2.2.15 that automatically converts uploaded images to WebP format. I've used some code, but it's not working properly.
Here's what I've tried:
The images are still being uploaded in PNG format and are not being converted to WebP.
Could someone please help me with this? Are there any specific settings or libraries required for WebP conversion in XenForo 2.2.15?
Thank you.
I'm trying to develop an add-on for XenForo 2.2.15 that automatically converts uploaded images to WebP format. I've used some code, but it's not working properly.
Here's what I've tried:
- Added code to the Attachment.php file in the add-on.
- Attempted to use the Imagick library.
- Tried reducing the size of the uploaded images.
The images are still being uploaded in PNG format and are not being converted to WebP.
Could someone please help me with this? Are there any specific settings or libraries required for WebP conversion in XenForo 2.2.15?
Code:
<?php
namespace YourAddonNamespace\XF\Entity;
class Attachment extends XFCP_Attachment
{
protected function _postSave()
{
parent::_postSave();
if ($this->isInsert() && $this->isImage() && $this->isWebpSupported()) {
$this->convertToWebp();
}
}
protected function isWebpSupported()
{
return function_exists('imagewebp');
}
protected function convertToWebp()
{
$imagePath = $this->getFilePath();
$webpPath = $imagePath . '.webp';
try {
$image = imagecreatefromstring(file_get_contents($imagePath));
if (!$image) {
return;
}
ob_start();
imagewebp($image, null, 80);
$webpData = ob_get_contents();
ob_end_clean();
imagedestroy($image);
file_put_contents($webpPath, $webpData);
$this->Data['file_path'] = $webpPath;
$this->save();
unlink($imagePath);
} catch (\Exception $e) {
\XF::logException($e, false, 'WebP conversion failed: ');
}
}
}
Thank you.