Images

Following the stream-based design, the Go image package decodes images from a stream. By connecting to a remote stream and reading the bytes from the request, we can easily render an image from a web server. The following code uses the Fyne canvas.NewImageFromImage() function to render a Go decoded image, which we've loaded from the https://golang.org/doc/gopher/frontpage.png URL using image.Decode():

package main

import (
"image"
_ "image/png"
"io"
"log"
"net/http"

"fyne.io/fyne"
"fyne.io/fyne/app"
"fyne.io/fyne/canvas"
)

func readStream(url string) io.ReadCloser {
res, err := http.Get(url)
if err != nil || res.StatusCode != 200 {
log.Fatal("Error reading URL", err)
}

return res.Body
}

func remoteImage(url string) image.Image {
stream := readStream(url)
defer stream.Close()

m, _, err := image.Decode(stream)
if err != nil {
log.Fatal("Error reading image", err)
}

return m
}

func main() {
app := app.New()
w := app.NewWindow("Remote Image")

img := canvas.NewImageFromImage(remoteImage("https://golang.org/doc/gopher/frontpage.png"))
img.SetMinSize(fyne.Size{180, 250})
w.SetContent(img)
w.ShowAndRun()
}

As you would expect, this application opens a single window with the image loaded as its content:

Loading a file from the internet

But this only works appropriately when the internet connection is behaving correctly and, even then, may take longer than the user expects to load. Before we look at strategies to improve this, let's see how to do the same for data downloaded from a web service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.174