jpegn

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 12 Imported by: 7 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

jpegn

Status Go Reference

JPEG image decoder and encoder in pure Go.

No CGo, no dependencies.

SIMD support for amd64 (SSE4.1, AVX2), arm64 (NEON) and riscv64 (RVV, with GORISCV64=rva23u64). Build with -tags noasm for pure Go everywhere.

Decoding

img, err := jpegn.Decode(r)

jpegn.Decode returns the image in its native color space, *image.YCbCr, *image.Gray, *image.CMYK or *image.RGBA, and registers itself with image.RegisterFormat. It can also force RGBA output, pick the chroma upsampling filter, apply the EXIF orientation, and scale by 1/2, 1/4 or 1/8 inside the inverse transform, which costs less than a full decode.

Decoding rows

r, err := jpegn.NewRowReader(data)
defer r.Close()
for {
	rows, n, err := r.Next()    // n rows, r.RowBytes() apart, valid until the next call
	if err == io.EOF {
		break
	}
}

NewRowReader hands out the image a band of rows at a time, as Gray, RGBA or CMYK, equal to what Decode returns. A baseline image is decoded as its rows are read and holds a few MCU rows rather than the whole picture: a 48 megapixel 4:2:0 photograph decodes in 20 MB instead of 254 MB, and a little faster. A progressive image is decoded whole first.

Encoding

err := jpegn.Encode(w, img, &jpegn.EncodeOptions{Quality: 90})

Subsampling follows the source, so an image.YCbCr keeps its native ratio and its planes are encoded without resampling. Progressive mode, optimized Huffman tables, adaptive quantization and restart intervals are all opt-in, and EXIF and anything else, such as an ICC profile, carry through a decode and re-encode.

Supported

  • Baseline and progressive decoding, 8-bit grayscale, YCbCr, RGB, CMYK and YCCK
  • Any power-of-two subsampling and restart intervals; truncated or corrupt data decodes as far as it goes
  • Baseline and progressive encoding, grayscale or YCbCr, at 4:4:4, 4:4:0, 4:2:2 and 4:2:0
  • Optimized Huffman tables and jpegli's adaptive dead zone quantization
  • SIMD on amd64 (AVX2, SSE4.1), arm64 and riscv64; -tags noasm selects pure Go
  • 2-3x the standard library's decode speed and 4-6x its encode speed

License

MIT, in LICENSE.

Documentation

Overview

Package jpegn decodes and encodes JPEG images.

img, err := jpegn.Decode(r)

Decode returns the image in its native color space, *image.YCbCr, *image.Gray, *image.CMYK or *image.RGBA. The package registers itself with image.RegisterFormat, so image.Decode works once it is imported for side effects.

It reads baseline and progressive JPEG, 8-bit, grayscale, YCbCr, RGB, CMYK and YCCK, any power-of-two subsampling, and restart intervals. Truncated or corrupt scan data decodes as far as it goes rather than failing, which is what a viewer wants from a partial file. Arithmetic coding and 12-bit samples are refused with ErrUnsupported; a broken file gives ErrSyntax.

Options

Options are passed to any of the decode functions and default to zero:

img, err := jpegn.Decode(r, &jpegn.Options{
	ToRGBA:     true, // RGBA instead of the native color space
	AutoRotate: true, // apply the EXIF orientation
	ScaleDenom: 2,    // decode at half size
})

Options.ScaleDenom downscales inside the inverse transform, so 2, 4 and 8 cost less than a full decode rather than more. Options.UpsampleMethod selects the chroma filter for RGBA output, NearestNeighbor or the slower, smoother CatmullRom.

DecodeConfig reports the dimensions and color model without decoding the image, as they are stored in the frame header and ignoring EXIF orientation.

Encoding

Encode writes baseline JPEG by default:

err := jpegn.Encode(w, img, &jpegn.EncodeOptions{Quality: 90})

Quality runs from 1 to 100 and zero selects DefaultQuality. EncodeOptions.Subsampling follows the source unless it is set, so an *image.YCbCr keeps its native ratio and its planes are encoded without resampling.

Three options trade encode time for size, and all three are off by default because each changes the output:

err := jpegn.Encode(w, img, &jpegn.EncodeOptions{
	Quality:              90,
	OptimizeCoding:       true, // Huffman tables from the real statistics
	Progressive:          true, // spectral selection and successive approximation
	AdaptiveQuantization: true, // drop coefficients the eye is least likely to miss
})

