请问,golang有没图片格式转换的库?

请问,golang有没图片格式转换的库?比如 .png转.jpg .bmp转.jpg 这样的

讨论数量: 3
 package main

 import (
         "fmt"
         "image"
         "image/color"
         "image/draw"
         "image/jpeg"
         "image/png"
         "os"
 )

 func main() {
         pngImgFile, err := os.Open("./PNG-file.png")

         if err != nil {
                 fmt.Println("PNG-file.png file not found!")
                 os.Exit(1)
         }

         defer pngImgFile.Close()

         // create image from PNG file
         imgSrc, err := png.Decode(pngImgFile)

         if err != nil {
                 fmt.Println(err)
                 os.Exit(1)
         }

         // create a new Image with the same dimension of PNG image
         newImg := image.NewRGBA(imgSrc.Bounds())

         // we will use white background to replace PNG's transparent background
         // you can change it to whichever color you want with
         // a new color.RGBA{} and use image.NewUniform(color.RGBA{<fill in color>}) function

         draw.Draw(newImg, newImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)

         // paste PNG image OVER to newImage
         draw.Draw(newImg, newImg.Bounds(), imgSrc, imgSrc.Bounds().Min, draw.Over)

         // create new out JPEG file
         jpgImgFile, err := os.Create("./JPEG-file.jpg")

         if err != nil {
                 fmt.Println("Cannot create JPEG-file.jpg !")
                 fmt.Println(err)
                 os.Exit(1)
         }

         defer jpgImgFile.Close()

         var opt jpeg.Options
         opt.Quality = 80

         // convert newImage to JPEG encoded byte and save to jpgImgFile
         // with quality = 80
         err = jpeg.Encode(jpgImgFile, newImg, &opt)

         //err = jpeg.Encode(jpgImgFile, newImg, nil) -- use nil if ignore quality options

         if err != nil {
                 fmt.Println(err)
                 os.Exit(1)
         }

         fmt.Println("Converted PNG file to JPEG file")
 }
1年前 评论

非常感谢,我去测试测试!

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!