将 jpg、png、gif 图片转换成webp图片

webp github 库https://github.com/search?l=PHP&q=webp&type=Repositories  (php)

确定你的服务器上安装了 libpng、libjpeg 等图片支持包。

 

webp 官网https://developers.google.com/speed/webp

webp 下载https://storage.googleapis.com/downloads.webmproject.org/releases/webp/index.html

Precompiled WebP utilities and library for Linux, Windows and Mac OS X.

They include:

0)Installation instructions

OS X Package Managers

Additionally, the WebP tools are often available for Mac OS X via Homebrew and MacPorts.

 

1)Download for Windows 

$ ll  libwebp-1.0.3-windows-x86/bin/
-rw-r--r--@ 1 homer  staff  573952 Jan  4 21:32 anim_diff.exe
-rw-r--r--@ 1 homer  staff  668672 Jan  4 21:32 anim_dump.exe
-rw-r--r--@ 1 homer  staff  590336 Jan  4 21:32 cwebp.exe
-rw-r--r--@ 1 homer  staff  410112 Jan  4 21:32 dwebp.exe
-rw-r--r--@ 1 homer  staff  218624 Jan  4 21:32 freeglut.dll
-rw-r--r--@ 1 homer  staff  583680 Jan  4 21:32 get_disto.exe
-rw-r--r--@ 1 homer  staff  594432 Jan  4 21:32 gif2webp.exe
-rw-r--r--@ 1 homer  staff  603648 Jan  4 21:32 img2webp.exe
-rw-r--r--@ 1 homer  staff  403456 Jan  4 21:32 vwebp.exe
-rw-r--r--@ 1 homer  staff  210944 Jan  4 21:32 webp_quality.exe
-rw-r--r--@ 1 homer  staff  271360 Jan  4 21:32 webpinfo.exe
-rw-r--r--@ 1 homer  staff  174592 Jan  4 21:32 webpmux.exe

 

2)Download for Linux 

$ ll  ../libwebp-1.0.3-linux-x86-64/bin/
-rwxr-xr-x@ 1 homer  staff   694936 Jul  5  2019 anim_diff
-rwxr-xr-x@ 1 homer  staff   961240 Jul  5  2019 anim_dump
-rwxr-xr-x@ 1 homer  staff  2463984 Jul  5  2019 cwebp
-rwxr-xr-x@ 1 homer  staff   953048 Jul  5  2019 dwebp
-rwxr-xr-x@ 1 homer  staff  2443440 Jul  5  2019 get_disto
-rwxr-xr-x@ 1 homer  staff   719560 Jul  5  2019 gif2webp
-rwxr-xr-x@ 1 homer  staff  2472144 Jul  5  2019 img2webp
-rwxr-xr-x@ 1 homer  staff   702272 Jul  5  2019 vwebp
-rwxr-xr-x@ 1 homer  staff   358936 Jul  5  2019 webp_quality
-rwxr-xr-x@ 1 homer  staff   371224 Jul  5  2019 webpinfo
-rwxr-xr-x@ 1 homer  staff   387656 Jul  5  2019 webpmux

 

3)Download for Mac OS X

$ ll  ../libwebp-1.0.3-mac-10.14/bin/   
-rwxr-xr-x@ 1 homer  staff   621376 Jul  5  2019 anim_diff
-rwxr-xr-x@ 1 homer  staff   810996 Jul  5  2019 anim_dump
-rwxr-xr-x@ 1 homer  staff  2048336 Jul  5  2019 cwebp
-rwxr-xr-x@ 1 homer  staff   801964 Jul  5  2019 dwebp
-rwxr-xr-x@ 1 homer  staff  2031384 Jul  5  2019 get_disto
-rwxr-xr-x@ 1 homer  staff   642456 Jul  5  2019 gif2webp
-rwxr-xr-x@ 1 homer  staff  2061752 Jul  5  2019 img2webp
-rwxr-xr-x@ 1 homer  staff   351612 Jul  5  2019 vwebp
-rwxr-xr-x@ 1 homer  staff   298344 Jul  5  2019 webp_quality
-rwxr-xr-x@ 1 homer  staff   318920 Jul  5  2019 webpinfo
-rwxr-xr-x@ 1 homer  staff   328512 Jul  5  2019 webpmux

 

