images

package
v0.0.0-...-db3ccfa Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2024 License: AGPL-3.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ImageFormatJPEG = ImageFormat("jpeg")
	ImageFormatWEBP = ImageFormat("webp")
	ImageFormatPNG  = ImageFormat("png")
)

List of image formats.

View Source
const (
	// ImageFitCover covers the given container with the image. The resulting
	// image may be shrunken, enlarged, and/or cropped.
	ImageFitCover = ImageFit("cover")

	// ImageFitContain fits the image in the container without either enlarging
	// the image or cropping it.
	ImageFitContain = ImageFit("contain")

	ImageFitDefault = ImageFitContain
)

There are the valid ImageFit values.

Variables

View Source
var (

	// HMACKey is the key used to set the HMAC portion of an image's URL.
	HMACKey []byte

	// FullImageURL takes in a partial url (a pathname with a set of query
	// parameters) and it should return a more complete url. This variable may
	// be nil.
	FullImageURL = func(s string) string {
		return "/images/" + s
	}
)
View Source
var (
	ErrImageNotFound          = errors.New("image not found")
	ErrStoreNotRegistered     = errors.New("store not registered")
	ErrBadURL                 = errors.New("bad image request url")
	ErrImageFormatUnsupported = errors.New("image format not supported")
	ErrImageFitUnsupported    = errors.New("invalid image fit")
)
View Source
var SkipProcessing = false

If SkipProcessing is set to true, images are saved as is, without compressing nor changing their size or format. Warning: This may lead to inadvertently storing (and leaking) image metadata.

Functions

func ClearCache

func ClearCache() error

ClearCache removes all cached image files.

func DeleteImageTx

func DeleteImageTx(ctx context.Context, tx *sql.Tx, db *sql.DB, image uid.ID) error

func ImageColumns

func ImageColumns(tableAlias string) []string

ImageColumns returns a list of columns of the images table (not all of them) for when selecting using and outer join. Use Image.ScanDestinations in conjunction with this function.

func ImageContainSize

func ImageContainSize(imageWidth, imageHeight, boxWidth, boxHeight int) (int, int)

ImageContainSize returns the width and height of an image as it would fit into a box, while keeping the aspect ratio of the image as it was.

func ImagePath

func ImagePath(id uid.ID) string

ImagePath returns the relative path of where an image is stored on disk (without the filename extension).

func ImageRecordColumns

func ImageRecordColumns() []string

ImageRecordColumns returns the list of columns of the images table. Use this function in conjuction with ImageRecordScanDestinations when selecting SQL joins.

func SaveImageTx

func SaveImageTx(ctx context.Context, tx *sql.Tx, storeName string, file []byte, opts *ImageOptions) (uid.ID, error)

func SetImagesRootFolder

func SetImagesRootFolder(p string)

SetImagesRootFolder sets the folder in which images are saved (for the disk store) and where cache files are stored. Make sure to call this function. The path p must be an absolute path.

Types

type Image

type Image struct {
	ID           *uid.ID      `json:"id"`
	Format       *ImageFormat `json:"format"`
	MimeType     *string      `json:"mimetype"`
	Width        *int         `json:"width"`
	Height       *int         `json:"height"`
	Size         *int         `json:"size"`
	AverageColor *RGB         `json:"averageColor"`
	URL          *string      `json:"url"`
	Copies       []*ImageCopy `json:"copies"`
}

Image is an image that's to be sent to the client. It is to be derived from an ImageRecord.

func NewImage

func NewImage() *Image

NewImage returns an Image with all pointer fields allocated and set to zero values.

func (*Image) AppendCopy

func (m *Image) AppendCopy(name string, boxWidth, boxHeight int, fit ImageFit, format ImageFormat) *ImageCopy

AppendCopy is a helper function that appends an ImageCopy to m.Copies slice. If format is zero, m.Format is used.

func (*Image) PostScan

func (m *Image) PostScan()

PostScan is to be called after m's fields are scanned from the database. It sets fields of m that are derived from database values (like m.URL).

func (*Image) ScanDestinations

func (m *Image) ScanDestinations() []any

func (*Image) SetURL

func (m *Image) SetURL()

SetURL sets m.URL properly with a hash signature.

type ImageCopy

type ImageCopy struct {
	ImageID   uid.ID      `json:"-"`
	Name      string      `json:"name,omitempty"` // To identify a copy.
	Width     int         `json:"width"`          // Real width of the image.
	Height    int         `json:"height"`         // Real height of the image.
	BoxWidth  int         `json:"boxWidth"`       // Width of the box the image fits into (for Format == ImageFitContain)
	BoxHeight int         `json:"boxHeight"`      // Height of the box the image fits into (for Format == ImageFitContain)
	Fit       ImageFit    `json:"objectFit"`
	Format    ImageFormat `json:"format"`
	URL       string      `json:"url"`
}

