Custom module for converting webp to jpg on node save in Drupal 7
So, the problem is as a result of the import of node, images paths in webp format were imported into the image field. The problem is that for Drupal 7 there are practically no solutions how to make the existing filled fields of images with the webp format work. Reference to manually - excluded. To solve, we create a custom module, which during the rebuilding of the node converts the image of the webp into the format of the jpg.
Create in module folder - site/all/module folder custom/webp_to_jpg. Inside create file webp_to_jpg.info
webp_to_jpg.infoname = WebP to JPG Converter
description = Converts WebP images to JPG on node save.
core = 7.x
package = Custom
and webp_to_jpg.module
<?php
/**
* Implements hook_node_presave().
*/
function webp_to_jpg_node_presave($node) {
if ($node->type == 'device') {
$field_items = field_get_items('node', $node, 'field_image');
if (!empty($field_items)) {
foreach ($field_items as $index => $item) {
$file = file_load($item['fid']);
if (pathinfo($file->uri, PATHINFO_EXTENSION) === 'webp') {
$converted_file = webp_to_jpg_convert($file);
if ($converted_file) {
// Заменить файл в поле
$node->field_image[LANGUAGE_NONE][$index] = (array) $converted_file;
}
}
}
}
}
}
/**
* Converts a WebP file to a JPG file.
*
* @param object $file
* File object to convert.
*
* @return object
* The converted file object.
*/
function webp_to_jpg_convert($file) {
$image = imagecreatefromwebp($file->uri);
if ($image === FALSE) {
return NULL;
}
$new_uri = preg_replace('/\.webp$/', '.jpg', $file->uri);
imagejpeg($image, $new_uri, 100);
imagedestroy($image);
$file_info = image_get_info($new_uri);
$new_file = file_save_data(file_get_contents($new_uri), $new_uri, FILE_EXISTS_REPLACE);
return $new_file;
}
Where 'device' is node type that we need and 'field_image' is field with image.
Thus, now with a simple node rebuilding, all images from the field_image field will be converted into the jpg format.