j2kgo

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 15 Imported by: 1

README

J2KGo PkgGoDev

高性能、零依赖、纯 Go 语言 J2K 图像编解码库

安装指南

go get -u github.com/xiaoqidun/j2kgo

应用案例

OFDGo、PDFGo:使用 J2KGo 实现 OFD、PDF 中的图像编解码

解码图像

package main

import (
	"image/png"
	"log"
	"os"

	"github.com/xiaoqidun/j2kgo"
)

func main() {
	file, err := os.Open("test.jp2")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	img, err := j2kgo.Decode(file)
	if err != nil {
		log.Fatal(err)
	}
	out, err := os.Create("test.png")
	if err != nil {
		log.Fatal(err)
	}
	if err := png.Encode(out, img); err != nil {
		out.Close()
		log.Fatal(err)
	}
	if err := out.Close(); err != nil {
		log.Fatal(err)
	}
}

标准用法

package main

import (
	"image"
	"image/png"
	"log"
	"os"

	_ "github.com/xiaoqidun/j2kgo"
)

func main() {
	file, err := os.Open("test.jp2")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		log.Fatal(err)
	}
	out, err := os.Create("test.png")
	if err != nil {
		log.Fatal(err)
	}
	if err := png.Encode(out, img); err != nil {
		out.Close()
		log.Fatal(err)
	}
	if err := out.Close(); err != nil {
		log.Fatal(err)
	}
}

编码图像

package main

import (
	"image/png"
	"log"
	"os"

	"github.com/xiaoqidun/j2kgo"
)

func main() {
	file, err := os.Open("test.png")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	img, err := png.Decode(file)
	if err != nil {
		log.Fatal(err)
	}
	out, err := os.Create("test.jp2")
	if err != nil {
		log.Fatal(err)
	}
	if err := j2kgo.Encode(out, img, nil); err != nil {
		out.Close()
		log.Fatal(err)
	}
	if err := out.Close(); err != nil {
		log.Fatal(err)
	}
}

授权协议

本项目使用 Apache License 2.0 授权协议

Documentation

Overview

Package j2kgo 高性能、零依赖、纯 Go 语言 J2K 图像编解码库

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

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

Decode 解码为标准图像,多分量裸码流需使用DecodeContext指定颜色空间 入参: r 输入流 返回: image.Image 图像, error 错误信息

func DecodeConfig

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

DecodeConfig 读取图像尺寸与显示颜色模型,不解码图像样本 入参: r 输入流 返回: image.Config 图像配置, error 错误信息

func DecodeConfigContext

func DecodeConfigContext(ctx context.Context, r io.Reader, opts *DecodeOptions) (image.Config, error)

DecodeConfigContext 读取显示尺寸及颜色模型,不解码样本或建立整幅图像索引 仅读取头部,成功不代表完整码流有效;MaxLayers、Workers和Warning不参与配置读取 入参: ctx 上下文, r 输入流, opts 解码选项 返回: image.Config 图像配置, error 错误信息

func DecodeContext

func DecodeContext(ctx context.Context, r io.Reader, opts *DecodeOptions) (image.Image, error)

DecodeContext 在资源限制内解码并转换为标准图像,不关闭调用方的输入流 入参: ctx 上下文, r 输入流, opts 解码选项 返回: image.Image 图像, error 错误信息

func Encode

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

Encode 编码标准图像,opts为nil时使用无损JP2格式 入参: w 输出流, m 图像, opts 编码选项 返回: error 错误信息

func EncodeContext

func EncodeContext(ctx context.Context, w io.Writer, m image.Image, opts *EncodeOptions) error

EncodeContext 按瓦片编码标准图像,输出图像的原点为零 入参: ctx 上下文, w 输出流, m 图像, opts 编码选项 返回: error 错误信息

func EncodeRaster

func EncodeRaster(ctx context.Context, w io.Writer, raster *Raster, opts *EncodeOptions) error

EncodeRaster 编码原始分量,保留样本精度、符号及采样间隔 入参: ctx 上下文, w 输出流, raster 原始图像, opts 编码选项 返回: error 错误信息

Types

type ChannelInfo

type ChannelInfo struct {
	Index       uint16
	Type        ChannelType
	Association uint16
}

ChannelInfo 描述JP2通道及其颜色关联,Association为零表示整幅图像

type ChannelMapping

type ChannelMapping struct {
	Component uint16
	Type      MappingType
	Column    uint8
}

