无法在Go中获取图片的SubImage [英] Trouble getting a SubImage of an Image in Go

查看:59
本文介绍了无法在Go中获取图片的SubImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Go中进行一些图像处理,并且试图获取图像的SubImage.

I'm doing some image processing in Go, and I'm trying to get the 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)
}

当我尝试对其进行编译时,得到.\ img.go:8:picture.SubImage未定义(类型image.Image没有字段或方法SubImage).

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

有什么想法吗?

推荐答案

这是另一种方法-使用类型断言来断言 my_image 具有 SubImage 方法.该方法适用于具有 SubImage 方法的所有图像类型(除 Uniform外,所有其他类型进行快速扫描).这将返回另一个未指定类型的 Image 接口.

Here is an alternative approach - use a type assertion to assert that my_image has a SubImage method. This will work for any image type which has the SubImage method (all of them except Uniform at a quick scan). This will return another Image interface of some unspecified 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())

}

如果您想做很多事情,那么可以使用 SubImage 接口创建一个新类型并使用它.

If you wanted to do this a lot then you would create a new type with the SubImage interface and use that.

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

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

通常带有类型断言的警告-如果您不使用,请使用,ok 格式不想惊慌.

The usual caveats with type assertions apply - use the ,ok form if you don't want a panic.

这篇关于无法在Go中获取图片的SubImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