includes/Images/class-img-converter.php
Img_Converter Class
Class Img_Converter
Img_Converter Class
class Img_ConverterConstants
| Constant | Visibility | Value | Line |
|---|---|---|---|
SALT_KEY | private | \'wppo_img_info_salt\' | 69 |
Properties
| Property | Visibility | Type | Default | Line |
|---|---|---|---|---|
$deferred_img_info | private static | array|null | null | 35 |
$img_info_shutdown_registered | private static | bool | false | 43 |
$img_info_persisted | private static | bool | false | 51 |
$client_side_processing_state | private static | array<int, | null | 61 |
$options | private | array | — | 77 |
$available_format | private | array | array( \'webp\', \'avif\', \'both\', ) | 85 |
$format | private | string | — | 97 |
$exclude_imgs | private | array | array() | 105 |
public __construct()
public function __construct($options)Img_Converter constructor. Parameter Type Default Description $optionsarray— Options for configuring image optimization.
publicstatic core_handles_next_gen()
public static function core_handles_next_gen(): boolCheck if WordPress core (6.7+) natively handles next-gen format generation (WebP/AVIF).
Return: bool — True if core handles next-gen formats natively.
publicstatic core_handles_both_next_gen()
public static function core_handles_both_next_gen(): boolCheck if WordPress core (7.1+) natively handles both WebP and AVIF generation.
Return: bool — True if core can generate both WebP and AVIF natively.
public get_format()
public function get_format(): stringGet the current conversion format.
Return: string — The format (\’webp\’, \’avif\’, \’both\’, or \’none\’).
private resolve_encode_quality()
private function resolve_encode_quality(string $mime, int $fallback, array=array() $size): intResolve the encode quality for an output MIME type. Parameter Type Default Description $mimestring— The output MIME type (e.g. \’image/webp\’). $fallbackint— Fallback quality (1-100) used when no core API provides a value. $sizearray=array()— Optional dimensions of the source image (\’width\’/\’height\’).
Return: int — The encode quality to use (1-100).
private resolve_output_format()
private function resolve_output_format(string $source_image, string $requested_format): stringResolve the effective target format using core\’s centralized `image_editor_output_format` mapping when available. Parameter Type Default Description $source_imagestring— Filesystem path to the source image. $requested_formatstring— The format requested by the plugin (\’webp\’, \’avif\’, or \’both\’).
Return: string — The effective target format (\’webp\’, \’avif\’, \’both\’, or \’none\’).
private get_source_image_dimensions()
private function get_source_image_dimensions(string $source_image): arrayInfer the dimensions of a source image from its file name. Parameter Type Default Description $source_imagestring— Filesystem path to the source image.
Return: array — The dimensions array (\’width\’/\’height\’), empty for full-size originals.
publicstatic get_smart_quality_size_offset()
public static function get_smart_quality_size_offset(array $size): intSize-aware quality offset for the smart-quality heuristic. Parameter Type Default Description $sizearray— Optional source dimensions (\’width\’/\’height\’). Empty means full-size original.
Return: int — Offset in `[-10, +10]`.
publicstatic is_hero_candidate_image()
public static function is_hero_candidate_image(string $source_image): boolWhether a source image looks like a hero/LCP candidate. Parameter Type Default Description $source_imagestring— Filesystem path to the source image.
Return: bool — True when the file looks like a hero candidate.
publicstatic get_smart_quality_role_offset()
public static function get_smart_quality_role_offset(string=\'\' $source_image): intRole-aware quality offset for the smart-quality heuristic. Parameter Type Default Description $source_imagestring=\'\'— Filesystem path to the source image.
Return: int — Offset in `[-10, +10]`.
publicstatic apply_smart_quality_offsets()
public static function apply_smart_quality_offsets(int $base, int $size_offset, int $role_offset): intApply size + role offsets to a base quality with bounded delta. Parameter Type Default Description $baseint— Base quality (1-100) before offsets. $size_offsetint— Size-aware offset (`[-10, +10]`). $role_offsetint— Role-aware offset (`[-10, +10]`).
Return: int — Adjusted quality (1-100) within ±10 of `$base`.
publicstatic order_queue_hero_first()
public static function order_queue_hero_first(array $attachment_ids): arrayOrder attachment IDs hero-first for the conversion queue. Parameter Type Default Description $attachment_idsarray— Attachment IDs in scan order.
Return: array — Reordered IDs with hero candidates first.
publicstatic is_avif_encoder_available()
public static function is_avif_encoder_available(): boolWhether an AVIF encoder is available on this host.
Return: bool — True when AVIF encoding is supported.
publicstatic is_imagick_avif_available()
public static function is_imagick_avif_available(): boolWhether Imagick alone can encode AVIF on this host.
Return: bool — True when Imagick reports an AVIF delegate.
public encode_avif_via_imagick()
public function encode_avif_via_imagick(string $source_image, string $dest_path, int $quality, int=0 $max_edge): boolEncode a source image to AVIF via Imagick. Parameter Type Default Description $source_imagestring— Filesystem path to the source image. $dest_pathstring— Filesystem path for the `.avif` output. $qualityint— Encode quality (1-100). $max_edgeint=0— Optional longest-edge cap in pixels (`0` disables).
Return: bool — True on success, false on any failure.
public get_skip_small_threshold()
public function get_skip_small_threshold(): intGet the skip-small byte threshold for image conversion.
Return: int — Threshold in bytes (>= 0).
public should_skip_small_file()
public function should_skip_small_file(string $path): boolWhether a source file should be skipped as too small to convert. Parameter Type Default Description $pathstring— Filesystem path to the source image.
Return: bool — True when the file is at or under the threshold.
public get_longest_edge_cap()
public function get_longest_edge_cap(): intResolve the longest-edge downscale cap in pixels.
Return: int — Cap in pixels (>= 0). `0` means disabled.
public get_max_source_pixels()
public function get_max_source_pixels(): intMaximum source pixel count decodable before GD risks a fatal OOM.
Return: int — Pixel budget (>= 1).
protected get_php_memory_limit_bytes()
protected function get_php_memory_limit_bytes(): intParse PHP\’s memory_limit into bytes.
Return: int — Bytes, or `0` when unlimited or unknown.
publicstatic is_path_in_allowlist()
public static function is_path_in_allowlist(string $path): boolCheck whether an absolute filesystem path stays inside the plugin\’s read allowlist. Parameter Type Default Description $pathstring— Absolute filesystem path to check.
Return: bool — True when the path is inside the allowlist.
publicstatic is_safe_delete_path()
public static function is_safe_delete_path(string $path): boolCheck whether a path is safe to unlink (strict delete allowlist). Parameter Type Default Description $pathstring— Absolute filesystem path proposed for deletion.
Return: bool — True when deletion is allowed.
publicstatic is_safe_write_path()
public static function is_safe_write_path(string $path): boolCheck whether a conversion output path is safe to write. Parameter Type Default Description $pathstring— Absolute filesystem path proposed for writing.
Return: bool — True when writing is allowed.
publicstatic is_allowed_source_mime()
public static function is_allowed_source_mime(string $mime): boolWhether a detected source MIME may reach an image decoder (audit #1411). Parameter Type Default Description $mimestring— Detected MIME (e.g. from getimagesize()).
Return: bool — True when the MIME is a decodable bitmap type.
public exceeds_pixel_budget()
public function exceeds_pixel_budget(int $width, int $height, int=4 $channels): boolChannels-aware pre-decode pixel-budget check against the PHP memory limit. Parameter Type Default Description $widthint— Source width in pixels. $heightint— Source height in pixels. $channelsint=4— Channel count (clamped to 1-4, default 4).
Return: bool — True when the image exceeds the budget and must be skipped.
private get_source_channels()
private function get_source_channels(): intDecode channel count for the pixel-budget estimate.
Return: int — Channel count (always 4, conservative for GD truecolor).
public maybe_downscale_gd_image()
public function maybe_downscale_gd_image($image, int $width, int $height)Downscale a decoded GD image when its longest edge exceeds the cap. Parameter Type Default Description $imageresource|\\GdImage— Decoded GD image resource. $widthint— Source width in pixels. $heightint— Source height in pixels.
Return: resource|\\GdImage — Scaled image when it shrinks output, else the original.
public maybe_downscale_gd_image_to_edge()
public function maybe_downscale_gd_image_to_edge($image, int $width, int $height, int $edge)Downscale a decoded GD image to an explicit longest edge. Parameter Type Default Description $imageresource|\\GdImage— Decoded GD image resource. $widthint— Source width in pixels. $heightint— Source height in pixels. $edgeint— Target longest edge in pixels.
Return: resource|\\GdImage — Scaled image when it shrinks output, else the original.
public get_memory_safe_edge_px()
public function get_memory_safe_edge_px(int $width, int $height, int=4 $channels): intMemory-safe longest edge for an over-budget source image. Parameter Type Default Description $widthint— Source width in pixels. $heightint— Source height in pixels. $channelsint=4— Channel count (clamped to 1-4, default 4).
Return: int — Safe longest edge in pixels, or `0` when no fallback is needed/unavailable.
protected apply_imagick_memory_guard()
protected function apply_imagick_memory_guard($imagick): voidApply best-effort Imagick memory guard resource limits. Parameter Type Default Description $imagick\\Imagick— Imagick instance to guard.
Return: void.
protected decode_overbudget_image_via_imagick()
protected function decode_overbudget_image_via_imagick(string $source, int $safe_edge)Decode an over-budget still via Imagick thumbnail without a full-size GD decode. Parameter Type Default Description $sourcestring— Absolute filesystem path to the source image. $safe_edgeint— Memory-safe longest edge in pixels.
Return: resource|\\GdImage|null — Decoded GD image on success, null on any failure.
public get_smart_quality()
public function get_smart_quality(string $mime, array=array() $size, string=\'\' $source_image): intResolve the smart encode quality for an output MIME type. Parameter Type Default Description $mimestring— Output MIME type (e.g. \’image/avif\’). $sizearray=array()— Optional source dimensions (\’width\’/\’height\’). $source_imagestring=\'\'— Optional source filesystem path for size/role offsets.
Return: int — The encode quality to use (1-100).
public is_smart_compress_enabled()
public function is_smart_compress_enabled(): boolWhether the size-compare smart-compress pipeline is enabled.
Return: bool — True when oversized siblings should be discarded.
public should_discard_oversized_sibling()
public function should_discard_oversized_sibling(string $source_path, string $sibling_path): boolWhether a converted sibling should be discarded for exceeding its source. Parameter Type Default Description $source_pathstring— Filesystem path to the source image. $sibling_pathstring— Filesystem path to the converted sibling.
Return: bool — True when the sibling must be discarded.
public discard_oversized_sibling()
public function discard_oversized_sibling(string $source_path, string $sibling_path): boolDiscard a converted sibling that exceeds its source byte size. Parameter Type Default Description $source_pathstring— Filesystem path to the source image. $sibling_pathstring— Filesystem path to the converted sibling.
Return: bool — True when the sibling was discarded.
private record_encoded_sibling()
private function record_encoded_sibling(string $source_image, string $sibling_path, string $type, bool& $success): voidRecord a freshly encoded (or pre-existing) sibling as completed, discarding it first when it exceeds its source byte size. Parameter Type Default Description $source_imagestring— Filesystem path to the source image. $sibling_pathstring— Filesystem path to the converted sibling. $typestring— Conversion type (\’webp\’ or \’avif\’). $successbool&— Conversion success flag, set to false when discarded.
Return: void.
private is_gain_map_image()
private function is_gain_map_image(string $source_image): boolWhether the source embeds an UltraHDR gain map. Parameter Type Default Description $source_imagestring— Filesystem path to the candidate image.
Return: bool — True when an hdrgm XMP marker is present.
public convert_image()
public function convert_image(string $source_image, string=\'webp\' $format, int=-1 $quality): boolConvert a source image into WebP and/or AVIF and record conversion status. Parameter Type Default Description $source_imagestring— Filesystem path to the source image. $formatstring=\'webp\'— One of \’webp\’, \’avif\’, or \’both\’ indicating desired target format(s). $qualityint=-1— Quality for the converted image (0-100). Use -1 to let underlying library choose defaults.
Return: bool — `true` if the conversion(s) for the requested format(s) completed successfully, `false` otherwise.
private convert_palette_to_truecolor()
private function convert_palette_to_truecolor($image)Convert an image palette to true color if it is not already in true color. Parameter Type Default Description $image\\GdImage— The image resource.
Return: \\GdImage — The true color image resource.
private extract_dominant_color()
private function extract_dominant_color($image): stringExtract dominant color from a GD image resource. Parameter Type Default Description $image\\GdImage— The GD image resource.
Return: string — Hex color string (e.g. \’#aabbcc\’).
private generate_lqip()
private function generate_lqip($image): stringGenerate a Low-Quality Image Placeholder (LQIP) from a GD image resource. Parameter Type Default Description $image\\GdImage— The GD image resource.
Return: string — Base64-encoded data URI, or empty string on failure.
private store_placeholder_data()
private function store_placeholder_data(string $rel_path, string $dominant_color, string $lqip): voidStore dominant color and LQIP data for an image atomically via the existing deferred-commit pattern (wppo_img_info). Parameter Type Default Description $rel_pathstring— The relative image path (ABSPATH-stripped). $dominant_colorstring— Hex color string. $lqipstring— LQIP data URI (empty string if not generated).
Return: void.
private store_placeholder_data_batch()
private function store_placeholder_data_batch(array $batch): voidStore placeholder data for multiple rel_paths in one atomic update. Parameter Type Default Description $batcharray— —
Return: void.
publicstatic get_placeholder_info()
public static function get_placeholder_info(): arrayGet placeholder data (dominant_color, lqip) from the shared wppo_img_info option.
Return: array{dominant_color: — array<string, string>, lqip: array<string, string>}.
publicstatic clean_placeholder_on_delete()
public static function clean_placeholder_on_delete(int $post_id): voidClean up placeholder data (dominant_color, lqip) when an attachment is deleted. Parameter Type Default Description $post_idint— The attachment ID.
Return: void.
private is_animated_webp()
private function is_animated_webp($file)Check if a WebP image is animated. Parameter Type Default Description $filestring— Path to the WebP file.
Return: bool — True if the WebP image is animated, false otherwise.
publicstatic get_img_path()
public static function get_img_path(string $source_image, string=\'webp\' $format): stringCompute the filesystem path where a converted image (WebP or AVIF) should be stored. Parameter Type Default Description $source_imagestring— Absolute filesystem path or URL of the source image. $formatstring=\'webp\'— Desired output format; typically \’webp\’ or \’avif\’.
Return: string — Filesystem path where the converted image should be saved, or the original $source_image if a safe local path cannot be determined.
publicstatic get_img_url()
public static function get_img_url(string $source_image, string=\'webp\' $format): stringGet the URL of the converted image. Parameter Type Default Description $source_imagestring— The source image URL. $formatstring=\'webp\'— The desired format (\’webp\’ or \’avif\’).
Return: string — The URL of the converted image.
public convert_image_to_next_gen_format()
public function convert_image_to_next_gen_format($metadata, $attachment_id)Convert uploaded images to WebP or AVIF format upon attachment upload. Parameter Type Default Description $metadataarray— The attachment metadata. $attachment_idint— The attachment ID.
Return: array|\\WP_Error — The modified attachment metadata, or WP_Error on failure.
private is_client_side_media_processing()
private function is_client_side_media_processing(): boolWhether WP 7.1+ client-side media processing is enabled.
Return: bool — True if client-side media processing is enabled.
private maybe_extract_placeholder_for_upload()
private function maybe_extract_placeholder_for_upload(array $metadata, int $attachment_id): voidExtract placeholder data for a new upload when server-side conversion is skipped (WP 7.1+ client-side processing, or WP 6.7+ core-native next-gen generation). Parameter Type Default Description $metadataarray— The attachment metadata. $attachment_idint— The attachment ID.
Return: void.
private store_placeholder_data_for_upload()
private function store_placeholder_data_for_upload(array $metadata, int $attachment_id): voidStore dominant-color and LQIP placeholder data for a new upload when server-side conversion is skipped (WP 7.1+ client-side media processing, or WP 6.7+ core-native next-gen generation). Parameter Type Default Description $metadataarray— The attachment metadata. $attachment_idint— The attachment ID.
Return: void.
public maybe_serve_next_gen_image()
public function maybe_serve_next_gen_image($image)Serve WebP or AVIF images if supported by the browser. Parameter Type Default Description $imagearray— The image source array.
Return: array — Modified image source with WebP/AVIF if applicable, or original image if not.
private should_suppress_re_queueing()
private function should_suppress_re_queueing(): boolWhether re-queueing of missing conversions should be suppressed on the frontend hot path.
Return: bool — True when re-queueing should be suppressed.
public update_conversion_status()
public function update_conversion_status($img_path, =\'completed\' $status, =\'webp\' $type)Update the conversion status of an image. Parameter Type Default Description $img_pathstring— The image path. $status=\'completed\'— The status to update (\’completed\’, \’failed\’, etc.). $type=\'webp\'— The image format type (\’webp\’, \’avif\’).
privatestatic measure_conversion_sizes()
private static function measure_conversion_sizes(string $img_path, string $type): ?arrayMeasure original vs converted byte sizes for a completed conversion. Parameter Type Default Description $img_pathstring— Relative source path (ABSPATH-stripped). $typestring— Conversion type (\’webp\’ or \’avif\’).
Return: array|null — { original: int, converted: int } or null when either file cannot be measured.
publicstatic get_savings_summary()
public static function get_savings_summary(?array=null $img_info): arrayAggregate recorded conversion sizes into a savings summary. Parameter Type Default Description $img_info?array=null— Pre-read img info (null = read here, avoids a second unserialize).
Return: array{original_bytes: — int, converted_bytes: int, saved_bytes: int, images_counted: int}.
publicstatic queue_unconverted_library_images()
public static function queue_unconverted_library_images(array $formats, int=50 $limit): intDiscover library images missing next-gen versions and queue them. Parameter Type Default Description $formatsarray— Conversion formats to ensure (\’webp\’, \’avif\’). $limitint=50— Maximum attachments inspected per window.
Return: int — Number of files newly queued.
publicstatic add_img_into_queue()
public static function add_img_into_queue($img_path, =\'webp\' $type)Add an image to the conversion queue. Parameter Type Default Description $img_pathstring— The image path. $type=\'webp\'— The image format type (\’webp\’, \’avif\’).
publicstatic get_img_info()
public static function get_img_info(): arrayReturns the current image info from the database.
Return: array.
publicstatic set_img_info()
public static function set_img_info(array $img_info): voidManually updates the image info database option. Parameter Type Default Description $img_infoarray— The new image info array.
Return: void.
publicstatic clear_completed_formats()
public static function clear_completed_formats(): voidAtomically clears completed webp and avif entries from the image info option.
Return: void.
privatestatic update_img_info_atomic()
private static function update_img_info_atomic(callable $callback): voidPerforms an atomic-like merge-aware update of the image info option. Parameter Type Default Description $callbackcallable— The callback that receives the current info and returns the updated info.
Return: void.
publicstatic commit_img_info()
public static function commit_img_info(): voidCommits deferred image info state to the database on shutdown.
Return: void.
publicstatic invalidate_img_info_cache()
public static function invalidate_img_info_cache(): voidInvalidate the image info cache by bumping the salt.
Return: void.
publicstatic migrate_img_info_autoload()
public static function migrate_img_info_autoload(): voidForces the \’wppo_img_info\’ option to be non-autoloading.
Return: void.
Hooks
Hooks referenced in includes/Images/class-img-converter.php: Hook Type Line Notes wppo_skip_small_threshold_bytesfilter 685 @param ×1 wppo_max_longest_edge_pxfilter 748 @param ×1 wppo_max_source_pixelsfilter 785 @param ×1 wppo_memory_safe_edge_pxfilter 1315 @param ×4 wppo_smart_qualityfilter 1499 @param ×1 wppo_smart_quality_valuefilter 1548 @param ×4 wppo_smart_pipeline_enabledfilter 1603 @param ×1 wppo_discard_oversized_siblingfilter 1653 @param ×3 wppo_convert_gain_map_imagesfilter 1819 — wppo_filesize_limit_bytesfilter 1885 — wppo_max_dimensionsfilter 1961 — wppo_filesize_limit_bytesfilter 3289 — wppo_max_dimensionsfilter 3346 — wppo_placeholder_string_fallback_max_bytesfilter 3397 — wppo_convertible_image_extensionsfilter 3766 — wppo_convertible_image_extensionsfilter 3828 @param ×1