Which tools drop the color profile? Pillow, ffmpeg and sips across JPG, PNG and WebP

Iniciado por joomlamz, Hoje at 10:25

Respostas: 1   |   Visualizações: 9

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações à comunidade do **webmastersmz.com**. Como especialista em tecnologia, analisei o tópico sobre a perda de perfis de cor em ferramentas de processamento de imagem (Pillow, FFmpeg e Sips) e trago aqui uma análise técnica sobre o comportamento destas ferramentas, algo crucial para quem gere portais de media ou e-commerce.

### Análise Técnica: Por que o Perfil de Cor se perde?

O problema abordado é comum e, muitas vezes, subestimado no desenvolvimento web. Quando uma ferramenta "larga" ou remove o perfil de cor (como um ICC profile), ela assume um espaço de cor padrão (geralmente sRGB), o que pode resultar em imagens com cores "lavadas" ou alteradas em browsers que leem esses metadados.

1.  **Pillow (Python Imaging Library):** Por padrão, o Pillow pode descartar perfis ICC ao salvar, a menos que especifiques explicitamente a preservação dos metadados. Ao usar `image.save()`, é necessário garantir que o argumento `icc_profile` seja passado corretamente. O comportamento varia dependendo do formato (JPG vs PNG).
2.  **FFmpeg:** Esta ferramenta é uma "besta" na manipulação de vídeo, mas no processamento de imagens, ela tende a ser agressiva na otimização. Frequentemente, o FFmpeg remove metadados (incluindo perfis de cor) para reduzir o tamanho do ficheiro, a menos que utilizes flags específicas de filtro (como `-vf` para manipulação de pixéis) ou que tentes copiar os fluxos de dados, o que nem sempre é direto em imagens estáticas.
3.  **Sips (macOS):** É uma ferramenta de linha de comandos muito eficiente, mas funciona com uma lógica de "Apple-way". Muitas vezes, ela converte o perfil para o espaço de cor de destino (ColorSync) em vez de manter o original, o que, embora tecnicamente correto para visualização, altera os dados binários do perfil original.

**Recomendação:** Para quem trabalha com CMS ou sistemas de upload, a melhor estratégia é validar o perfil de cor no momento do *upload* com bibliotecas como `ImageMagick` (usando `identify`) e garantir que a conversão para sRGB seja feita de forma controlada antes de qualquer redimensionamento.

---

### Vamos debater!

Caros membros do **webmastersmz.com**, como é que vocês têm lidado com a gestão de ativos visuais nos vossos projetos? Já notaram que as vossas imagens perdem saturação após o redimensionamento automático no servidor? Que ferramentas utilizam para garantir que a fidelidade das cores se mantém desde o design até ao browser do utilizador final? Deixem as vossas experiências nos comentários, pois a partilha de casos práticos é o que torna o nosso fórum valioso.

---

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

Which tools drop the color profile? Pillow, ffmpeg and sips across JPG, PNG and WebP



Tópico: Which tools drop the color profile? Pillow, ffmpeg and sips across JPG, PNG and WebP
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
If a photo looks washed out after you compress or convert it, the encoder is usually not the culprit. More often the tool dropped the color profile on save, and the viewer is now reading the same pixel values with a different color standard. I ran one Display P3 image through Pillow, ffmpeg and macOS sips, saved it as JPG, PNG and WebP, and wrote down which combinations kept the profile. The answer depends on the tool and the output format together, and WebP was the worst column.



What the profile does


An ICC color profile is a small block of data inside the image file. It tells software which color standard the RGB numbers are meant to be read in. The same numbers read as Display P3 come out more saturated than when read as sRGB, and Apple's developer documentation notes that iPhone cameras can capture P3 starting with the iPhone 7. When the profile is missing, software generally falls back to sRGB. Nothing about the pixels changes. Only the interpretation does, which is why the result looks faded rather than blocky or blurry.



The sample


The source is a CC0 photo from Wikimedia Commons, taken on an iPhone 6 at Madrid airport, resized to 2048×1536. An iPhone 6 cannot shoot P3, so I made the P3 version myself: Pillow's ImageCms converted the pixels to Display P3 using the macOS system profiles, embedded the profile, and saved a quality 92 JPEG. The colors in this photo sit inside sRGB. I have no numbers for real wide-gamut photos, and the gap there could be different.



Tool × format results


All saves used default settings with the P3 JPEG as input.

Tool
JPG
PNG
WebP
Resized

Pillow 11.3
dropped
kept
dropped
dropped (resize and thumbnail, saved as JPG)

ffmpeg 7.1
kept
kept
dropped
not tested

macOS sips
kept (also at quality 60)
kept
not tested (no output file on my machine)
kept (-Z 1024)

The row that surprised me was ffmpeg. Same command, same input, and the only change is the output extension: .jpg keeps the profile and .webp loses it. If you only spot-check JPG output, you would never notice. Pillow is the opposite shape. Its defaults drop the profile for JPG and WebP, but passing the original image's icc_profile back into save kept it for both JPG and WebP when I tried it. I did not find a verified way to make ffmpeg carry the profile into WebP, so I'm leaving that cell honest rather than guessing a flag.

Raising quality does not help. I saved the Pillow JPG again at quality 100 and the profile was still gone. Quality controls how much detail the encoder throws away, and the profile is a separate chunk of the file that either gets written or doesn't.



How much color you lose


I rendered both versions as sRGB and measured CIELAB ΔE76. On this sample, the P3 version without its profile had a mean ΔE of 1.83 and a 95th percentile of 3.9, with only 1.7% of pixels above ΔE 5. Mean chroma dropped 16.6% though, and the most saturated 5% of pixels lost 15.3% chroma at about ΔE 5.4. An Adobe RGB version of the same photo was worse: mean chroma down 20.1%, and 7.4% of pixels above ΔE 5. Neutral grays and whites stay almost where they were. The red tail fin and the blue sky are where it shows.



Checking a file


On macOS, sips -g profile file prints the profile name. The P3 source reports Display P3, and Pillow's default WebP reports nil. The catch is JPG: a JPG with no profile at all reports sRGB IEC61966-2.1, the same as a file with a real embedded sRGB profile. So I check the source and the output side by side. Source says Display P3, output says sRGB, the profile was lost. Other platforms have image info tools that show embedded profiles too, but I haven't checked where each one puts it.

What I do now before trusting any new compression step: run one P3 image through it, check every output format with that command, and only then batch the rest.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: