png.go 795 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package imagemeta
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "io"
  6. "github.com/imgproxy/imgproxy/v3/imagetype"
  7. )
  8. var pngMagick = []byte("\x89PNG\r\n\x1a\n")
  9. type PngFormatError string
  10. func (e PngFormatError) Error() string { return "invalid PNG format: " + string(e) }
  11. func DecodePngMeta(r io.Reader) (Meta, error) {
  12. var tmp [16]byte
  13. if _, err := io.ReadFull(r, tmp[:8]); err != nil {
  14. return nil, err
  15. }
  16. if !bytes.Equal(pngMagick, tmp[:8]) {
  17. return nil, PngFormatError("not a PNG image")
  18. }
  19. if _, err := io.ReadFull(r, tmp[:]); err != nil {
  20. return nil, err
  21. }
  22. return &meta{
  23. format: imagetype.PNG,
  24. width: int(binary.BigEndian.Uint32(tmp[8:12])),
  25. height: int(binary.BigEndian.Uint32(tmp[12:16])),
  26. }, nil
  27. }
  28. func init() {
  29. RegisterFormat(string(pngMagick), DecodePngMeta)
  30. }