ChannelMapping 描述一个逻辑通道的分量来源及调色板列

type ChannelType

type ChannelType uint16

ChannelType JP2通道类型

const (
	ChannelColor         ChannelType = iota  // 颜色通道
	ChannelOpacity                           // 不透明度通道
	ChannelPremultiplied                     // 对应预乘颜色的不透明度通道
	ChannelUnspecified   ChannelType = 65535 // 未指定类型
)

type CodeBlockStyle

type CodeBlockStyle uint8

CodeBlockStyle 码块编码方式,可按位组合,零值使用默认算术编码

const (
	CodeBlockBypass       CodeBlockStyle = 1 << iota // 选择性算术编码旁路
	CodeBlockReset                                   // 编码遍结束后重置上下文
	CodeBlockTerminate                               // 每个编码遍独立终止
	CodeBlockCausal                                  // 垂直因果上下文
	CodeBlockPredictable                             // 可预测终止
	CodeBlockSegmentation                            // 清理遍分段符号
)

type ColorSpace

type ColorSpace uint32

ColorSpace 图像颜色空间,零值表示未知

const (
	ColorUnknown ColorSpace = 0  // 未指定颜色空间
	ColorSRGB    ColorSpace = 16 // sRGB
	ColorGray    ColorSpace = 17 // 灰度
	ColorSYCC    ColorSpace = 18 // sYCC
)

type ColorTransform

type ColorTransform uint8

ColorTransform 编码时使用的分量变换,作用于前三个分量,零值自动选择

const (
	ColorTransformAuto         ColorTransform = iota // 按小波类型和分量布局自动选择
	ColorTransformNone                               // 不进行分量变换
	ColorTransformReversible                         // 可逆分量变换
	ColorTransformIrreversible                       // 不可逆分量变换
)

type Component

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

Component 按精度紧凑存储原始样本,坐标位于分量网格

func (*Component) Bounds

func (c *Component) Bounds() image.Rectangle

Bounds 返回分量网格边界 返回: image.Rectangle 分量边界

func (*Component) Info

func (c *Component) Info() ComponentInfo

Info 返回分量信息 返回: ComponentInfo 分量信息

func (*Component) ReadSamples

func (c *Component) ReadSamples(dst []int64, x, y int) error

ReadSamples 将同一行的连续样本复制到目标切片,校验失败时不修改目标 入参: dst 目标切片, x 分量起始横坐标, y 分量行坐标 返回: error 错误信息

func (*Component) Sample

func (c *Component) Sample(x, y int) int64

Sample 返回原始样本,坐标越界时返回零 入参: x 分量横坐标, y 分量纵坐标 返回: int64 样本值

func (*Component) SetSample

func (c *Component) SetSample(x, y int, value int64) error

SetSample 设置原始样本,拒绝越界坐标及超出精度范围的值 入参: x 分量横坐标, y 分量纵坐标, value 样本值 返回: error 错误信息

func (*Component) WriteSamples

func (c *Component) WriteSamples(src []int64, x, y int) error

WriteSamples 写入同一行的连续样本,校验失败时不修改分量 入参: src 样本切片, x 分量起始横坐标, y 分量行坐标 返回: error 错误信息

type ComponentInfo

type ComponentInfo struct {
	Precision uint8
	Signed    bool
	XStep     uint8
	YStep     uint8
	XOffset   float64
	YOffset   float64
}

ComponentInfo 分量精度、采样间隔及配准偏移 Precision为1至38位,XStep和YStep为1至255个参考网格点 XOffset、YOffset以对应方向的采样间隔为单位,范围为[0,1),不改变样本坐标

type ComponentOptions

type ComponentOptions struct {
	Index               int
	Wavelet             *Wavelet
	DecompositionLevels *int
	CodeBlockSize       image.Point
	CodeBlockStyle      *CodeBlockStyle
	PrecinctSizes       []image.Point
	Quantization        *Quantization
}

ComponentOptions 指定单个分量的编码参数,未设置的选项沿用所在图像或瓦片的默认参数 分解级数与默认值不同时,若未指定PrecinctSizes,则使用32768×32768 默认量化参数不足以覆盖该分量的子带时,须单独设置Quantization

type DecodeOptions

type DecodeOptions struct {
	Reduce     int
	MaxLayers  int
	Workers    int
	Limits     Limits
	ColorSpace ColorSpace
	Warning    func(error)
}