The libwebp library, which can be used to add WebP encoding or decoding to your programs.

cwebp -- WebP encoder tool

dwebp -- WebP decoder tool

vwebp -- WebP file viewer

webpmux -- WebP muxing tool

gif2webp -- Tool for converting GIF images to WebP

Precompiled WebP framework for iOS. Build details are contained in the README in the archive.

Download

Source code of WebP library and utilities. If the precompiled binaries don't suit your needs, you can compile them yourself.

Installation instructions | Download | Latest source code

 

Download for Mac OS X 解压配置的详细步骤(macos)

1、解压

tar zxvf libwebp-1.0.3-mac-10.14.tar.gz
cd libwebp-1.0.3-mac-10.14

$ ll  ../libwebp-1.0.3-mac-10.14/bin/   
-rwxr-xr-x@ 1 homer  staff   621376 Jul  5  2019 anim_diff
-rwxr-xr-x@ 1 homer  staff   810996 Jul  5  2019 anim_dump
-rwxr-xr-x@ 1 homer  staff  2048336 Jul  5  2019 cwebp
-rwxr-xr-x@ 1 homer  staff   801964 Jul  5  2019 dwebp
-rwxr-xr-x@ 1 homer  staff  2031384 Jul  5  2019 get_disto
-rwxr-xr-x@ 1 homer  staff   642456 Jul  5  2019 gif2webp
-rwxr-xr-x@ 1 homer  staff  2061752 Jul  5  2019 img2webp
-rwxr-xr-x@ 1 homer  staff   351612 Jul  5  2019 vwebp
-rwxr-xr-x@ 1 homer  staff   298344 Jul  5  2019 webp_quality
-rwxr-xr-x@ 1 homer  staff   318920 Jul  5  2019 webpinfo
-rwxr-xr-x@ 1 homer  staff   328512 Jul  5  2019 webpmux

 

2、配置

sudo cp -r libwebp-1.0.3-mac-10.14 /opt/
sudo chown -R homer:staff /opt/libwebp-1.0.3-mac-10.14/

 

3、添加环境变量

sudo vim /etc/profile

在末尾,添加一行:

export PATH=/opt/libwebp-1.0.3-mac-10.14/bin:$PATH

使其生效

source /etc/profile

 

4、不明来源授权

执行 gif2webp -h 时,可能需要苹果不明来源软件授权,根据提示授权即可

$ which gif2webp
/opt/libwebp-1.0.3-mac-10.14/bin/gif2webp
$ gif2webp -h
Usage:
 gif2webp [options] gif_file -o webp_file
Options:
  -h / -help ............. this help
  -lossy ................. encode image using lossy compression
  -mixed ................. for each frame in the image, pick lossy
                           or lossless compression heuristically
  -q <float> ............. quality factor (0:small..100:big)
  -m <int> ............... compression method (0=fast, 6=slowest)
  -min_size .............. minimize output size (default:off)
                           lossless compression by default; can be
                           combined with -q, -m, -lossy or -mixed
                           options
  -kmin <int> ............ min distance between key frames
  -kmax <int> ............ max distance between key frames
  -f <int> ............... filter strength (0=off..100)
  -metadata <string> ..... comma separated list of metadata to
                           copy from the input to the output if present
                           Valid values: all, none, icc, xmp (default)
  -loop_compatibility .... use compatibility mode for Chrome
                           version prior to M62 (inclusive)
  -mt .................... use multi-threading if available

  -version ............... print version number and exit
  -v ..................... verbose
  -quiet ................. don't print anything

 

 

webp  格式图片支持的浏览器