EncodeOptions.OptimizeCoding saves about 4% at quality 50, rising to about 20% at quality 95. EncodeOptions.Progressive saves about 9% more on flat color and hard edges, and little or nothing on detailed photographic content. EncodeOptions.AdaptiveQuantization is jpegli's per-block dead zone, worth about 10% again; it does not vary the quantization table, so the result is an ordinary JPEG that any decoder reads. Together they are about 17% below plain baseline at about 1.6x the encode time.

EncodeOptions.RestartInterval puts a restart marker every so many MCUs, which bounds the damage a corrupt run of bytes can do.

Metadata

DecodeExif parses the EXIF an image carries, and RawExif returns the APP1 segment whole. Both report ErrNoEXIF when the file has none.

exif, err := jpegn.DecodeExif(r)

To carry metadata through a decode and re-encode, hand the raw segment back as EncodeOptions.Exif and anything else, an ICC profile for instance, as EncodeOptions.Segments. EncodeOptions.ResetOrientation rewrites the orientation tag to 1, which is what an encoder that has already applied the rotation should write.

Index

Constants

View Source
const DefaultQuality = 75

DefaultQuality is the quality used when EncodeOptions is nil or Quality is zero.

Variables

View Source
var (
	ErrNoJPEG             = errors.New("not a JPEG file")
	ErrNoEXIF             = errors.New("no EXIF data found")
	ErrUnsupported        = errors.New("unsupported format")
	ErrOutOfMemory        = errors.New("out of memory")
	ErrInternal           = errors.New("internal error")
	ErrSyntax             = errors.New("syntax error")
	ErrMissingHuffmanCode = errors.New("missing Huffman code")
	ErrInvalidSegment     = errors.New("invalid marker segment")
)

Standard error types for JPEG decoding.

Functions

func Decode

func Decode(r io.Reader, opts ...*Options) (image.Image, error)

Decode reads a JPEG image from r and returns it as an image.Image. It accepts an optional Options struct to control decoding parameters.

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the color model and dimensions of a JPEG image without decoding the entire image data. The dimensions returned are as stored in the file (SOF marker), ignoring any EXIF orientation tags.

func DrawYCbCr added in v0.7.2

func DrawYCbCr(dst *image.RGBA, src *image.YCbCr, sp image.Point)

DrawYCbCr converts src from sp to RGBA in dst, as Decode with ToRGBA does.

func Encode added in v0.5.0

func Encode(w io.Writer, m image.Image, opts ...*EncodeOptions) error

Encode writes the image m to w as JPEG, baseline unless EncodeOptions.Progressive is set.

func Orient added in v0.7.2

func Orient(img image.Image, orientation int) image.Image

Orient applies an EXIF orientation to img, keeping RGBA, YCbCr and Gray in their own color space.

func RawExif added in v0.5.0

func RawExif(r io.Reader) ([]byte, error)

RawExif returns the EXIF APP1 segment verbatim, for EncodeOptions.Exif.

Types

type EncodeOptions added in v0.5.0

type EncodeOptions struct {
	// Quality ranges from 1 (smallest) to 100 (best). Zero selects [DefaultQuality].
	Quality int
	// Subsampling selects the chroma subsampling ratio.
	Subsampling Subsampling
	// OptimizeCoding derives Huffman tables from the coefficient statistics.
	OptimizeCoding bool
	// Progressive writes a progressive JPEG.
	Progressive bool
	// AdaptiveQuantization drops coefficients the eye is least likely to miss.
	AdaptiveQuantization bool
	// RestartInterval is the MCU count between restart markers; zero disables them.
	RestartInterval int
	// Exif is a raw APP1 payload from [RawExif]; it replaces the JFIF APP0 segment.
	Exif []byte
	// ResetOrientation rewrites the embedded EXIF orientation tag to 1.
	ResetOrientation bool
	// Segments are additional marker segments written after the header segment.
	Segments []Segment
}

EncodeOptions specifies encoding parameters.

type Exif added in v0.3.0

