Created
February 24, 2020 19:41
-
-
Save radist2s/716a729c2b150cdb31e7a9e24fc423ae to your computer and use it in GitHub Desktop.
Wordpress custom GD editor with `fill_background` ability to fill PNG alpha with color fill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Custom_WP_Image_Editor_GD extends WP_Image_Editor_GD { | |
/** | |
* @param array $rgb | |
* | |
* @return false|resource | |
*/ | |
public function fill_background( $rgb ) { | |
$width = $this->size['width']; | |
$height = $this->size['height']; | |
$image_background_resource = imagecreatetruecolor( $width, $height ); | |
$image_fill_arguments = array_merge( | |
array( $image_background_resource ), | |
apply_filters( 'wpp_image_editor_gd_background_color', $rgb, $this ) | |
); | |
$image_fill_color = call_user_func_array( 'imagecolorallocate', $image_fill_arguments ); | |
imagefilledrectangle( $image_background_resource, 0, 0, $width, $height, $image_fill_color ); | |
imagealphablending( $this->image, true ); | |
$is_copied = imagecopy( $image_background_resource, $this->image, 0, 0, 0, 0, $width, $height ); | |
if ( $is_copied ) { | |
imagedestroy( $this->image ); | |
$this->image = $image_background_resource; | |
} else { | |
imagedestroy( $image_background_resource ); | |
} | |
return $is_copied; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$output_image_mime_type = 'image/jpeg'; | |
$source_image_path = 'file.png' // output will be `file.png.jpeg` | |
$wp_image_editors_filter_callback = function () { | |
return array( 'Custom_WP_Image_Editor_GD' ); | |
}; | |
add_filter( 'wp_image_editors', $wp_image_editors_filter_callback); | |
$editor = wp_get_image_editor( $source_image_path ); | |
$editor->fill_background(array(255, 255, 255)); | |
$saved = $editor->save( "{$source_image_path}.$output_image_format", array( 'mime_type' => $output_image_mime_type ) ); | |
remove_filter( 'wp_image_editors', $wp_image_editors_filter_callback); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment