Richard
Richard

Reputation: 183

how to preserve transparency when scaling PNG with ffmpeg

I am using ffmpeg to scale my PNG images, and I find the transparency turns to white after scaling. How can I preserve the transparency? Thanks

ffmpeg -i background_image.png -vf scale=1080:1920 output.png
ffmpeg version 4.3.1-static https://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 8 (Debian 8.3.0-6)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gmp --enable-libgme --enable-gray --enable-libaom --enable-libfribidi --enable-libass --enable-libvmaf --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libdav1d --enable-libxvid --enable-libzvbi --enable-libzimg
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
  libpostproc    55.  7.100 / 55.  7.100
Input #0, png_pipe, from 'background_image.png':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: png, pal8(pc), 1440x2560, 25 tbr, 25 tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (png (native) -> png (native))
Press [q] to stop, [?] for help
Output #0, image2, to 'output.png':
  Metadata:
    encoder         : Lavf58.45.100
    Stream #0:0: Video: png, pal8, 1080x1920, q=2-31, 200 kb/s, 25 fps, 25 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.91.100 png
frame=    1 fps=0.0 q=-0.0 Lsize=N/A time=00:00:00.04 bitrate=N/A speed=0.113x    
video:669kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown

My Sample PNG file

I don't know why my PNG file with transparency is converted to a jpg format with white after uploading to stackoverflow.

Upvotes: 2

Views: 4508

Answers (1)

Hernán Alarcón
Hernán Alarcón

Reputation: 4109

Use rgba as pixel format (-pix_fmt). In your command it would be:

ffmpeg -i background_image.png -pix_fmt rgba -vf scale=1080:1920 output.png

This ticket mentions a similar problem, so I tried with the sample image of that ticket, which is also a pal8 PNG as yours, and got these results:

Without -pix_fmt rgba the output file has a white background:

ffmpeg -i pal8_alpha.png -vf scale=1080:1920 output.png

With -pix_fmt rgba the background is transparent:

ffmpeg -i pal8_alpha.png -pix_fmt rgba -vf scale=1080:1920 output.png

Upvotes: 7

Related Questions