在Go中阅读图像

mbjcgjjk  于 2023-08-01  发布在  Go
关注(0)|答案(2)|浏览(103)
func (sticky *Sticky) DrawImage(W, H int) (img *image, err error) {

    myImage := image.NewRGBA(image.Rect(0, 0, 10, 25))
    myImage.Pix[0] = 55 // 1st pixel red
    myImage.Pix[1] = 155 // 1st pixel green
    return myImage ,nil
}

字符串
我在创造一个形象。我想读取现有的图像,并在此函数中返回。我该怎么做?

ldfqzlk8

ldfqzlk81#

大概是这样的:

func getImageFromFilePath(filePath string) (image.Image, error) {
    f, err := os.Open(filePath)
    if err != nil {
        return nil, err
    }
    defer f.Close()
    image, _, err := image.Decode(f)
    return image, err
}

字符串
参考文献

  • https://golang.org/pkg/image/#Decode
  • https://golang.org/pkg/os/#Open
jdzmm42g

jdzmm42g2#

试试这个:

package main

import (
  "fmt"
  "image"
  "image/png"
  "os"
)

func main() {
  // Read image from file that already exists
  existingImageFile, err := os.Open("test.png")
  if err != nil {
    // Handle error
  } 

  defer existingImageFile.Close()

  // Calling the generic image.Decode() will tell give us the data
  // and type of image it is as a string. We expect "png"
  imageData, imageType, err := image.Decode(existingImageFile)
  if err != nil {
    // Handle error
  }
  fmt.Println(imageData)
  fmt.Println(imageType)

  // We only need this because we already read from the file
  // We have to reset the file pointer back to beginning
  existingImageFile.Seek(0, 0)

  // Alternatively, since we know it is a png already
  // we can call png.Decode() directly
  loadedImage, err := png.Decode(existingImageFile)
  if err != nil {
    // Handle error
    }
  fmt.Println(loadedImage)
 }

字符串
参考文献

相关问题