An ImageCopy is a transformed (size, format, and/or fit changed) copy of an Image.

func (*ImageCopy) SetURL

func (c *ImageCopy) SetURL()

SetURL sets c.URL to the correct value.

type ImageFit

type ImageFit string

ImageFit denotes how an image is to be fitted into a rectangle.

func (ImageFit) Supported

func (f ImageFit) Supported() bool

Supported returns false if f is not supported by this package.

type ImageFormat

type ImageFormat string

ImageFormat represents the type of image.

func (ImageFormat) BIMGType

func (f ImageFormat) BIMGType() (t bimg.ImageType, err error)

BIMGType converts f into its matching bimg.ImageType value.

func (ImageFormat) Extension

func (f ImageFormat) Extension() string

func (ImageFormat) Valid

func (f ImageFormat) Valid() bool

Valid reports whether f is supported by the image package.

type ImageOptions

type ImageOptions struct {
	Width, Height int
	Format        ImageFormat
	Fit           ImageFit
}

ImageOptions hold optional arguments to SaveImage.

type ImageRecord

type ImageRecord struct {
	ID uid.ID `json:"id"`

	StoreName string `json:"storeName"`

	StoreMetadata map[string]any `json:"storeMetadata"`

	Format       ImageFormat `json:"format"`
	Width        int         `json:"width"`
	Height       int         `json:"height"`
	Size         int         `json:"size"`
	UploadSize   int         `json:"uploadSize"`
	AverageColor RGB         `json:"averageColor"`
	CreatedAt    time.Time   `json:"createdAt"`
	DeletedAt    *time.Time  `json:"deletedAt"`
	// contains filtered or unexported fields
}

ImageRecord is a database row of an image item.

Table name: images.

func GetImageRecord

func GetImageRecord(ctx context.Context, db *sql.DB, id uid.ID) (*ImageRecord, error)

GetImageRecords returns an image record. If no image was found it returns ErrImageNotFound.

func GetImageRecords

func GetImageRecords(ctx context.Context, db *sql.DB, ids ...uid.ID) ([]*ImageRecord, error)

GetImageRecords returns a slice of image records. If no images were found it returns ErrImageNotFound.

func SaveImage

func SaveImage(ctx context.Context, db *sql.DB, storeName string, file []byte, opts *ImageOptions) (*ImageRecord, error)

SaveImage saves the provided image in the image store with the name storeName and creates a row in the images table. The argument opts can be nil, in which case default values are used.

func (*ImageRecord) Image

func (r *ImageRecord) Image() *Image

func (*ImageRecord) ScanDestinations

func (r *ImageRecord) ScanDestinations() []any

ScanDestinations returns a slice of pointers that sql.Rows.Scan can populate. The pointers match the column names returned by ImageRecordSelectColumns.

func (*ImageRecord) StoreExists

func (r *ImageRecord) StoreExists() bool

func (*ImageRecord) UnmarshalMetadataJSON

func (r *ImageRecord) UnmarshalMetadataJSON() error

UnmarshalMetadataJSON allocates r.StoreMetadata and fills it with JSON metadata fetched from the database.

type ImageSize

type ImageSize struct {
	Width, Height int
}

ImageSize represents the size of an image.

func (ImageSize) MarshalText

func (s ImageSize) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interface. Output is the same as String method.

func (ImageSize) String

func (s ImageSize) String() string

String returns, for example, "400" if width and height are both 400px, and "400x600" if width is 400px and height is 600px.

func (*ImageSize) UnmarshalText

func (s *ImageSize) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler interface.

func (ImageSize) Zero

func (s ImageSize) Zero() bool

Zero returns true if either the width or the height is 0.

type RGB

type RGB struct {
	Red   uint32 `json:"r"`
	Green uint32 `json:"g"`
	Blue  uint32 `json:"b"`
}

RGB represents color values of range (0, 255). It implements sql.Scanner and driver.Valuer interfaces. Use a 12-byte binary database column type to store values of this type in SQL databases.

func AverageColor

func AverageColor(img image.Image) RGB

AverageColor returns the average RGB color of img by averaging the colors of at most 10^4 pixels.

func (RGB) MarshalText

func (c RGB) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*RGB) Scan

func (c *RGB) Scan(src any) error

Scan implements sql.Scanner interface.

func (RGB) String

func (c RGB) String() string

String implements fmt.Stringer.

func (*RGB) UnmarshalJSON

func (c *RGB) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*RGB) UnmarshalText

func (c *RGB) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler interface.

func (RGB) Value

func (c RGB) Value() (driver.Value, error)

Value implements driver.Valuer interface.

type Server

type Server struct {
	SkipHashCheck bool
	DB            *sql.DB
	CacheDisabled bool
}

Server implements the http.Handler interface.

Set HMACKey and FullImageURL before this server is started.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

Jump to

Keyboard shortcuts

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