type Exif struct {
	// Basic image info
	Orientation int // EXIF orientation (1-8). 1 = normal, values 2-8 indicate rotation/flip.
	Width       int // Image width in pixels (may differ from actual JPEG dimensions if rotated).
	Height      int // Image height in pixels.

	// Camera info
	Make     string // Camera manufacturer (e.g., "Canon").
	Model    string // Camera model (e.g., "Canon EOS 5D Mark III").
	Software string // Software used to process/create the image.

	// Date/Time (format: "YYYY:MM:DD HH:MM:SS")
	DateTime         string // File modification date/time.
	DateTimeOriginal string // Original capture date/time (when photo was taken).

	// Exposure settings
	ExposureTime float64 // Shutter speed in seconds (e.g., 0.004 = 1/250s).
	FNumber      float64 // Aperture f-number (e.g., 5.6 = f/5.6).
	ISOSpeed     int     // ISO speed rating (e.g., 800).
	FocalLength  float64 // Lens focal length in millimeters.
	Flash        int     // Flash mode/status (0 = no flash, non-zero = flash fired).

	// GPS location
	GPSLatitude  float64 // Latitude in decimal degrees (positive = North, negative = South).
	GPSLongitude float64 // Longitude in decimal degrees (positive = East, negative = West).
	GPSAltitude  float64 // Altitude in meters above sea level.

	// Copyright/Author
	Copyright string // Copyright notice.
	Artist    string // Creator/photographer name.
}

Exif contains metadata extracted from a JPEG image's EXIF data.

func DecodeExif added in v0.3.0

func DecodeExif(r io.Reader) (*Exif, error)

DecodeExif reads EXIF metadata from a JPEG image. Absent tags stay zero.

type Options

type Options struct {
	// ToRGBA forces RGBA output instead of the image's native color space.
	ToRGBA bool
	// UpsampleMethod selects the chroma upsampling algorithm, for RGBA output only.
	UpsampleMethod UpsampleMethod
	// AutoRotate applies the EXIF orientation, keeping the native color space except for CMYK.
	AutoRotate bool
	// ScaleDenom downscales during the IDCT. Valid values are 1, 2, 4 and 8; others are clamped.
	ScaleDenom int
}

Options specifies decoding parameters.

type RowReader added in v0.7.0

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

RowReader decodes a JPEG a band of rows at a time. A baseline image whose first scan carries every component is decoded as its rows are read, holding a few MCU rows of each component; any other is decoded whole first. Either way the rows equal those Decode returns with the same Options and ToRGBA set for a three component image: Gray for one component, RGBA for three and CMYK for four. AutoRotate is not applied.

func NewRowReader added in v0.7.0

func NewRowReader(data []byte, opts ...*Options) (*RowReader, error)

NewRowReader prepares to decode the JPEG in data, which it keeps and must not change until Close.

func (*RowReader) Close added in v0.7.0

func (r *RowReader) Close()

Close returns the decoder to its pool. The reader must not be used after.

func (*RowReader) ColorModel added in v0.7.0

func (r *RowReader) ColorModel() color.Model

ColorModel is the model of the rows: Gray, RGBA or CMYK.

func (*RowReader) Height added in v0.7.0

func (r *RowReader) Height() int

Height is the number of rows.

func (*RowReader) Next added in v0.7.0

func (r *RowReader) Next() ([]byte, int, error)

Next returns the next band of rows, RowBytes apart, and how many there are, without copying them; the band is valid until the next call. It returns io.EOF once every row has been read.

func (*RowReader) ReadRows added in v0.7.0

func (r *RowReader) ReadRows(dst []byte) (int, error)

ReadRows writes as many whole rows as fit in dst, top first, and returns how many it wrote. It returns io.EOF once every row has been read.

func (*RowReader) RowBytes added in v0.7.0

func (r *RowReader) RowBytes() int

RowBytes is the size of one row.

func (*RowReader) Width added in v0.7.0

func (r *RowReader) Width() int

Width is the width of the rows in pixels.

type Segment added in v0.5.0

type Segment struct {
	// Marker is an APPn marker (0xE0 to 0xEF) or the comment marker 0xFE.
	Marker byte
	// Data is the segment payload, at most 65533 bytes.
	Data []byte
}

Segment is an application or comment marker segment to embed in the output.

type Subsampling added in v0.5.0

type Subsampling int

Subsampling selects the chroma subsampling of the encoded image.

const (
	// SubsampleAuto follows the source image, defaulting to 4:2:0.
	SubsampleAuto Subsampling = iota
	// Subsample444 keeps chroma at full resolution.
	Subsample444
	// Subsample440 halves chroma vertically.
	Subsample440
	// Subsample422 halves chroma horizontally.
	Subsample422
	// Subsample420 halves chroma in both directions.
	Subsample420
	// SubsampleGray discards chroma and writes a single-component image.
	SubsampleGray
)

type UpsampleMethod

type UpsampleMethod int

UpsampleMethod defines the algorithm used for chroma upsampling.

const (
	// NearestNeighbor is a fast but low-quality upsampling method.
	NearestNeighbor UpsampleMethod = iota
	// CatmullRom is a higher-quality bicubic upsampling method.
	CatmullRom
)

Jump to

Keyboard shortcuts

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