Instantiating an image files, and attempting to save them in PNG format using setImageFormat('PNG'), I occasionally encountered
"gd-png: libpng warning: iCCP: profile 'icc': 'CMYK': invalid ICC profile color space".
However, transformimagecolorspace( \Imagick::COLORSPACE_SRGB ) had not effect, because getImageColorspace() did not indicate COLORSPACE_CMYK.
Instead, one has to check for the presence of any ICC profile, inspect the ICC profile header (offset 16) for the "CMYK" color space tag, and then remove the ICC profile:
$ICC_count = remove_ICC( $image, 'CMYK');
function remove_ICC( \Imagick $image, ?string $colorspace ): int
{
$icc_count = 0;
foreach ( $image->getImageProfiles( 'icc' ) as $name => $profile ) {
if ( empty( $colorspace ) or 0 === strcasecmp( $colorspace, substr( $profile, 16, 4 ) ) )
// Either consider all ICC profiles, or just those matching the color space.
$icc_count++;
}
if ( $icc_count > 0 )
$image->profileImage( 'icc', null ); // Delete any ICC profiles.
return $icc_count;
}