注:蓝色表示支持,红色表示不支持,Apple Safari 浏览器都不支持 webp,打不开

 

在线图片转换工具:https://cloudconvert.com/jpeg-to-webp

isparta:http://isparta.github.io (软件,支持 Windows、MacOS、Linux)

converter:https://www.office-converter.com/JPEG-to-JPG

ezgif.com:https://ezgif.com/webp-to-gif

sojson:https://www.sojson.com/image/format.html

智图:https://zhitu.isux.us (推荐,在线和软件转化,腾讯ISUX前端团队开发)

朝夕网:https://pic.zhaoxi.net  

做好图:http://www.zuohaotu.com/image-converter.aspx (不支持 webp格式)

我拉网:http://pic.55.la  (不支持 webp格式)

改图宝:https://www.gaitubao.com/jpg-gif-png  (不支持格式转换)

Chrome 插件:Save image as Type ,WebP Highlighter

 

 

1、安装 libwebp 库

1)CentOS 安装

yum -y install libwebp-devel libwebp-tools

2)Ubuntu 安装

sudo apt-get install webp

3)MacOS 安装

brew install webp

 

安装完毕后,系统会多几条命令,查看如下:

# ll /bin/*web*
-rwxr-xr-x 1 root root 44320 Aug  2  2017 /bin/cwebp
-rwxr-xr-x 1 root root 19504 Aug  2  2017 /bin/dwebp
-rwxr-xr-x 1 root root 19504 Aug  2  2017 /bin/gif2webp
-rwxr-xr-x 1 root root 27784 Aug  2  2017 /bin/webpmux

 

macOS 默认 brew install webp 安装后,并不包含 gif2webp

