Home>

About the process of converting a jpg file in the current directory to a png file in Go language.

When I execute png.Encode (out, img), SIGSEGV occurs due to a runtime error.
I can't think about which process is wrong, so I would like advice.

package main
import (
    "image"
    "image/png"
    "os"
)
func main () {
    // Original image
    f, _: = os.Open ("./cat.jpg")
    img, _, _: = image.Decode (f)
    defer f.Close ()
    // Conveted image
    out, _: = os.Create ("./cat.png")
    defer out.Close ()
    png.Encode (out, img)
}

Error output

anic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code = 0x1 addr = 0x20 pc = 0x10c88ba]

goroutine 1 [running]:
image/png. (* Encoder) .Encode (0xc00000c0a0, 0x1119c80, 0xc00000e088, 0x0, 0x0, 0x0, 0x0)
/usr/local/go/src/image/png/writer.go:569 + 0x5a
image/png.Encode (...)
/usr/local/go/src/image/png/writer.go:561
main.main ()
... tmp.go: 18 + 0x151
exit status 2

go
  • Answer # 1

    Firstos.OpenWe recommend that you do not ignore errors from functions such as.

    f, err: = os.Open ("./cat.jpg")
    if err! = nil {
        panic (err)
        // Error handling
    }
    // ...

    If an error occurs, simply displaying the error in standard error will give you a clue as to the cause.

    package main
    import (
        "image"
        "image/png"
        "os"
    )
    func main () {
        // Original image
        f, err: = os.Open ("./cat.jpg")
        if err! = nil {
            panic (err)
        }
        img, _, err: = image.Decode (f)
        if err! = nil {
            panic (err)
        }
        defer f.Close ()
        // Conveted image
        out, err: = os.Create ("./cat.png")
        if err! = nil {
            panic (err)
        }
        defer out.Close ()
        if err: = png.Encode (out, img);err! = nil {
            panic (err)
        }
    }

    If you execute the above, it will be as follows.

    panic: image: unknown format
    goroutine 1 [running]:
    main.main ()
        main.go: 17 + 0x22b

    As a concrete solution

    1. For import_ "image/jpeg"Specify to specify that jpeg is handled

    import (
        "image"
        _ "image/jpeg"
        "image/png"
        "os"
    )

    2.imageNot a packagejpegDecode using package

      img, err: = jpeg.Decode (f)
        if err! = nil {
            panic (err)
        }
        defer f.Close ()

    Such will be considered.