Automatically Convert PNGs to JPEGs in Wordpress

WARNING: This article features ANCIENT code! I'm keeping it online because it's interesting to see what I was thinking 10+ years ago. But you DEFINITELY should not be using this code. Anything you're reading about on this page has changed significantly since this was written.

This took me entirely too long to figure out.. The goal was to reduce the load page and server load by converting PNGs to JPEGs. This method may be lack a bit of subtlety, as it always converts PNGs to JPEGs. Maybe sometimes you actually do want a PNG. Something to consider for the future.. anyway, dropping this in your functions.php or wrapping it in a plugin should do the trick:

<?php
add_action('wp_handle_upload', 'my_resample_handle_upload');
function my_resample_handle_upload($arr) {
    if($arr['type'] != 'image/png') {
        return $arr;
    }
    $file = $arr['file'];
    $url = $arr['url'];
    $dst_file = substr($file, 0, -3) . 'jpg';
    $dst_url = substr($url, 0, -3) . 'jpg';
    list($width, $height, $type, $attr) = getimagesize($file);
    $image = imagecreatefrompng($file);
    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $width, $height);
    imagejpeg($new_image, $dst_file);  
    imagedestroy($new_image);
    $arr['file'] = $dst_file;
    $arr['url'] = $dst_url;
    $arr['type'] = 'image/jpeg';
    return $arr;
}

Seems to do the job.