$ ll /usr/local/bin/*webp*
-rwxr-xr-x  1 homer  staff  69436  1  4 21:38 /usr/local/bin/cwebp
-rwxr-xr-x  1 homer  staff  37568  1  4 21:38 /usr/local/bin/dwebp
lrwxr-xr-x  1 homer  staff     33  9  3 00:26 /usr/local/bin/img2webp -> ../Cellar/webp/1.0.3/bin/img2webp
lrwxr-xr-x  1 homer  staff     33  9  3 00:26 /usr/local/bin/webpinfo -> ../Cellar/webp/1.0.3/bin/webpinfo
lrwxr-xr-x  1 homer  staff     32  9  3 00:26 /usr/local/bin/webpmux -> ../Cellar/webp/1.0.3/bin/webpmux

解决办法:macOS系统下,手动下载,配置环境,并授权,详见本文上面的 Download for Mac OS X 解压配置的详细步骤(macos)

 

 

webp默认图片质量是80,如果需要修改,可以使用vim、Gedit等编辑器打开webp文件,找到:

QUALITY=80

修改为你需要数值即可。

另外,GIMP图像处理软件如果需要支持保存为WebP格式,需要安装一个插件,相应的命令如下:

apt-add-repository ppa:george-edison55/webp
apt-get update
apt-get install gimp-webp

 

 

2、webp 格式转换

1)将 png、jpg/jpeg、gif 图片转换成 webp

查看 webp -h 帮助命令:

# cwebp -h
Usage:

   cwebp [options] -q quality input.png -o output.webp

where quality is between 0 (poor) to 100 (very good).
Typical value is around 80.

实例:

png 转成 webp:cwebp -q 80 01.png -o 01.webp

png 图片:

转换成的webp图片:

 

jpg/jpeg 转成 webp:cwebp -q 80 02.jpg -o 02.webp

jpeg 图片,如下图:

转换成的 webp 图片,如下图:

 

gif2webp -h 命令帮助:

# gif2webp -h
Usage:
 gif2webp [options] gif_file -o webp_file
options:
  -h / -help  ............ this help
  -lossy ................. Encode image using lossy compression.
  -q <float> ............. quality factor (0:small..100:big)
  -m <int> ............... compression method (0=fast, 6=slowest)
  -f <int> ............... filter strength (0=off..100)

  -version ............... print version number and exit.
  -v ..................... verbose.
  -quiet ................. don't print anything.

gif 转成 webp:gif2webp -q 80 03.gif -o 03.webp   // 转换耗时比较长

gif 图片:

转换成的 webp 图片:

 

2)将 webp 图片转换成 png、jpg/jpeg、gif

dwebp命令可以将WebP文件解压成一个图像文件,类型可以是JPG,PNG,PAM,PPM,PGM等等。

dwebp -h 命令帮助:

# dwebp -h
Usage: dwebp in_file [options] [-o out_file]

Decodes the WebP image file to PNG format [Default]
Use following options to convert into alternate image formats:
  -pam ......... save the raw RGBA samples as a color PAM
  -ppm ......... save the raw RGB samples as a color PPM
  -pgm ......... save the raw YUV samples as a grayscale PGM
                 file with IMC4 layout.
  -yuv ......... save the raw YUV samples in flat layout.

 Other options are:
  -version  .... print version number and exit.
  -nofancy ..... don't use the fancy YUV420 upscaler.
  -nofilter .... disable in-loop filtering.
  -mt .......... use multi-threading
  -crop <x> <y> <w> <h> ... crop output with the given rectangle
  -scale <w> <h> .......... scale the output (*after* any cropping)
  -alpha ....... only save the alpha plane.
  -h     ....... this help message.
  -v     ....... verbose (e.g. print encoding/decoding times)
  -noasm ....... disable all assembly optimizations.

 

webp 转成  png:dwebp 05.webp -o 05.png    (webp静态图)

webp 转成  jpg:dwebp 05.webp -o 05.jpg     (webp静态图)

webp 转成  jpeg:dwebp 05.webp -o 05.jpeg (webp静态图)

webp 静态图片,webp图片格式,如下图:

转换成的 png 图片:

转换成的 jpg 图片:

转换成的 jpeg 图片:

 

webp 转成  gif:dwebp 05.webp -o 05.gif (webp动态图)

webpmux 从静态的webp images创建动态的webp,或者从动态的webp提取静态的webp images。以及管理XMP/EXIF数据和ICC描述文件。

webpmux 官网:https://developers.google.cn/speed/webp/docs/webpmux

webpmux -h 使用帮助:

# webpmux -h
Usage: webpmux -get GET_OPTIONS INPUT -o OUTPUT
       webpmux -set SET_OPTIONS INPUT -o OUTPUT
       webpmux -strip STRIP_OPTIONS INPUT -o OUTPUT
       webpmux -frame FRAME_OPTIONS [-frame...] [-loop LOOP_COUNT]
               [-bgcolor BACKGROUND_COLOR] -o OUTPUT
       webpmux -info INPUT
       webpmux [-h|-help]
       webpmux -version

GET_OPTIONS:
 Extract relevant data.
   icc       Get ICC profile.
   exif      Get EXIF metadata.
   xmp       Get XMP metadata.
   frame n   Get nth frame.

SET_OPTIONS:
 Set color profile/metadata.
   icc  file.icc     Set ICC profile.
   exif file.exif    Set EXIF metadata.
   xmp  file.xmp     Set XMP metadata.
   where:    'file.icc' contains the ICC profile to be set,
             'file.exif' contains the EXIF metadata to be set
             'file.xmp' contains the XMP metadata to be set

STRIP_OPTIONS:
 Strip color profile/metadata.
   icc       Strip ICC profile.
   exif      Strip EXIF metadata.
   xmp       Strip XMP metadata.

webp 动态图片:

转换成的 gif 图片:暂时没找到方法,可在第三方网站进行,例如 WebP to animated GIF converter

 

最后,对比一下以上转换前后的文件大小:webp 理论上要远远小于 png、jpg/jpeg、gif 图片

 

PhotoShop 高度压缩图片技巧

通常在PhotoShop里保存图片的时候,会选择“存储为”,然后通过调整图片质量来达到压缩图片的目的,但是这样的压缩效果并不理想

比如在某些平台实名认证时,身份证扫描图片上传限制几十K大小,压缩到认不出图片中的人是谁也达不到这个文件大小要求。

如果你的图片是用于Web的,以后再也不要选择“存储为”了,而应该选择“存储为Web所用格式”:

上图,注意右上角的预设选项,可以选择不同的保存格式,哪种格式既能保证图片质量又能把文件压缩得很小呢?

  • GIF:实用于图片颜色比较单一的图片,例如网页上的一些按钮图片;
  • JPEG:实用于图片颜色较丰富的图片,例如照片;
  • PNG:支持透明度,同时颜色丰富的图片也能有较好的压缩效果;

实在不行,就自己在预设选项中逐个都试一下,改变选项后左边会即时呈现压缩后的图片效果,并且图片左下角有显示压缩后的图片大小

最后,点击存储就可以了。

 

 

PHP 实现把 png、jpg/jpeg、gif 转成 webp 格式

由于项目要求需要将jpg、png类型的图片  转换成webp格式,最开始使用了php gd类库里 imagewebp 方法实现,结果发现转换成的webp格式文件会偶尔出现空白内容的情况。

像创建了一个透明图层的图片,但是尺寸和内存确跟转换成功的文件一般无二。

初想,可以找个办法判断一下图片是否无效的,网上找各种办法,结果无果。

虽然失败了但是还是上一下代码,期待大神能协助完善方法。

function imgToWebp($file=''){
    
    if(is_file($file)){
        $img = getimagesize($file);
        $type = $img['mime'];
        if($type == 'image/jpeg'){
            $file_source = imagecreatefromjpeg($file);
        }
        elseif($type == 'image/png'){
            $file_source = imagecreatefrompng($file);
        }
        else{
            return false;
        }
        $i = strripos($file,'.');
        $newFileName = substr($file,0,$i+1).'webp';
        $ret = imagewebp($file_source,$newFileName,'80');
        return $ret;
    }
}

使用前提条件为,php版本>=5.5  以上,并且开启gd类库。

上面这个方法的成功率不怎么高,欢迎指错。

 

在网上又找了一个 PHP 转换 webp格式的代码

<?php
/**
 * Use : 将JPEG/JPG/PNG 的图片转换为 WEBP 格式
 * User: yKan_SF
 * Date: 2018-2-27
 * Time: 下午8:22
 */