DecodeOptions 解码选项,零值使用完整分辨率、全部质量层及默认资源限制 Reduce为0至32的分辨率缩减级数,MaxLayers为非负的质量层上限,零值读取全部质量层 Workers限制并发数,零值自动选择,内存不足时降低并发;ColorSpace仅指定裸码流的颜色空间 设置Warning后允许修正偏小的瓦片分段总数,或忽略与实际分段矛盾的TLM索引,并通过回调报告

type Decoder

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

Decoder 保存输入及解码索引,输入流由调用方关闭 使用后不可复制;关闭解码器前,调用方须保持输入内容可读且不变 同一解码器的并发及重入调用共用内部内存预算

func NewDecoder

func NewDecoder(ctx context.Context, r io.Reader, opts *DecodeOptions) (*Decoder, error)

NewDecoder 检查码流并建立解码索引,不解码图像样本 Warning仅在建立索引时使用,不由解码器保留 入参: ctx 上下文, r 输入流, opts 解码选项 返回: *Decoder 解码器, error 错误信息

func (*Decoder) Close

func (d *Decoder) Close() error

Close 释放解码索引与内部缓存,可重复调用,不关闭调用方输入流 返回: error 错误信息

func (*Decoder) Decode

func (d *Decoder) Decode(ctx context.Context) (*Raster, error)

Decode 解码原始分量,保留精度、符号和采样间隔 入参: ctx 上下文 返回: *Raster 原始图像, error 错误信息

func (*Decoder) DecodeBlocks

func (d *Decoder) DecodeBlocks(ctx context.Context, size image.Point, visit func(*Raster) error) error

DecodeBlocks 按瓦片顺序解码图块,各瓦片内按行遍历 回调依次执行,返回的图块互相独立;后续解码失败不影响已返回的图块,其内存不计入后续解码预算 入参: ctx 上下文, size 降低分辨率后的最大块尺寸,以参考网格点计,零值使用256×256, visit 图块回调,返回错误时停止解码 返回: error 错误信息

func (*Decoder) DecodeRegion

func (d *Decoder) DecodeRegion(ctx context.Context, bounds image.Rectangle) (*Raster, error)

DecodeRegion 解码指定区域,输出坐标使用Reduce指定的分辨率 为显示保留的相邻样本不会扩大返回图像的边界 入参: ctx 上下文, bounds 完整分辨率下的参考网格区域 返回: *Raster 区域图像, error 错误信息

func (*Decoder) DecodeSize

func (d *Decoder) DecodeSize(ctx context.Context, size image.Point) (*Raster, error)

DecodeSize 按目标尺寸选择码流分辨率并解码原始分量,不进行像素重采样 指定尺寸时仅覆盖本次解码的Reduce选项,零值沿用原选项 入参: ctx 上下文, size 目标参考网格尺寸,宽高须均为正数或均为零 返回: *Raster 原始分量图像,尺寸可能大于目标, error 错误信息

func (*Decoder) Info

func (d *Decoder) Info() Info

Info 返回完整分辨率的图像信息副本,解码器关闭后返回零值 返回: Info 图像信息

func (*Decoder) Metadata

func (d *Decoder) Metadata(ctx context.Context) ([]MetadataBox, error)

Metadata 按文件顺序读取JP2顶层的XML、UUID、UUID信息和版权元数据 返回数据由调用方独立持有,不影响图像解码,也不会在重新编码时自动写入 裸码流返回空列表;未知框不返回,外部URL不会被访问 入参: ctx 上下文 返回: []MetadataBox 元数据框, error 错误信息

func (*Decoder) Reduction

func (d *Decoder) Reduction(size image.Point) (int, error)

Reduction 在宽高均满足目标尺寸的前提下,返回可用的最大缩减级数,不读取图像样本 目标尺寸按参考网格计算;零值、超出原图的尺寸及调色板图像均返回零 入参: size 目标尺寸,宽高须均为正数或均为零 返回: int 分辨率缩减级数, error 参数或解码器状态错误

type EncodeOptions

type EncodeOptions struct {
	Format              Format
	Wavelet             Wavelet
	DecompositionLevels *int
	TileSize            image.Point
	TileOrigin          *image.Point
	TilePartPackets     int
	CodeBlockSize       image.Point
	CodeBlockStyle      CodeBlockStyle
	Quantization        *Quantization
	Components          []ComponentOptions
	Tiles               []TileOptions
	PrecinctSizes       []image.Point
	Progression         Progression
	ProgressionChanges  []ProgressionChange
	ColorTransform      ColorTransform
	ROI                 []image.Rectangle
	Layers              []Layer
	SOP                 bool
	EPH                 bool
	TLM                 bool
	PLM                 bool
	PLT                 bool
	PPT                 bool
	PPM                 bool
	Metadata            []MetadataBox
	Limits              Limits
}

EncodeOptions 编码选项,零值输出无损JP2,分解级数为nil时自动选择 TileOrigin指定瓦片网格起点,nil时使用图像起点,首个瓦片须覆盖图像起点 TilePartPackets限制每个瓦片分段的数据包数,零值不分段;Quantization为nil时自动生成量化参数 ROI指定输出参考网格中的优先编码区域,超出图像的部分不参与编码 SOP在每个数据包前写入起始标记,EPH在每个数据包头后写入结束标记 TLM、PLM分别在主头中写入瓦片分段长度表和数据包长度表,均需预编码以统计长度 PLM要求每个瓦片分段的包长编码不超过255字节;PLT在瓦片分段头中写入数据包长度表 PPT将数据包头集中写入所属瓦片分段头;PPM将全部数据包头集中写入主头,需预编码且不可与PPT同时启用 Metadata仅用于JP2,按顺序写入文件顶层;未指定时不添加XML、UUID或版权元数据

type Format

type Format uint8

Format 图像封装格式

const (
	FormatJP2 Format = iota // JP2封装
	FormatJ2K               // JPEG2000裸码流
)

type FormatError

type FormatError string

FormatError 码流或容器格式错误

func (FormatError) Error

func (e FormatError) Error() string

Error 返回错误描述 返回: string 错误描述

type Info

type Info struct {
	Bounds            image.Rectangle
	Components        []ComponentInfo
	Channels          []ChannelInfo
	Mapping           []ChannelMapping
	Palette           []PaletteColumn
	ColorSpace        ColorSpace
	ICCProfile        []byte
	CaptureResolution Resolution
	DisplayResolution Resolution
}

Info 图像的参考网格、分量及颜色信息

type Layer

type Layer struct {
	BitsPerPixel float64
}

Layer 指定质量层的累计目标码率,各层码率递增,末层为零时保留全部编码遍 BitsPerPixel按参考网格计算总码率,包含容器及头部开销,逐瓦片分配预算 使用不可逆变换时,即使保留全部编码遍也不能保证无损 启用ROI且未指定质量层时自动分层;末层码率为零时,层数须足以容纳全部编码遍

type LimitError

type LimitError struct {
	Resource string
	Limit    uint64
	Required uint64
}

LimitError 表示资源用量超出限制

func (*LimitError) Error

func (e *LimitError) Error() string

Error 返回错误描述 返回: string 错误描述

type Limits

type Limits struct {
	MaxInputBytes  uint64
	MaxSamples     uint64
	MaxMemoryBytes uint64
}

Limits 限制库内资源用量,零值使用默认限制,不限制调用方或整个进程的内存 默认输入上限为1GiB、样本上限为2^30、内存上限为512MiB;各字段为零时分别采用默认值

type MappingType

type MappingType uint8

MappingType 通道映射方式,分为直接映射和调色板映射

const (
	MappingDirect  MappingType = iota // 分量直接映射到通道
	MappingPalette                    // 分量作为调色板索引
)

type MetadataBox

type MetadataBox struct {
	Type string
	Data []byte
}

MetadataBox 保存JP2文件顶层的一个可选元数据框,不包含框头 Type为四字节类型标识,支持"xml "、"uuid"、"uinf"和"jp2i" Data保留原始内容;XML文档、UUID关联数据和版权信息的含义由调用方处理 XML内容由调用方保证良构,库不展开实体或验证供应方的元数据格式

type PaletteColumn

type PaletteColumn struct {
	Precision uint8
	Signed    bool
	Values    []int64
}

PaletteColumn 保存一列调色板的精度、符号及样本

type Progression

type Progression uint8

Progression 数据包渐进顺序

const (
	LRCP Progression = iota // 质量层、分辨率、分量、位置
	RLCP                    // 分辨率、质量层、分量、位置
	RPCL                    // 分辨率、位置、分量、质量层
	PCRL                    // 位置、分量、分辨率、质量层
	CPRL                    // 分量、位置、分辨率、质量层
)

type ProgressionChange

type ProgressionChange struct {
	Order           Progression
	ComponentStart  int
	ComponentEnd    int
	ResolutionStart int
	ResolutionEnd   int
	LayerEnd        int
}

ProgressionChange 指定数据包的渐进顺序和范围 范围包含起点、不包含终点,终点为零时使用对应上限 各范围按顺序处理,跳过已输出的数据包,所有范围须共同覆盖全部数据包

type Quantization

type Quantization struct {
	Style     QuantizationStyle
	GuardBits uint8
	Steps     []QuantizationStep
}

Quantization 指定量化方式、保护位数及子带参数 Steps以LL开头,其余子带按分辨率从低到高排列HL、LH、HH;派生量化仅指定LL

type QuantizationStep

type QuantizationStep struct {
	Exponent uint8
	Mantissa uint16
}

QuantizationStep 表示量化步长的指数与尾数 Exponent取值0至31,Mantissa取值0至2047;无量化时Mantissa须为零

type QuantizationStyle

type QuantizationStyle uint8

QuantizationStyle 子带量化方式

const (
	QuantizationNone      QuantizationStyle = iota // 不量化
	QuantizationDerived                            // 由LL子带步长派生
	QuantizationExpounded                          // 各子带独立指定步长
)

type Raster

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

Raster 保存图像元数据及未经显示颜色转换的原始分量 由NewRaster或解码方法创建;并发读取不修改样本时无需额外同步

func NewRaster

func NewRaster(info Info, limits Limits) (*Raster, error)

NewRaster 创建原始图像并复制元数据 入参: info 图像信息, limits 资源限制 返回: *Raster 原始图像, error 错误信息

func (*Raster) Bounds

func (r *Raster) Bounds() image.Rectangle

Bounds 返回参考网格边界 返回: image.Rectangle 图像边界

func (*Raster) Clone

func (r *Raster) Clone(ctx context.Context, limits Limits) (*Raster, error)

Clone 复制图像元数据及全部样本,原图内存不计入本次复制的资源限制 入参: ctx 上下文, limits 资源限制 返回: *Raster 独立图像副本, error 错误信息

func (*Raster) Component

func (r *Raster) Component(index int) *Component

Component 返回指定分量,索引越界时返回nil 返回值与原图共享样本,修改时须由调用方协调并发访问 入参: index 分量索引 返回: *Component 分量

func (*Raster) Image

func (r *Raster) Image(ctx context.Context, limits Limits) (image.Image, error)

Image 将原始分量转换为标准图像,输出原点为零,不修改原图 显示通道最高支持16位精度,更高精度须通过Component读取原始样本 资源限制仅用于输出图像和转换缓存,不包含原图内存 入参: ctx 上下文, limits 输出及转换缓存的资源限制 返回: image.Image 图像副本, error 错误信息

func (*Raster) Info

func (r *Raster) Info() Info

Info 返回独立的图像信息副本 返回: Info 图像信息

type Resolution

type Resolution struct {
	X float64
	Y float64
}

Resolution 表示JP2参考网格的物理分辨率,单位为每米网格点数,零值表示未指定

type TileOptions

type TileOptions struct {
	Index               int
	Wavelet             *Wavelet
	DecompositionLevels *int
	CodeBlockSize       image.Point
	CodeBlockStyle      *CodeBlockStyle
	Quantization        *Quantization
	Components          []ComponentOptions
	PrecinctSizes       []image.Point
	Progression         *Progression
	ProgressionChanges  []ProgressionChange
	ColorTransform      *ColorTransform
	ROI                 []image.Rectangle
	Layers              []Layer
	TilePartPackets     *int
	SOP                 *bool
	EPH                 *bool
	PLT                 *bool
	PPT                 *bool
}

TileOptions 指定单个瓦片的编码参数,Index按瓦片网格从左到右、从上到下编号 指针为nil或尺寸为零时沿用全局选项;分解级数改变且未指定区域尺寸时使用32768×32768 Components、ProgressionChanges、ROI和Layers为nil时沿用全局列表,非nil时替换整个列表 任一瓦片单独指定Layers时,各瓦片按自身像素数计算字节预算,公共头部开销按面积分摊

type UnsupportedError

type UnsupportedError string

UnsupportedError 表示尚不支持的格式特性

func (UnsupportedError) Error

func (e UnsupportedError) Error() string

Error 返回错误描述 返回: string 错误描述

type Wavelet

type Wavelet uint8

Wavelet 小波变换,零值使用可逆5/3变换

const (
	Wavelet53 Wavelet = iota // 可逆5/3变换
	Wavelet97                // 不可逆9/7变换
)

Jump to

Keyboard shortcuts

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