Choose a WebP CLI or library by task
| Task | Suitable starting point | Check before use |
|---|---|---|
| JPG/PNG to WebP | libwebp cwebp | Static input; choose lossy or lossless deliberately. |
| Static WebP to PNG | libwebp dwebp | No JPEG output or animated WebP decoding. |
| WebP to JPG | ImageMagick or an image library | Select a frame and composite alpha onto an opaque background. |
| Animated conversion | An animation-aware library | Read all frames, durations and loops; verify the destination limitations. |
WebP CLI encoding: PNG or JPG to WebP
Install the official libwebp tools for your platform and record their actual version. cwebp accepts supported static PNG and JPEG input. These examples preserve separate output names and choose a lossy photo or lossless graphic path:
cwebp -version
cwebp -q 80 -m 4 input.jpg -o photo.webp
cwebp -lossless -m 4 input.png -o graphic.webpQuality and encoding effort are different controls. The method setting trades processing effort against compression; a quality value of 100 in a lossy mode is not the lossless switch. cwebp does not accept animated PNG or animated WebP as an animation conversion workflow.
WebP CLI decoding: PNG and JPEG require different writers
dwebp writes PNG or PPM-family outputs from supported static WebP. It does not write JPEG. Use a JPEG-capable application such as ImageMagick 7 for that destination:
dwebp -version
dwebp input.webp -o output.png
magick -version
magick "input.webp[0]" -background white -alpha remove -alpha off output.jpgThe JPEG command explicitly reads frame zero and composites alpha over white. For a non-programming JPEG task, convert WebP to JPG. For a PNG result, convert WebP to PNG.
Python: encode PNG/JPG and decode a still frame
For scripts that would otherwise invoke a WebP CLI, Pillow offers direct image operations. Check the installed WebP feature and version; Pillow’s format documentation defines the encoder options. This example selects frame zero and makes the JPEG background explicit. Metadata copying is not implemented here.
from PIL import Image, features
if not features.check("webp"):
raise RuntimeError("This Pillow build has no WebP support")
print("libwebp:", features.version("webp"))
with Image.open("input.png") as source:
source.seek(0)
source.convert("RGBA").save("from-png.webp", lossless=True, method=4)
with Image.open("input.jpg") as source:
source.convert("RGB").save("from-jpg.webp", quality=80, method=4)
with Image.open("input.webp") as source:
source.seek(0)
rgba = source.convert("RGBA")
rgba.save("output.png")
opaque = Image.new("RGB", rgba.size, "white")
opaque.paste(rgba, mask=rgba.getchannel("A"))
opaque.save("output.jpg", quality=90)Python: carry a WebP timeline into GIF
This animated example deliberately flattens every frame onto white and reduces it to a GIF palette. It requires positive source durations and maps finite WebP playback counts to GIF repeat counts. Read each duration after loading its frame. GIF timing quantization and palette conversion can change the result; inspect a full loop.
from PIL import Image, ImageSequence
frames, durations = [], []
with Image.open("animation.webp") as source:
if source.format != "WEBP" or not getattr(source, "is_animated", False):
raise ValueError("Expected an animated WebP source")
webp_loops = int(source.info.get("loop", 0))
# GIF repeats after the first play; omitting loop means play once.
gif_loop = {} if webp_loops == 1 else {"loop": 0 if webp_loops == 0 else webp_loops - 1}
for frame in ImageSequence.Iterator(source):
frame.load()
duration = frame.info.get("duration")
if duration is None or duration <= 0:
raise ValueError("Define a timing policy for missing or zero delays")
rgba = frame.convert("RGBA")
opaque = Image.new("RGB", rgba.size, "white")
opaque.paste(rgba, mask=rgba.getchannel("A"))
frames.append(opaque.convert("P", palette=Image.Palette.ADAPTIVE, colors=256))
durations.append(duration)
frames[0].save("output.gif", save_all=True, append_images=frames[1:],
duration=durations, disposal=2, optimize=False, **gif_loop)A finite loop value is not interchangeable between the containers. libwebp’s GIF conversion source adjusts GIF’s repeat count when writing WebP. The example applies the reverse mapping: one WebP play omits the GIF loop extension, zero stays infinite, and larger values become one fewer GIF repeat.
This holds decoded frames in memory, so use bounded inputs. For the browser direction and its limits, see WebP to GIF. A still PNG or JPG output cannot carry this timeline.
Java: use a WebP reader, then a JPEG writer
Add and pin the WebP reader module from TwelveMonkeys ImageIO with its documented dependencies. Its format matrix lists WebP reading, not WebP writing. With the reader on the classpath, this first-image example checks decode failure and paints an opaque JPEG background:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class WebpToJpeg {
public static void main(String[] args) throws IOException {
BufferedImage input = ImageIO.read(new File("input.webp"));
if (input == null) throw new IOException("No reader decoded the source");
BufferedImage rgb = new BufferedImage(input.getWidth(), input.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = rgb.createGraphics();
try {
g.setColor(Color.WHITE);
g.fillRect(0, 0, rgb.getWidth(), rgb.getHeight());
g.drawImage(input, 0, 0, null);
} finally { g.dispose(); }
if (!ImageIO.write(rgb, "JPEG", new File("output.jpg"))) {
throw new IOException("No JPEG writer is available");
}
}
}C#: read WebP and write PNG or an opaque JPEG
ImageSharp loading options include a frame limit, and its format documentation covers WebP, PNG and JPEG. Add the package version appropriate to your project. The example keeps alpha in PNG and explicitly composites it over white for JPEG:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using Image<Rgba32> source = Image.Load<Rgba32>(
new DecoderOptions { MaxFrames = 1 }, "input.webp");
source.Save("output.png", new PngEncoder());
using var opaque = new Image<Rgb24>(source.Width, source.Height);
for (int y = 0; y < source.Height; y++) {
for (int x = 0; x < source.Width; x++) {
Rgba32 p = source[x, y];
byte OverWhite(byte channel) =>
(byte)((channel * p.A + 255 * (255 - p.A) + 127) / 255);
opaque[x, y] = new Rgb24(OverWhite(p.R), OverWhite(p.G), OverWhite(p.B));
}
}
opaque.Save("output.jpg", new JpegEncoder { Quality = 90 });Loading or saving can fail; handle the library’s exceptions in the calling application. This is a first-frame example, not an animation export or a color-management pipeline.
PHP/GD: check capability, then actually decode
gd_info reports build capabilities. getimagesize reports dimensions and type but is not image validation. GD’s WebP decoder does not accept animated WebP. The following PHP 8+ static paths check decode and write failures:
<?php
if (!extension_loaded("gd") || !(gd_info()["WebP Support"] ?? false)) {
throw new RuntimeException("GD WebP support is unavailable");
}
$info = getimagesize("input.webp"); // Inspection only, not validation.
$source = imagecreatefromwebp("input.webp");
if ($source === false) throw new RuntimeException("WebP decode failed");
imagealphablending($source, false);
imagesavealpha($source, true);
if (!imagepng($source, "output.png")) throw new RuntimeException("PNG write failed");
$jpg = imagecreatetruecolor(imagesx($source), imagesy($source));
imagefill($jpg, 0, 0, imagecolorallocate($jpg, 255, 255, 255));
imagealphablending($jpg, true);
imagecopy($jpg, $source, 0, 0, 0, 0, imagesx($source), imagesy($source));
if (!imagejpeg($jpg, "output.jpg", 90)) throw new RuntimeException("JPEG write failed");
foreach (["input.png" => "from-png.webp", "input.jpg" => "from-jpg.webp"] as $in => $out) {
$image = str_ends_with($in, ".png") ? imagecreatefrompng($in) : imagecreatefromjpeg($in);
if ($image === false) throw new RuntimeException("Source decode failed");
imagepalettetotruecolor($image);
imagealphablending($image, false);
imagesavealpha($image, true);
if (!imagewebp($image, $out, 80)) throw new RuntimeException("WebP write failed");
$check = imagecreatefromwebp($out);
if ($check === false) throw new RuntimeException("Written WebP is invalid");
imagedestroy($check);
imagedestroy($image);
}
imagedestroy($jpg);
imagedestroy($source);The PNG/JPEG source choices above are explicit local examples, not an upload detector. PHP documents an imagewebp return-value caveat, so reopen the output rather than trusting a boolean alone. Check JPEG and PNG support in your GD build too.
JavaScript: browser, Node.js and WASM are separate environments
For a known static PNG or JPEG File in a browser, draw decoded pixels to canvas and request WebP. toBlob can fall back to PNG; reject an unexpected type rather than attaching a misleading extension:
async function staticFileToWebp(file) {
const bitmap = await createImageBitmap(file);
const canvas = document.createElement("canvas");
canvas.width = bitmap.width;
canvas.height = bitmap.height;
try {
const context = canvas.getContext("2d");
if (!context) throw new Error("A 2D canvas context is unavailable");
context.drawImage(bitmap, 0, 0);
} finally {
bitmap.close();
}
return await new Promise((resolve, reject) => {
canvas.toBlob(blob => {
if (!blob || blob.type !== "image/webp") {
reject(new Error("WebP encoding is unavailable or failed"));
} else resolve(blob);
}, "image/webp", 0.85);
});
}In Node.js, install and pin sharp rather than assuming browser canvas APIs exist. Its constructor defaults to one page; the examples below explicitly keep that static scope:
import sharp from "sharp";
await sharp("input.png", { pages: 1 })
.webp({ lossless: true, effort: 4 }).toFile("from-png.webp");
await sharp("input.jpg", { pages: 1 })
.webp({ quality: 80, effort: 4 }).toFile("from-jpg.webp");A WASM codec supplies its own asset loading, memory and API contract. It is not automatically the same interface as canvas, sharp or a WebP CLI. Morphio’s internal components are not a public SDK. For embedding and delivery, continue to WebP on websites.
Check read and write capabilities before choosing a binding
Go’s x/image/webp package provides decoding and DecodeConfig, not a WebP encoder. Rust image’s WebPEncoder documents lossless encoding; do not infer a lossy mode from the class name.
For C or C++, libwebp’s official API separates decoding, encoding and memory ownership. Buffers allocated by its simple decoding functions must be released with WebPFree. Check pixel layout and the API’s return status.
For Delphi, confirm the registered codecs and separate read/write capabilities of the exact framework or third-party component in your build. A decoder registered for image loading does not by itself provide a WebP writer.
UIImage: check the actual platform decoding path
Safari support does not prove every UIImage initializer handles the same data. ImageIO can report its supported source type identifiers. Check the target OS and selected decoding API, then attempt a real decode and handle failure. Image display, animation and export require separate confirmation.
Record versions and resolve library loading failures
A WebP CLI executable, a dynamic library and an image file are different artifacts. Obtain binaries from the relevant project, match architecture and runtime dependencies, and record resolved versions. A missing-library error calls for dependency diagnosis, not renaming a random DLL.
Use WebP file safety guidance when checking source and library provenance. No replacement DLL download or plugin bundle is supplied by this guide.
Verify a WebP CLI or library result
Reopen the output with an independent reader where practical. Confirm actual format, dimensions, frame count, alpha behavior and animation duration. Keep stderr, exceptions or per-file errors instead of treating the presence of a filename as success.
Use appropriately licensed WebP test files to cover static, transparent and animated cases. Record your own dependency versions and observed results; a code example is not evidence of testing on your deployment.
Questions and answers
Practical answers for this task.
Use a command when a repeatable local process and exit status fit the workflow. Use a library when the application needs direct pixels, structured errors or controlled animation handling.
No. A reader can decode WebP without offering a WebP writer. Check both sides of the actual task.
No. Effort controls how much work the encoder spends searching for a result. Quality and lossless mode have separate meanings and differ between APIs.
No blanket metadata-preservation claim is made. The examples focus on pixels and stated frame behavior; add and verify a deliberate metadata policy for your application.