What's the easiest way for a Go program to display an image on Windows? I have this fragment based on a tutorial:
package main
import (
"image"
"image/color"
"image/draw"
)
func main() {
m := image.NewRGBA(image.Rect(0, 0, 640, 480))
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
}
But how to I display the object m? I'd like to pop up a window and display the image there, not write it out to a file first.
Updated answer using Fyne would be as follows, assuming a generateImage
function that creates the image.Image
to be rendered.
package main
import (
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/canvas"
)
func main() {
a := app.New()
w := a.NewWindow("Images")
img := canvas.NewImageFromImage(generateImage())
w.SetContent(img)
w.Resize(fyne.NewSize(640, 480))
w.ShowAndRun()
}
There is an image viewer sample in the package gxui, it shows an image selected from command line frags. The result can be seen here. It is likely one of the simpler approaches to present this gui using go.
Beware that gxui is experiental and future updates might break your code.
For your request, the code would be the following. It yields a window showing your image, a full blue image.
package main
import (
"image"
"image/color"
"image/draw"
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/themes/dark"
)
func appMain(driver gxui.Driver) {
width, height := 640, 480
m := image.NewRGBA(image.Rect(0, 0, width, height))
blue := color.RGBA{0, 0, 255, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
// The themes create the content. Currently only a dark theme is offered for GUI elements.
theme := dark.CreateTheme(driver)
img := theme.CreateImage()
window := theme.CreateWindow(width, height, "Image viewer")
texture := driver.CreateTexture(m, 1.0)
img.SetTexture(texture)
window.AddChild(img)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
}
I confirm this works on Windows and Linux. It likely works on MacOSX.
You might want to look into a more stable package if this is for production. For example go-qml or go-qt5 as mentioned by ComputerFellow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With