I tried manually implementing the Drupal 6 patch https://www.drupal.org/files/force_jpg-1557758-1_0.patch located in https://www.drupal.org/node/1557758 for Drupal 7. It didn't actually change the format of images, it just changes the extension. Any ideas on how to adapt this to Drupal 7?

Comments

Marvin Daugherty’s picture

This alters the image format after it is saved and leaves the extension as .png. The .png extension really doesn't matter as long as the MIME type is correct.

On line 518 just above '@chmod($image['destination'], 0664);' in /sites/all/modules/image_resize_filter/image_resize_filter.module, I stuck in...

 if ($path_info['extension'] == 'png') {
     $filePath = drupal_realpath($image['destination']);
     $new_image = imagecreatefrompng($filePath);
     $bg = imagecreatetruecolor(imagesx($new_image), imagesy($new_image));
     imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
     imagealphablending($bg, TRUE);
     imagecopy($bg, $new_image, 0, 0, 0, 0, imagesx($new_image), imagesy($new_image));
     imagedestroy($new_image);
     $quality = 75; // 0 = worst / smaller file, 100 = better / bigger file 
     imagejpeg($bg, $filePath, $quality);
     imagedestroy($bg);
 }

If anyone has an improvement, I would be appreciative.

Marvin Daugherty’s picture

Improved it so it checks the MIME format before replacing it with a JPEG. Also, tests for 'nojpg' in the file name for those times where you just have to have a transparency.

// If valid path i.e. not false, get MIME type.
$image_mime = image_get_info($image['destination']) ? image_get_info($image['destination'])['mime_type'] : false;
// If MIME is a PNG and the path does not contain 'nojpg', then process into a JPEG.
if ($image_mime == 'image/png' && strpos($image['destination'], 'nojpg') === false) {
    $filePath = drupal_realpath($image['destination']);
    $new_image = imagecreatefrompng($filePath);
    $bg = imagecreatetruecolor(imagesx($new_image), imagesy($new_image));
    imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
    imagealphablending($bg, TRUE);
    imagecopy($bg, $new_image, 0, 0, 0, 0, imagesx($new_image), imagesy($new_image));
    imagedestroy($new_image);
    $quality = 75; // 0 = worst / smaller file, 100 = better / bigger file 
    imagejpeg($bg, $filePath, $quality);
    imagedestroy($bg);
}

As always, comments are appreciated.