首页 > 解决方案 > 为 webp 文件格式生成缩略图

问题描述

以下代码是使用github.com/disintegration/imaging包创建缩略图,适用于 jpeg 等典型图像格式,但不适用于webp文件格式。

我收到imaging: unsupported image format下面的代码错误。

是否有更强大的方法来为典型图像类型(jpg、gif、tiff、bmp 等)和 webp 生成缩略图?

package main

import (
    "bytes"
    "fmt"
    "github.com/disintegration/imaging"
    "github.com/chai2010/webp"
    "io/ioutil"
)

//https://stackoverflow.com/questions/8340751/webp-encoder-decoder-in-go
func main() {
    //img, _ := imaging.Open("ml/input/apple.jpg")

    // Load webp
    data, _ := ioutil.ReadFile("ml/input/waterski2.webp")
    // Decode webp
    img, _ := webp.Decode(bytes.NewReader(data))
    //Create thumbnail
    dstImage := imaging.Thumbnail(img, 400, 400, imaging.Lanczos)

    err1:=imaging.Save(dstImage, "ml/output/waterski2.webp")
    if err1!=nil{
        fmt.Println(err1)
    }
}

标签: gowebp

解决方案


我最终得到了它的webp Save方法。

package main

import (
    "bytes"
    "github.com/chai2010/webp"
    "github.com/disintegration/imaging"
    "io/ioutil"
)

//https://stackoverflow.com/questions/8340751/webp-encoder-decoder-in-go
func main() {
    //img, _ := imaging.Open("ml/input/apple.jpg")

    // Load webp
    data, _ := ioutil.ReadFile("ml/input/waterski2.webp")
    // Decode webp
    img, _ := webp.Decode(bytes.NewReader(data))
    //Create thumbnail
    dstImage := imaging.Thumbnail(img, 400, 400, imaging.Lanczos)


    webp.Save("ml/output/waterski2.webp",dstImage,&webp.Options{})

    //err1:=imaging.Save(dstImage, "ml/output/waterski2.webp")
    //if err1!=nil{
    //  fmt.Println(err1)
    //}
}

推荐阅读