Problem getting SubImage image in Go

I am doing image processing in Go and I am trying to get a SubImage of an image.

import (
  "image/jpeg"
  "os"
)
func main(){
  image_file, err := os.Open("somefile.jpeg")
  my_image, err := jpeg.Decode(image_file)
  my_sub_image := my_image.SubImage(Rect(j, i, j+x_width, i+y_width)).(*image.RGBA)
}

When I try to compile this, I get .\img.go:8: picture.SubImage undefined (type image.Image has no field or method SubImage).

Any thoughts?

+5
source share
2 answers

Here's an alternative approach - use a type statement to state what the my_imagemethod has SubImage. This will work for any image that has a method SubImage(all of them, except Uniformfor quick scans). This will return another interface of Imagesome undefined type.

package main

import (
    "fmt"
    "image"
    "image/jpeg"
    "log"
    "os"
)

func main() {
    image_file, err := os.Open("somefile.jpeg")
    if err != nil {
        log.Fatal(err)
    }
    my_image, err := jpeg.Decode(image_file)
    if err != nil {
        log.Fatal(err)
    }

    my_sub_image := my_image.(interface {
        SubImage(r image.Rectangle) image.Image
    }).SubImage(image.Rect(0, 0, 10, 10))

    fmt.Printf("bounds %v\n", my_sub_image.Bounds())

}

If you want to do this a lot, you must create a new type with an interface SubImageand use it.

type SubImager interface {
    SubImage(r image.Rectangle) image.Image
}

my_sub_image := my_image.(SubImager).SubImage(image.Rect(0, 0, 10, 10))

- ,ok, .

+9

image.Image SubImage. , image.*.

rgbImg := img.(image.RGBA)
subImg := rgbImg.SubImage(...)
+5

All Articles