ini_set('display_errors',1);
class imagick_convert
{
    //原始图片绝对路径
    private $str_old_file = '';
    //转换webp默认扩展名
    private $str_default_ext = 'webp';
    //支持转换的图片格式
    private $arr_image_ext = null;

    /**
     * 默认构造函数
     */
    public function __construct($str_image_path)
    {
        $this->str_old_file = $str_image_path;
    }

    /**
     * Linux下ImageMagick + libwebp + php扩展imagick 转化 jpeg/jpg/png 图片文件
     * @param string $webp_dir webp图片的存储绝对路径
     * @return string  返回处理之后的图片绝对路径
     */
    public function convert_transform_images($webp_dir = '')
    {
        //文件是否存在
        if(!is_file($this->str_old_file))
        {
               //WEBP格式转换:待转换的图片路径不正确
            return $this->str_old_file;
        }
        //图片基本信息
        $ext = pathinfo($this->str_old_file,PATHINFO_EXTENSION);
        $ext = empty($ext) ? '' : strtolower($ext);
        //图片质量
        $this->arr_image_ext = array(
            'jpeg' => Imagick::COMPRESSION_JPEG,
            'jpg'  => Imagick::COMPRESSION_JPEG,
            'png'  => Imagick::COMPRESSION_UNDEFINED,
        );
        //根据后缀名把jpg或者png转成webp
        if(!in_array($ext, array_keys($this->arr_image_ext)))
        {
               //WEBP格式转换:暂不支持该格式转换,目前仅支持转换 jpeg,jpg和png 格式
            return $this->str_old_file;
        }
        //默认webp图片新路径
        if(empty($webp_dir))
        {
            $webp_dir = rtrim($this->str_old_file,$ext) . $this->str_default_ext;
        }
        //开始转换
        try
        {
            //原图的质量
            $new_q = $this->get_img_quality($ext);
            //转换成webp格式
            $this->do_jpg_transform_webp($webp_dir, $new_q);
        }
        catch(Exception $e)
        {
               //WEBP格式转换:工具转换异常,切换至GD库转换
            $webp_dir = $this->php_gd_image_webp($ext,$webp_dir);
        }
        //睡眠0.2秒
        usleep(20000);
        if(is_file($webp_dir))
        {
               //删除原始图片 + 设置WEBP图片访问权限
            chmod($webp_dir, 0777);
            unlink($this->str_old_file);
               //WEBP格式转换:转换成功
            return $webp_dir;
        }
          //WEBP格式转换:转换失败,返回原始图片路径
        return $this->str_old_file;
    }

