bmp.go 972 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package imagemeta
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "io"
  6. "github.com/imgproxy/imgproxy/v3/imagetype"
  7. )
  8. var bmpMagick = []byte("BM")
  9. func DecodeBmpMeta(r io.Reader) (Meta, error) {
  10. var tmp [26]byte
  11. if _, err := io.ReadFull(r, tmp[:]); err != nil {
  12. return nil, err
  13. }
  14. if !bytes.Equal(tmp[:2], bmpMagick) {
  15. return nil, newFormatError("BMP", "malformed header")
  16. }
  17. infoSize := binary.LittleEndian.Uint32(tmp[14:18])
  18. var width, height int
  19. if infoSize >= 40 {
  20. width = int(binary.LittleEndian.Uint32(tmp[18:22]))
  21. height = int(int32(binary.LittleEndian.Uint32(tmp[22:26])))
  22. } else {
  23. // CORE
  24. width = int(binary.LittleEndian.Uint16(tmp[18:20]))
  25. height = int(int16(binary.LittleEndian.Uint16(tmp[20:22])))
  26. }
  27. // height can be negative in Windows bitmaps
  28. if height < 0 {
  29. height = -height
  30. }
  31. return &meta{
  32. format: imagetype.BMP,
  33. width: width,
  34. height: height,
  35. }, nil
  36. }
  37. func init() {
  38. RegisterFormat(string(bmpMagick), DecodeBmpMeta)
  39. }