Skip to content

HEIC images support. #199

Description

@gwin
// HEIC to JPEG Conversion
add_filter('wp_handle_upload', 'convert_heic_to_jpeg');

function convert_heic_to_jpeg($file) {
$file_path = $file['file'];
$file_type = mime_content_type($file_path);

// Only process HEIC/HEIF images
if ($file_type === 'image/heic' || $file_type === 'image/heif') {
if (!class_exists('Imagick')) {
return $file;
}

try {
$image = new Imagick($file_path);

// Convert HEIC to JPEG
$image->setImageFormat('jpeg');
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(75);

// Create a new JPEG file path
$new_file_path = preg_replace('/\.(heic|heif)$/i', '.jpg', $file_path);
$image->writeImage($new_file_path);
$image->clear();
$image->destroy();

// Delete original HEIC file
if (!unlink($file['file'])) {
error_log('<pre><strong>Debug:</strong> Failed to delete original HEIC file: ' . $file['file'] . '</pre>');
}

// Update file array with new JPEG data
$file['file'] = $new_file_path;
$file['url'] = str_replace(basename($file_path), basename($new_file_path), $file['url']);
$file['type'] = 'image/jpeg';
$file['name'] = preg_replace('/\.(heic|heif)$/i', '.jpg', $file['name']);

// Update WordPress media attachment metadata
$attachment_id = attachment_url_to_postid($file['url']);
if ($attachment_id) {
update_attached_file($attachment_id, $new_file_path);
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $new_file_path));
}

} catch (Exception $e) {
error_log('<pre><strong>Debug:</strong> HEIC to JPEG conversion failed: ' . $e->getMessage() . '</pre>');
}
}

return $file;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions