Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion image/qoi.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
//
// For more information, see: https://qoiformat.org/
type QOI[T pixel.Color] struct {
data string
data []byte
width, height int
state qoiDecodeState[T]
}
Expand Down Expand Up @@ -48,6 +48,30 @@ func NewQOI[T pixel.Color](data string) (*QOI[T], error) {
// The colorspace affects how a pixel.Color is encoded.
return nil, errQOIUnsupportedColorSpace
}
img := &QOI[T]{
data: []byte(data),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will result in a heap allocation the size of the image, which is probably not what you want.
We could unsafely cast the string to a byte slice using unsafe.Slice (and then make sure to never modify it) to avoid this. It's a bit dangerous though.

}
img.width = int(uint32(data[4])<<24 | uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])<<0)
img.height = int(uint32(data[8])<<24 | uint32(data[9])<<16 | uint32(data[10])<<8 | uint32(data[11])<<0)
img.state.reset()
return img, nil
}

func NewQOIFromBytes[T pixel.Color](data []byte) (*QOI[T], error) {
if len(data) < 14 {
return nil, errQOIHeaderTooSmall
}
if string(data[:4]) != "qoif" {
return nil, errQOIInvalidMagic
}
if data[12] != 3 {
// We only support RGB, we don't support the alpha channel (yet!).
return nil, errQOIUnsupportedChannelNum
}
if data[13] != qoiColorSpaceSRGB {
// The colorspace affects how a pixel.Color is encoded.
return nil, errQOIUnsupportedColorSpace
}
img := &QOI[T]{
data: data,
}
Expand Down