    /**
     * 获取图片的质量
     * @param string $str_ext 图片扩展名
     * @return int 图片的质量
     */
    private function get_img_quality($str_ext)
    {
        $resource = new Imagick($this->str_old_file);
        //png特殊处理
        if($str_ext == 'png')
        {
            $resource->setImageFormat('PNG');
        }
        $resource->setImageCompression($this->arr_image_ext[$str_ext]);
        $current = $resource->getImageCompressionQuality();
        $resource->clear();
        $resource->destroy();
        if(!isset($current) || empty($current))
        {
            $current = 80;
        }
        $resource->clear();
        $resource->destroy();
        return $current;
    }

    /**
     * jpg/jpeg/png格式转换成webp格式
     * @param string $webp_img_path webp图片的真实路径
     * @param int $int_q 图片的压缩质量
     */
    private function do_jpg_transform_webp($webp_img_path, $int_q = 80)
    {
        exec("cwebp -q {$int_q} {$this->str_old_file} -o {$webp_img_path}");
    }

    /**
     * 应用PHP自身的GD库重新生成一张 webp 格式的图片,但是有概率生成空白图(有风险)
     * @param string $ext  文件扩展名
     * @param string $webp_img_path  生成webp文件的绝对路径
     * @return string 返回处理之后的图片绝对路径
     */
    private function php_gd_image_webp($ext,$webp_img_path)
    {
        //jpg处理使用jpeg
        $ext = $ext == 'jpg' ? 'jpeg' : $ext;
        //拼接函数名 imagecreatefromjpeg 还是 imagecreatefrompng
        $funName = 'imagecreatefrom' . $ext;
        //开始转换
        $obj_img = null;
        try
        {
            //打开这个图片资源
            $obj_img = $funName($this->str_old_file);
            //用这个图片资源创建一个webp图片, 存在路径$tdir
            imagewebp($obj_img,$webp_img_path);
        }
        catch(Exception $e)
        {

        }
        //销毁画布资源
        if($obj_img != null)
        {
            imagedestroy($obj_img);
        }
        //睡眠0.3秒
        return $webp_img_path;
    }
} 

 

此外,webp github 库https://github.com/search?l=PHP&q=webp&type=Repositories  (php实现)

 

 

参考推荐

webp 图片格式介绍及浏览器支持   (推荐

WordPress 支持 WebP格式图片上传方法   (推荐

Linux 下将 PNG 和 JPG 批量互转的方法总结

CentOS下 将(jgp、png)图片转换成webp格式

WebP - Mac上使用cwebp,dwebp,webpmux工具

Linux环境—JPEG/JPG/PNG图片转换WEBP格式 (CSDN)

WebP官方转换工具手把手安装教程,支持Mac (CSDN)

JPEG-to-JPG (图片转换网站)

WebP to animated GIF converter(图片转换网站)