Skip to main content

image

Package image decodes images upright, and loads network images with in-memory and disk caching.

Decoding​

Decode is the standard library's image.Decode plus EXIF orientation: cameras store a JPEG's pixels as the sensor saw them and record in its EXIF data how to turn them upright, which browsers apply and image.Decode does not. Decode applies all eight orientations, so a portrait photo decodes as portrait, its bounds being its displayed size. Use it to decode photos, files and assets for [widgets.Image].

Network Images​

The primary entry point is Loader, which fetches images over HTTP, decodes them into standard image.Image values, and caches the results in a two-tier cache (in-memory LRU via Cache, optional filesystem via DiskCache). Concurrent requests for the same URL are deduplicated into a single HTTP request, and callers can cancel individual listeners without affecting others.

Default Loader​

DefaultLoader returns a shared process-wide Loader with sensible defaults (100-entry / 100 MB memory cache, 500 MB disk cache under the platform cache directory). The [widgets.NetworkImage] widget uses DefaultLoader automatically.

Supported Formats​

This package registers decoders for PNG, JPEG, GIF, and WebP on import. Additional formats can be registered via the standard image.RegisterFormat mechanism. EXIF orientation is applied to JPEG only.

Custom Loader​

Applications that need custom cache sizes, HTTP clients, or headers can construct their own Loader:

loader := image.NewLoader(image.LoaderOptions{
MemoryCache: image.NewCache(image.CacheOptions{MaxEntries: 50}),
Client: myAuthClient,
})

cancel := loader.Load(url, image.LoadOptions{
Headers: map[string]string{"Authorization": "Bearer tok"},
}, func(result image.LoadResult) {
// handle result.Image or result.Err
})
defer cancel()

func Decode​

func Decode(r io.Reader) (img image.Image, format string, err error)

Decode decodes an image in any registered format, as the standard library's image.Decode does, and returns it upright: a JPEG's EXIF orientation (set by cameras, which store pixels as the sensor saw them) is applied, as browsers do. The returned image's bounds are its displayed size. format is the format name, such as "jpeg".

Use Decode, not image.Decode, for photos: from an image picker, the camera, a file or an asset. Loader decodes with it.

type Cache​

Cache is a thread-safe in-memory LRU cache for decoded images.

type Cache struct {
// contains filtered or unexported fields
}

func NewCache​

func NewCache(opts CacheOptions) *Cache

NewCache creates an in-memory LRU cache with the given options.

func (*Cache) Bytes​

func (c *Cache) Bytes() int64

Bytes returns the total estimated decoded size of cached images.

func (*Cache) Clear​

func (c *Cache) Clear()

Clear removes all entries from the cache.

func (*Cache) Get​

func (c *Cache) Get(key string) (image.Image, bool)

Get retrieves an image from the cache. Returns the image and true on hit, or nil and false on miss. A hit promotes the entry to most-recently-used.

func (*Cache) Len​

func (c *Cache) Len() int

Len returns the number of entries in the cache.

func (*Cache) Put​

func (c *Cache) Put(key string, img image.Image)

Put adds an image to the cache, evicting least-recently-used entries as needed. If the key already exists, the entry is replaced and promoted.

func (*Cache) Remove​

func (c *Cache) Remove(key string)

Remove removes a single entry from the cache.

type CacheOptions​

CacheOptions configures an in-memory image cache.

type CacheOptions struct {
// MaxEntries is the maximum number of images to cache. Default: 100.
MaxEntries int
// MaxBytes is the maximum total decoded size in bytes. Default: 100 MB.
MaxBytes int64
}

type DiskCache​

DiskCache persists raw image bytes to the filesystem. It stores undecoded response bodies so that Decode detects the format on read.

Keys are hashed with SHA-256 to produce safe filenames. When the cache exceeds MaxBytes, the oldest files by modification time are evicted.

type DiskCache struct {
// contains filtered or unexported fields
}

func NewDiskCache​

func NewDiskCache(dir string, maxBytes int64) (*DiskCache, error)

NewDiskCache creates a disk cache rooted at dir. The directory is created if it does not exist. maxBytes controls the total size limit; pass 0 for the default of 500 MB.

func (*DiskCache) Clear​

func (d *DiskCache) Clear() error

Clear removes all cached files.

func (*DiskCache) Get​

func (d *DiskCache) Get(key string) (io.ReadCloser, bool)

Get returns a reader for the cached data and true on hit, or nil and false on miss. The caller must close the returned reader.

func (*DiskCache) Put​

func (d *DiskCache) Put(key string, data []byte) error

Put writes data to the cache under key, then evicts old entries if the total cache size exceeds MaxBytes.

func (*DiskCache) Remove​

func (d *DiskCache) Remove(key string)

Remove deletes a single entry from the cache.

type HTTPError​

HTTPError represents a non-2xx HTTP response.

type HTTPError struct {
URL string
StatusCode int
}

func (*HTTPError) Error​

func (e *HTTPError) Error() string

type LoadOptions​

LoadOptions configures a single image load request.

type LoadOptions struct {
// Headers are added to the HTTP request (e.g., authorization tokens).
Headers map[string]string
}

type LoadResult​

LoadResult is the outcome of an image load operation.

type LoadResult struct {
// Image is the decoded image on success, nil on failure.
Image image.Image
// Err is the error on failure, nil on success.
Err error
}

type Loader​

Loader coordinates fetching, decoding (with Decode), and caching of network images. It deduplicates concurrent requests for the same URL. All methods are safe for concurrent use.

type Loader struct {
// contains filtered or unexported fields
}

func DefaultLoader​

func DefaultLoader() *Loader

DefaultLoader returns the process-wide shared Loader. It uses a 100-entry / 100 MB in-memory cache and a 500 MB disk cache under the platform's cache directory. The loader is created lazily on first call.

func NewLoader​

func NewLoader(opts LoaderOptions) *Loader

NewLoader creates a Loader with the given options.

func (*Loader) ClearCache​

func (l *Loader) ClearCache() error

ClearCache clears both memory and disk caches. Memory cache clearing is always attempted; disk cache errors are returned.

func (*Loader) Evict​

func (l *Loader) Evict(url string)

Evict removes a URL from both memory and disk caches, including all header-variant entries that were cached for different request headers.

func (*Loader) Load​

func (l *Loader) Load(url string, opts LoadOptions, callback func(LoadResult)) (cancel func())

Load fetches, decodes, and caches an image from url. The callback is invoked from a background goroutine with either the decoded image or an error. Callers that need to update UI state should use drift.Dispatch inside the callback to marshal onto the UI thread.

If the image is already in the memory cache, the callback is called synchronously before Load returns and cancel is a no-op.

The returned function cancels this listener. If all listeners for a URL cancel, the underlying HTTP request is also canceled.

type LoaderOptions​

LoaderOptions configures a Loader.

type LoaderOptions struct {
// MemoryCache is the in-memory LRU cache. Required.
MemoryCache *Cache
// DiskCache is the optional filesystem cache. Nil disables disk caching.
DiskCache *DiskCache
// Client is the HTTP client. Defaults to a client with 30s timeout.
Client *http.Client
}

Generated by gomarkdoc