在Go中阅读图像

问题描述 投票:0回答:2
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
}

我正在创建一个图像。我想读取现有的Image并返回此函数。我怎么能这样做?

go
2个回答
2
投票

像这样的东西:

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

}

引用


1
投票

试试这个:

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)
 }

引用

© www.soinside.com 2019 - 2024. All rights reserved.