image

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 2 Imported by: 0

README

tinywasm/image

Todo lo relacionado con imágenes para TinyWasm: builders HTML + pipeline de optimización WebP + compresión en cliente.

Cuatro capas

  1. Builders (github.com/tinywasm/image) — Img, Picture, Source, construcción de elementos HTML. Compila para WASM y backend. Sin etiquetas de construcción (build tags).
  2. Pipeline (github.com/tinywasm/image/min) — Handler, Config, procesamiento WebP. Solo para backend (//go:build !wasm).
  3. Navegador (github.com/tinywasm/image/browser) — Compress, CompressToFit, compresión y redimensionado en el cliente antes de subir. Solo para WASM (//go:build wasm).
  4. Favicon (github.com/tinywasm/image/favicon) — //go:build !wasm — de un logo cuadrado al juego de iconos.

Favicon (Backend)

import "github.com/tinywasm/image/favicon"

files, _ := favicon.Derive(favicon.Source{Raster: pngBytes, SVG: svgBytes})
for _, f := range files {
    os.WriteFile(filepath.Join(outDir, f.Name), f.Content, 0644)
}

El nombre image sombrea el paquete estándar de Go a propósito: el stdlib image es demasiado pesado para TinyGo. Internamente, el pipeline aliasea el stdlib como stdimage.

Compresión en el cliente (Frontend/WASM)

import "github.com/tinywasm/image/browser"

// En el handler del evento 'change' de un <input type="file">:
file := input.Get("files").Index(0)

// Comprimir a 1920px maxEdge, WebP, calidad 0.85
res, err := browser.Compress(file, browser.Config{
    MaxEdge: 1920,
    Quality: 0.85,
    Type:    "image/webp",
})
if err != nil {
    // Manejar error (p.ej. browser.ErrUnsupported)
}

// res.Data contiene los []byte listos para subir por HTTP

Render (Frontend/WASM)

import . "github.com/tinywasm/image"

// Variantes generadas: S=480px, M=1024px, L=1600px (calidad JPEG 62 por defecto).
// sizes importa: sin el, el navegador asume 100vw y baja de mas en cualquier
// imagen que no ocupe el ancho completo.

// Imagen responsiva con srcset y sizes (100vw por defecto):
func (c *Card) Render() *dom.Element {
    return Responsive("/img/foto.jpg", "Fachada").
        Sizes("(max-width: 600px) 100vw, 33vw").
        Lazy().
        AsElement()
}

// Imagen simple sin srcset:
func (c *Logo) Render() *dom.Element {
    return Img("/img/logo.png", "Logo").Size(200, 50).AsElement()
}

Declaración para procesamiento (image.go, //go:build !wasm)

package herosection
import "github.com/tinywasm/image"

func RenderImages() []image.Asset {
    return []image.Asset{
        {Path: "img/hero.png", Variants: image.AllVariants, Alt: "Hero"},
    }
}

El nombre de archivo debe ser image.go. El pipeline lo detecta automáticamente.

Pipeline (Backend)

import "github.com/tinywasm/image/min"

handler := min.New(&min.Config{RootDir: ".", OutputDir: "web/public/img", Quality: 80})
handler.LoadImages()

La detección de módulos se delega a tinywasm/modfind.

Documentation

Index

Constants

View Source
const (
	WidthS = 480
	WidthM = 1024
	WidthL = 1600
)

Widths for responsive variants in pixels.

View Source
const AllVariants = VariantS | VariantM | VariantL

AllVariants includes all responsive variants.

View Source
const DefaultSizes = "100vw"

DefaultSizes is the default sizes attribute value for responsive images.

Variables

This section is empty.

Functions

func Picture

func Picture() *dom.Element

Picture builds a <picture> element for responsive images.

func Source

func Source(srcset, mediaOrType string) *dom.Element

Source builds a <source> for use inside <picture>. mediaOrType: media query "(max-width: 600px)" or MIME type "image/webp".

Types

type Asset

type Asset struct {
	Path     string  // relative to the module directory: "img/logo.png"
	Variants Variant // e.g., AllVariants, VariantS|VariantM, VariantL
	Alt      string  // SEO alternative text; if empty derived from filename
}

Asset represents an image declaration in a module.

type ImgElement

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

ImgElement wraps *dom.Element to provide a fluent image-specific API.

func Img

func Img(src, alt string) *ImgElement

Img builds an <img> element with src and alt.

func Responsive added in v0.0.25

func Responsive(base, alt string) *ImgElement

Responsive construye un <img> con srcset para las tres variantes que el pipeline genera, a partir de la ruta BASE (sin sufijo de variante).

Responsive("/img/foto.jpg", "Fachada")

emite:

<img src="/img/foto.M.jpg"
     srcset="/img/foto.S.jpg 480w, /img/foto.M.jpg 1024w, /img/foto.L.jpg 1600w"
     sizes="100vw" alt="Fachada">

El src apunta a la variante M para que un navegador que ignore srcset reciba algo razonable en vez de la version de escritorio.

func (*ImgElement) AsElement

func (i *ImgElement) AsElement() *dom.Element

AsElement returns the underlying *dom.Element for embedding in Render() trees.

func (*ImgElement) Attr

func (i *ImgElement) Attr(key, val string) *ImgElement

Attr sets an arbitrary attribute.

func (*ImgElement) Class

func (i *ImgElement) Class(classes ...string) *ImgElement

Class adds CSS classes.

func (*ImgElement) Lazy

func (i *ImgElement) Lazy() *ImgElement

Lazy sets loading="lazy".

func (*ImgElement) Size

func (i *ImgElement) Size(w, h int) *ImgElement

Size sets width and height (reduces CLS).

func (*ImgElement) Sizes added in v0.0.25

func (i *ImgElement) Sizes(s string) *ImgElement

Sizes declara al navegador que ancho ocupara la imagen en el layout, para que pueda elegir la variante ANTES de conocer el CSS.

func (*ImgElement) Srcset added in v0.0.25

func (i *ImgElement) Srcset(s string) *ImgElement

Srcset fija el atributo srcset a mano. Escape hatch para un consumidor con variantes que no siguen la convencion; Responsive es el camino normal.

func (*ImgElement) String

func (i *ImgElement) String() string

String serializes the image element (satisfies dom.Component).

type Variant

type Variant uint8

Variant represents a bitmask for responsive image variants.

const (
	VariantS Variant = 1 << iota // 1 — 480px  grillas y tarjetas
	VariantM                     // 2 — 1024px telefono a pantalla completa, tablet
	VariantL                     // 4 — 1600px escritorio
)

func (Variant) Suffix added in v0.0.25

func (v Variant) Suffix() string

Suffix es la marca que el pipeline intercala antes de la extension: "foto.jpg" con VariantM produce "foto.M.jpg".

Vive aqui y no en min/ porque quien ESCRIBE los archivos y quien los DECLARA en el HTML tienen que compartir una sola definicion: min/ es backend, y el que emite el srcset renderiza tambien en wasm.

func (Variant) Width added in v0.0.25

func (v Variant) Width() int

Width es el ancho en pixeles al que el pipeline redimensiona esta variante. Es el descriptor "w" que el srcset necesita para que el navegador elija.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL