stdlibreader.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. // Code generated by gen.go. DO NOT EDIT.
  2. // Copyright 2009 The Go Authors. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. // Package png implements a PNG image decoder and encoder.
  6. //
  7. // The PNG specification is at https://www.w3.org/TR/PNG/.
  8. package png
  9. import (
  10. "compress/zlib"
  11. "encoding/binary"
  12. "fmt"
  13. "hash"
  14. "hash/crc32"
  15. "image"
  16. "image/color"
  17. "io"
  18. )
  19. // Color type, as per the PNG spec.
  20. const (
  21. ctGrayscale = 0
  22. ctTrueColor = 2
  23. ctPaletted = 3
  24. ctGrayscaleAlpha = 4
  25. ctTrueColorAlpha = 6
  26. )
  27. // A cb is a combination of color type and bit depth.
  28. const (
  29. cbInvalid = iota
  30. cbG1
  31. cbG2
  32. cbG4
  33. cbG8
  34. cbGA8
  35. cbTC8
  36. cbP1
  37. cbP2
  38. cbP4
  39. cbP8
  40. cbTCA8
  41. cbG16
  42. cbGA16
  43. cbTC16
  44. cbTCA16
  45. )
  46. func cbPaletted(cb int) bool {
  47. return cbP1 <= cb && cb <= cbP8
  48. }
  49. func cbTrueColor(cb int) bool {
  50. return cb == cbTC8 || cb == cbTC16
  51. }
  52. // Filter type, as per the PNG spec.
  53. const (
  54. ftNone = 0
  55. ftSub = 1
  56. ftUp = 2
  57. ftAverage = 3
  58. ftPaeth = 4
  59. nFilter = 5
  60. )
  61. // Interlace type.
  62. const (
  63. itNone = 0
  64. itAdam7 = 1
  65. )
  66. // interlaceScan defines the placement and size of a pass for Adam7 interlacing.
  67. type interlaceScan struct {
  68. xFactor, yFactor, xOffset, yOffset int
  69. }
  70. // interlacing defines Adam7 interlacing, with 7 passes of reduced images.
  71. // See https://www.w3.org/TR/PNG/#8Interlace
  72. var interlacing = []interlaceScan{
  73. {8, 8, 0, 0},
  74. {8, 8, 4, 0},
  75. {4, 8, 0, 4},
  76. {4, 4, 2, 0},
  77. {2, 4, 0, 2},
  78. {2, 2, 1, 0},
  79. {1, 2, 0, 1},
  80. }
  81. // Decoding stage.
  82. // The PNG specification says that the IHDR, PLTE (if present), tRNS (if
  83. // present), IDAT and IEND chunks must appear in that order. There may be
  84. // multiple IDAT chunks, and IDAT chunks must be sequential (i.e. they may not
  85. // have any other chunks between them).
  86. // https://www.w3.org/TR/PNG/#5ChunkOrdering
  87. const (
  88. dsStart = iota
  89. dsSeenIHDR
  90. dsSeenPLTE
  91. dsSeentRNS
  92. dsSeenIDAT
  93. dsSeenIEND
  94. )
  95. const pngHeader = "\x89PNG\r\n\x1a\n"
  96. type decoder struct {
  97. r io.Reader
  98. img image.Image
  99. crc hash.Hash32
  100. width, height int
  101. depth int
  102. palette color.Palette
  103. cb int
  104. stage int
  105. idatLength uint32
  106. tmp [3 * 256]byte
  107. interlace int
  108. // useTransparent and transparent are used for grayscale and truecolor
  109. // transparency, as opposed to palette transparency.
  110. useTransparent bool
  111. transparent [6]byte
  112. }
  113. // A FormatError reports that the input is not a valid PNG.
  114. type FormatError string
  115. func (e FormatError) Error() string { return "png: invalid format: " + string(e) }
  116. var chunkOrderError = FormatError("chunk out of order")
  117. // An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.
  118. type UnsupportedError string
  119. func (e UnsupportedError) Error() string { return "png: unsupported feature: " + string(e) }
  120. func (d *decoder) parseIHDR(length uint32) error {
  121. if length != 13 {
  122. return FormatError("bad IHDR length")
  123. }
  124. if _, err := io.ReadFull(d.r, d.tmp[:13]); err != nil {
  125. return err
  126. }
  127. d.crc.Write(d.tmp[:13])
  128. if d.tmp[10] != 0 {
  129. return UnsupportedError("compression method")
  130. }
  131. if d.tmp[11] != 0 {
  132. return UnsupportedError("filter method")
  133. }
  134. if d.tmp[12] != itNone && d.tmp[12] != itAdam7 {
  135. return FormatError("invalid interlace method")
  136. }
  137. d.interlace = int(d.tmp[12])
  138. w := int32(binary.BigEndian.Uint32(d.tmp[0:4]))
  139. h := int32(binary.BigEndian.Uint32(d.tmp[4:8]))
  140. if w <= 0 || h <= 0 {
  141. return FormatError("non-positive dimension")
  142. }
  143. nPixels64 := int64(w) * int64(h)
  144. nPixels := int(nPixels64)
  145. if nPixels64 != int64(nPixels) {
  146. return UnsupportedError("dimension overflow")
  147. }
  148. // There can be up to 8 bytes per pixel, for 16 bits per channel RGBA.
  149. if nPixels != (nPixels*8)/8 {
  150. return UnsupportedError("dimension overflow")
  151. }
  152. d.cb = cbInvalid
  153. d.depth = int(d.tmp[8])
  154. switch d.depth {
  155. case 1:
  156. switch d.tmp[9] {
  157. case ctGrayscale:
  158. d.cb = cbG1
  159. case ctPaletted:
  160. d.cb = cbP1
  161. }
  162. case 2:
  163. switch d.tmp[9] {
  164. case ctGrayscale:
  165. d.cb = cbG2
  166. case ctPaletted:
  167. d.cb = cbP2
  168. }
  169. case 4:
  170. switch d.tmp[9] {
  171. case ctGrayscale:
  172. d.cb = cbG4
  173. case ctPaletted:
  174. d.cb = cbP4
  175. }
  176. case 8:
  177. switch d.tmp[9] {
  178. case ctGrayscale:
  179. d.cb = cbG8
  180. case ctTrueColor:
  181. d.cb = cbTC8
  182. case ctPaletted:
  183. d.cb = cbP8
  184. case ctGrayscaleAlpha:
  185. d.cb = cbGA8
  186. case ctTrueColorAlpha:
  187. d.cb = cbTCA8
  188. }
  189. case 16:
  190. switch d.tmp[9] {
  191. case ctGrayscale:
  192. d.cb = cbG16
  193. case ctTrueColor:
  194. d.cb = cbTC16
  195. case ctGrayscaleAlpha:
  196. d.cb = cbGA16
  197. case ctTrueColorAlpha:
  198. d.cb = cbTCA16
  199. }
  200. }
  201. if d.cb == cbInvalid {
  202. return UnsupportedError(fmt.Sprintf("bit depth %d, color type %d", d.tmp[8], d.tmp[9]))
  203. }
  204. d.width, d.height = int(w), int(h)
  205. return d.verifyChecksum()
  206. }
  207. func (d *decoder) parsePLTE(length uint32) error {
  208. np := int(length / 3) // The number of palette entries.
  209. if length%3 != 0 || np <= 0 || np > 256 || np > 1<<uint(d.depth) {
  210. return FormatError("bad PLTE length")
  211. }
  212. n, err := io.ReadFull(d.r, d.tmp[:3*np])
  213. if err != nil {
  214. return err
  215. }
  216. d.crc.Write(d.tmp[:n])
  217. switch d.cb {
  218. case cbP1, cbP2, cbP4, cbP8:
  219. d.palette = make(color.Palette, 256)
  220. for i := 0; i < np; i++ {
  221. d.palette[i] = color.RGBA{d.tmp[3*i+0], d.tmp[3*i+1], d.tmp[3*i+2], 0xff}
  222. }
  223. for i := np; i < 256; i++ {
  224. // Initialize the rest of the palette to opaque black. The spec (section
  225. // 11.2.3) says that "any out-of-range pixel value found in the image data
  226. // is an error", but some real-world PNG files have out-of-range pixel
  227. // values. We fall back to opaque black, the same as libpng 1.5.13;
  228. // ImageMagick 6.5.7 returns an error.
  229. d.palette[i] = color.RGBA{0x00, 0x00, 0x00, 0xff}
  230. }
  231. d.palette = d.palette[:np]
  232. case cbTC8, cbTCA8, cbTC16, cbTCA16:
  233. // As per the PNG spec, a PLTE chunk is optional (and for practical purposes,
  234. // ignorable) for the ctTrueColor and ctTrueColorAlpha color types (section 4.1.2).
  235. default:
  236. return FormatError("PLTE, color type mismatch")
  237. }
  238. return d.verifyChecksum()
  239. }
  240. func (d *decoder) parsetRNS(length uint32) error {
  241. switch d.cb {
  242. case cbG1, cbG2, cbG4, cbG8, cbG16:
  243. if length != 2 {
  244. return FormatError("bad tRNS length")
  245. }
  246. n, err := io.ReadFull(d.r, d.tmp[:length])
  247. if err != nil {
  248. return err
  249. }
  250. d.crc.Write(d.tmp[:n])
  251. copy(d.transparent[:], d.tmp[:length])
  252. switch d.cb {
  253. case cbG1:
  254. d.transparent[1] *= 0xff
  255. case cbG2:
  256. d.transparent[1] *= 0x55
  257. case cbG4:
  258. d.transparent[1] *= 0x11
  259. }
  260. d.useTransparent = true
  261. case cbTC8, cbTC16:
  262. if length != 6 {
  263. return FormatError("bad tRNS length")
  264. }
  265. n, err := io.ReadFull(d.r, d.tmp[:length])
  266. if err != nil {
  267. return err
  268. }
  269. d.crc.Write(d.tmp[:n])
  270. copy(d.transparent[:], d.tmp[:length])
  271. d.useTransparent = true
  272. case cbP1, cbP2, cbP4, cbP8:
  273. if length > 256 {
  274. return FormatError("bad tRNS length")
  275. }
  276. n, err := io.ReadFull(d.r, d.tmp[:length])
  277. if err != nil {
  278. return err
  279. }
  280. d.crc.Write(d.tmp[:n])
  281. if len(d.palette) < n {
  282. d.palette = d.palette[:n]
  283. }
  284. for i := 0; i < n; i++ {
  285. rgba := d.palette[i].(color.RGBA)
  286. d.palette[i] = color.NRGBA{rgba.R, rgba.G, rgba.B, d.tmp[i]}
  287. }
  288. default:
  289. return FormatError("tRNS, color type mismatch")
  290. }
  291. return d.verifyChecksum()
  292. }
  293. // Read presents one or more IDAT chunks as one continuous stream (minus the
  294. // intermediate chunk headers and footers). If the PNG data looked like:
  295. //
  296. // ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2
  297. //
  298. // then this reader presents xxxyy. For well-formed PNG data, the decoder state
  299. // immediately before the first Read call is that d.r is positioned between the
  300. // first IDAT and xxx, and the decoder state immediately after the last Read
  301. // call is that d.r is positioned between yy and crc1.
  302. func (d *decoder) Read(p []byte) (int, error) {
  303. if len(p) == 0 {
  304. return 0, nil
  305. }
  306. for d.idatLength == 0 {
  307. // We have exhausted an IDAT chunk. Verify the checksum of that chunk.
  308. if err := d.verifyChecksum(); err != nil {
  309. return 0, err
  310. }
  311. // Read the length and chunk type of the next chunk, and check that
  312. // it is an IDAT chunk.
  313. if _, err := io.ReadFull(d.r, d.tmp[:8]); err != nil {
  314. return 0, err
  315. }
  316. d.idatLength = binary.BigEndian.Uint32(d.tmp[:4])
  317. if string(d.tmp[4:8]) != "IDAT" {
  318. return 0, FormatError("not enough pixel data")
  319. }
  320. d.crc.Reset()
  321. d.crc.Write(d.tmp[4:8])
  322. }
  323. if int(d.idatLength) < 0 {
  324. return 0, UnsupportedError("IDAT chunk length overflow")
  325. }
  326. n, err := d.r.Read(p[:min(len(p), int(d.idatLength))])
  327. d.crc.Write(p[:n])
  328. d.idatLength -= uint32(n)
  329. return n, err
  330. }
  331. // decode decodes the IDAT data into an image.
  332. func (d *decoder) decode() (image.Image, error) {
  333. r, err := zlib.NewReader(d)
  334. if err != nil {
  335. return nil, err
  336. }
  337. defer r.Close()
  338. var img image.Image
  339. if d.interlace == itNone {
  340. img, err = d.readImagePass(r, 0, false)
  341. if err != nil {
  342. return nil, err
  343. }
  344. } else if d.interlace == itAdam7 {
  345. // Allocate a blank image of the full size.
  346. img, err = d.readImagePass(nil, 0, true)
  347. if err != nil {
  348. return nil, err
  349. }
  350. for pass := 0; pass < 7; pass++ {
  351. imagePass, err := d.readImagePass(r, pass, false)
  352. if err != nil {
  353. return nil, err
  354. }
  355. if imagePass != nil {
  356. d.mergePassInto(img, imagePass, pass)
  357. }
  358. }
  359. }
  360. // Check for EOF, to verify the zlib checksum.
  361. n := 0
  362. for i := 0; n == 0 && err == nil; i++ {
  363. if i == 100 {
  364. return nil, io.ErrNoProgress
  365. }
  366. n, err = r.Read(d.tmp[:1])
  367. }
  368. if err != nil && err != io.EOF {
  369. return nil, FormatError(err.Error())
  370. }
  371. if n != 0 || d.idatLength != 0 {
  372. return nil, FormatError("too much pixel data")
  373. }
  374. return img, nil
  375. }
  376. // readImagePass reads a single image pass, sized according to the pass number.
  377. func (d *decoder) readImagePass(r io.Reader, pass int, allocateOnly bool) (image.Image, error) {
  378. bitsPerPixel := 0
  379. pixOffset := 0
  380. var (
  381. gray *image.Gray
  382. rgba *image.RGBA
  383. paletted *image.Paletted
  384. nrgba *image.NRGBA
  385. gray16 *image.Gray16
  386. rgba64 *image.RGBA64
  387. nrgba64 *image.NRGBA64
  388. img image.Image
  389. )
  390. width, height := d.width, d.height
  391. if d.interlace == itAdam7 && !allocateOnly {
  392. p := interlacing[pass]
  393. // Add the multiplication factor and subtract one, effectively rounding up.
  394. width = (width - p.xOffset + p.xFactor - 1) / p.xFactor
  395. height = (height - p.yOffset + p.yFactor - 1) / p.yFactor
  396. // A PNG image can't have zero width or height, but for an interlaced
  397. // image, an individual pass might have zero width or height. If so, we
  398. // shouldn't even read a per-row filter type byte, so return early.
  399. if width == 0 || height == 0 {
  400. return nil, nil
  401. }
  402. }
  403. switch d.cb {
  404. case cbG1, cbG2, cbG4, cbG8:
  405. bitsPerPixel = d.depth
  406. if d.useTransparent {
  407. nrgba = image.NewNRGBA(image.Rect(0, 0, width, height))
  408. img = nrgba
  409. } else {
  410. gray = image.NewGray(image.Rect(0, 0, width, height))
  411. img = gray
  412. }
  413. case cbGA8:
  414. bitsPerPixel = 16
  415. nrgba = image.NewNRGBA(image.Rect(0, 0, width, height))
  416. img = nrgba
  417. case cbTC8:
  418. bitsPerPixel = 24
  419. if d.useTransparent {
  420. nrgba = image.NewNRGBA(image.Rect(0, 0, width, height))
  421. img = nrgba
  422. } else {
  423. rgba = image.NewRGBA(image.Rect(0, 0, width, height))
  424. img = rgba
  425. }
  426. case cbP1, cbP2, cbP4, cbP8:
  427. bitsPerPixel = d.depth
  428. paletted = image.NewPaletted(image.Rect(0, 0, width, height), d.palette)
  429. img = paletted
  430. case cbTCA8:
  431. bitsPerPixel = 32
  432. nrgba = image.NewNRGBA(image.Rect(0, 0, width, height))
  433. img = nrgba
  434. case cbG16:
  435. bitsPerPixel = 16
  436. if d.useTransparent {
  437. nrgba64 = image.NewNRGBA64(image.Rect(0, 0, width, height))
  438. img = nrgba64
  439. } else {
  440. gray16 = image.NewGray16(image.Rect(0, 0, width, height))
  441. img = gray16
  442. }
  443. case cbGA16:
  444. bitsPerPixel = 32
  445. nrgba64 = image.NewNRGBA64(image.Rect(0, 0, width, height))
  446. img = nrgba64
  447. case cbTC16:
  448. bitsPerPixel = 48
  449. if d.useTransparent {
  450. nrgba64 = image.NewNRGBA64(image.Rect(0, 0, width, height))
  451. img = nrgba64
  452. } else {
  453. rgba64 = image.NewRGBA64(image.Rect(0, 0, width, height))
  454. img = rgba64
  455. }
  456. case cbTCA16:
  457. bitsPerPixel = 64
  458. nrgba64 = image.NewNRGBA64(image.Rect(0, 0, width, height))
  459. img = nrgba64
  460. }
  461. if allocateOnly {
  462. return img, nil
  463. }
  464. bytesPerPixel := (bitsPerPixel + 7) / 8
  465. // The +1 is for the per-row filter type, which is at cr[0].
  466. rowSize := 1 + (int64(bitsPerPixel)*int64(width)+7)/8
  467. if rowSize != int64(int(rowSize)) {
  468. return nil, UnsupportedError("dimension overflow")
  469. }
  470. // cr and pr are the bytes for the current and previous row.
  471. cr := make([]uint8, rowSize)
  472. pr := make([]uint8, rowSize)
  473. for y := 0; y < height; y++ {
  474. // Read the decompressed bytes.
  475. _, err := io.ReadFull(r, cr)
  476. if err != nil {
  477. if err == io.EOF || err == io.ErrUnexpectedEOF {
  478. return nil, FormatError("not enough pixel data")
  479. }
  480. return nil, err
  481. }
  482. // Apply the filter.
  483. cdat := cr[1:]
  484. pdat := pr[1:]
  485. switch cr[0] {
  486. case ftNone:
  487. // No-op.
  488. case ftSub:
  489. for i := bytesPerPixel; i < len(cdat); i++ {
  490. cdat[i] += cdat[i-bytesPerPixel]
  491. }
  492. case ftUp:
  493. for i, p := range pdat {
  494. cdat[i] += p
  495. }
  496. case ftAverage:
  497. // The first column has no column to the left of it, so it is a
  498. // special case. We know that the first column exists because we
  499. // check above that width != 0, and so len(cdat) != 0.
  500. for i := 0; i < bytesPerPixel; i++ {
  501. cdat[i] += pdat[i] / 2
  502. }
  503. for i := bytesPerPixel; i < len(cdat); i++ {
  504. cdat[i] += uint8((int(cdat[i-bytesPerPixel]) + int(pdat[i])) / 2)
  505. }
  506. case ftPaeth:
  507. filterPaeth(cdat, pdat, bytesPerPixel)
  508. default:
  509. return nil, FormatError("bad filter type")
  510. }
  511. // Convert from bytes to colors.
  512. switch d.cb {
  513. case cbG1:
  514. if d.useTransparent {
  515. ty := d.transparent[1]
  516. for x := 0; x < width; x += 8 {
  517. b := cdat[x/8]
  518. for x2 := 0; x2 < 8 && x+x2 < width; x2++ {
  519. ycol := (b >> 7) * 0xff
  520. acol := uint8(0xff)
  521. if ycol == ty {
  522. acol = 0x00
  523. }
  524. nrgba.SetNRGBA(x+x2, y, color.NRGBA{ycol, ycol, ycol, acol})
  525. b <<= 1
  526. }
  527. }
  528. } else {
  529. for x := 0; x < width; x += 8 {
  530. b := cdat[x/8]
  531. for x2 := 0; x2 < 8 && x+x2 < width; x2++ {
  532. gray.SetGray(x+x2, y, color.Gray{(b >> 7) * 0xff})
  533. b <<= 1
  534. }
  535. }
  536. }
  537. case cbG2:
  538. if d.useTransparent {
  539. ty := d.transparent[1]
  540. for x := 0; x < width; x += 4 {
  541. b := cdat[x/4]
  542. for x2 := 0; x2 < 4 && x+x2 < width; x2++ {
  543. ycol := (b >> 6) * 0x55
  544. acol := uint8(0xff)
  545. if ycol == ty {
  546. acol = 0x00
  547. }
  548. nrgba.SetNRGBA(x+x2, y, color.NRGBA{ycol, ycol, ycol, acol})
  549. b <<= 2
  550. }
  551. }
  552. } else {
  553. for x := 0; x < width; x += 4 {
  554. b := cdat[x/4]
  555. for x2 := 0; x2 < 4 && x+x2 < width; x2++ {
  556. gray.SetGray(x+x2, y, color.Gray{(b >> 6) * 0x55})
  557. b <<= 2
  558. }
  559. }
  560. }
  561. case cbG4:
  562. if d.useTransparent {
  563. ty := d.transparent[1]
  564. for x := 0; x < width; x += 2 {
  565. b := cdat[x/2]
  566. for x2 := 0; x2 < 2 && x+x2 < width; x2++ {
  567. ycol := (b >> 4) * 0x11
  568. acol := uint8(0xff)
  569. if ycol == ty {
  570. acol = 0x00
  571. }
  572. nrgba.SetNRGBA(x+x2, y, color.NRGBA{ycol, ycol, ycol, acol})
  573. b <<= 4
  574. }
  575. }
  576. } else {
  577. for x := 0; x < width; x += 2 {
  578. b := cdat[x/2]
  579. for x2 := 0; x2 < 2 && x+x2 < width; x2++ {
  580. gray.SetGray(x+x2, y, color.Gray{(b >> 4) * 0x11})
  581. b <<= 4
  582. }
  583. }
  584. }
  585. case cbG8:
  586. if d.useTransparent {
  587. ty := d.transparent[1]
  588. for x := 0; x < width; x++ {
  589. ycol := cdat[x]
  590. acol := uint8(0xff)
  591. if ycol == ty {
  592. acol = 0x00
  593. }
  594. nrgba.SetNRGBA(x, y, color.NRGBA{ycol, ycol, ycol, acol})
  595. }
  596. } else {
  597. copy(gray.Pix[pixOffset:], cdat)
  598. pixOffset += gray.Stride
  599. }
  600. case cbGA8:
  601. for x := 0; x < width; x++ {
  602. ycol := cdat[2*x+0]
  603. nrgba.SetNRGBA(x, y, color.NRGBA{ycol, ycol, ycol, cdat[2*x+1]})
  604. }
  605. case cbTC8:
  606. if d.useTransparent {
  607. pix, i, j := nrgba.Pix, pixOffset, 0
  608. tr, tg, tb := d.transparent[1], d.transparent[3], d.transparent[5]
  609. for x := 0; x < width; x++ {
  610. r := cdat[j+0]
  611. g := cdat[j+1]
  612. b := cdat[j+2]
  613. a := uint8(0xff)
  614. if r == tr && g == tg && b == tb {
  615. a = 0x00
  616. }
  617. pix[i+0] = r
  618. pix[i+1] = g
  619. pix[i+2] = b
  620. pix[i+3] = a
  621. i += 4
  622. j += 3
  623. }
  624. pixOffset += nrgba.Stride
  625. } else {
  626. pix, i, j := rgba.Pix, pixOffset, 0
  627. for x := 0; x < width; x++ {
  628. pix[i+0] = cdat[j+0]
  629. pix[i+1] = cdat[j+1]
  630. pix[i+2] = cdat[j+2]
  631. pix[i+3] = 0xff
  632. i += 4
  633. j += 3
  634. }
  635. pixOffset += rgba.Stride
  636. }
  637. case cbP1:
  638. for x := 0; x < width; x += 8 {
  639. b := cdat[x/8]
  640. for x2 := 0; x2 < 8 && x+x2 < width; x2++ {
  641. idx := b >> 7
  642. if len(paletted.Palette) <= int(idx) {
  643. paletted.Palette = paletted.Palette[:int(idx)+1]
  644. }
  645. paletted.SetColorIndex(x+x2, y, idx)
  646. b <<= 1
  647. }
  648. }
  649. case cbP2:
  650. for x := 0; x < width; x += 4 {
  651. b := cdat[x/4]
  652. for x2 := 0; x2 < 4 && x+x2 < width; x2++ {
  653. idx := b >> 6
  654. if len(paletted.Palette) <= int(idx) {
  655. paletted.Palette = paletted.Palette[:int(idx)+1]
  656. }
  657. paletted.SetColorIndex(x+x2, y, idx)
  658. b <<= 2
  659. }
  660. }
  661. case cbP4:
  662. for x := 0; x < width; x += 2 {
  663. b := cdat[x/2]
  664. for x2 := 0; x2 < 2 && x+x2 < width; x2++ {
  665. idx := b >> 4
  666. if len(paletted.Palette) <= int(idx) {
  667. paletted.Palette = paletted.Palette[:int(idx)+1]
  668. }
  669. paletted.SetColorIndex(x+x2, y, idx)
  670. b <<= 4
  671. }
  672. }
  673. case cbP8:
  674. if len(paletted.Palette) != 256 {
  675. for x := 0; x < width; x++ {
  676. if len(paletted.Palette) <= int(cdat[x]) {
  677. paletted.Palette = paletted.Palette[:int(cdat[x])+1]
  678. }
  679. }
  680. }
  681. copy(paletted.Pix[pixOffset:], cdat)
  682. pixOffset += paletted.Stride
  683. case cbTCA8:
  684. copy(nrgba.Pix[pixOffset:], cdat)
  685. pixOffset += nrgba.Stride
  686. case cbG16:
  687. if d.useTransparent {
  688. ty := uint16(d.transparent[0])<<8 | uint16(d.transparent[1])
  689. for x := 0; x < width; x++ {
  690. ycol := uint16(cdat[2*x+0])<<8 | uint16(cdat[2*x+1])
  691. acol := uint16(0xffff)
  692. if ycol == ty {
  693. acol = 0x0000
  694. }
  695. nrgba64.SetNRGBA64(x, y, color.NRGBA64{ycol, ycol, ycol, acol})
  696. }
  697. } else {
  698. for x := 0; x < width; x++ {
  699. ycol := uint16(cdat[2*x+0])<<8 | uint16(cdat[2*x+1])
  700. gray16.SetGray16(x, y, color.Gray16{ycol})
  701. }
  702. }
  703. case cbGA16:
  704. for x := 0; x < width; x++ {
  705. ycol := uint16(cdat[4*x+0])<<8 | uint16(cdat[4*x+1])
  706. acol := uint16(cdat[4*x+2])<<8 | uint16(cdat[4*x+3])
  707. nrgba64.SetNRGBA64(x, y, color.NRGBA64{ycol, ycol, ycol, acol})
  708. }
  709. case cbTC16:
  710. if d.useTransparent {
  711. tr := uint16(d.transparent[0])<<8 | uint16(d.transparent[1])
  712. tg := uint16(d.transparent[2])<<8 | uint16(d.transparent[3])
  713. tb := uint16(d.transparent[4])<<8 | uint16(d.transparent[5])
  714. for x := 0; x < width; x++ {
  715. rcol := uint16(cdat[6*x+0])<<8 | uint16(cdat[6*x+1])
  716. gcol := uint16(cdat[6*x+2])<<8 | uint16(cdat[6*x+3])
  717. bcol := uint16(cdat[6*x+4])<<8 | uint16(cdat[6*x+5])
  718. acol := uint16(0xffff)
  719. if rcol == tr && gcol == tg && bcol == tb {
  720. acol = 0x0000
  721. }
  722. nrgba64.SetNRGBA64(x, y, color.NRGBA64{rcol, gcol, bcol, acol})
  723. }
  724. } else {
  725. for x := 0; x < width; x++ {
  726. rcol := uint16(cdat[6*x+0])<<8 | uint16(cdat[6*x+1])
  727. gcol := uint16(cdat[6*x+2])<<8 | uint16(cdat[6*x+3])
  728. bcol := uint16(cdat[6*x+4])<<8 | uint16(cdat[6*x+5])
  729. rgba64.SetRGBA64(x, y, color.RGBA64{rcol, gcol, bcol, 0xffff})
  730. }
  731. }
  732. case cbTCA16:
  733. for x := 0; x < width; x++ {
  734. rcol := uint16(cdat[8*x+0])<<8 | uint16(cdat[8*x+1])
  735. gcol := uint16(cdat[8*x+2])<<8 | uint16(cdat[8*x+3])
  736. bcol := uint16(cdat[8*x+4])<<8 | uint16(cdat[8*x+5])
  737. acol := uint16(cdat[8*x+6])<<8 | uint16(cdat[8*x+7])
  738. nrgba64.SetNRGBA64(x, y, color.NRGBA64{rcol, gcol, bcol, acol})
  739. }
  740. }
  741. // The current row for y is the previous row for y+1.
  742. pr, cr = cr, pr
  743. }
  744. return img, nil
  745. }
  746. // mergePassInto merges a single pass into a full sized image.
  747. func (d *decoder) mergePassInto(dst image.Image, src image.Image, pass int) {
  748. p := interlacing[pass]
  749. var (
  750. srcPix []uint8
  751. dstPix []uint8
  752. stride int
  753. rect image.Rectangle
  754. bytesPerPixel int
  755. )
  756. switch target := dst.(type) {
  757. case *image.Alpha:
  758. srcPix = src.(*image.Alpha).Pix
  759. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  760. bytesPerPixel = 1
  761. case *image.Alpha16:
  762. srcPix = src.(*image.Alpha16).Pix
  763. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  764. bytesPerPixel = 2
  765. case *image.Gray:
  766. srcPix = src.(*image.Gray).Pix
  767. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  768. bytesPerPixel = 1
  769. case *image.Gray16:
  770. srcPix = src.(*image.Gray16).Pix
  771. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  772. bytesPerPixel = 2
  773. case *image.NRGBA:
  774. srcPix = src.(*image.NRGBA).Pix
  775. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  776. bytesPerPixel = 4
  777. case *image.NRGBA64:
  778. srcPix = src.(*image.NRGBA64).Pix
  779. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  780. bytesPerPixel = 8
  781. case *image.Paletted:
  782. source := src.(*image.Paletted)
  783. srcPix = source.Pix
  784. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  785. bytesPerPixel = 1
  786. if len(target.Palette) < len(source.Palette) {
  787. // readImagePass can return a paletted image whose implicit palette
  788. // length (one more than the maximum Pix value) is larger than the
  789. // explicit palette length (what's in the PLTE chunk). Make the
  790. // same adjustment here.
  791. target.Palette = source.Palette
  792. }
  793. case *image.RGBA:
  794. srcPix = src.(*image.RGBA).Pix
  795. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  796. bytesPerPixel = 4
  797. case *image.RGBA64:
  798. srcPix = src.(*image.RGBA64).Pix
  799. dstPix, stride, rect = target.Pix, target.Stride, target.Rect
  800. bytesPerPixel = 8
  801. }
  802. s, bounds := 0, src.Bounds()
  803. for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  804. dBase := (y*p.yFactor+p.yOffset-rect.Min.Y)*stride + (p.xOffset-rect.Min.X)*bytesPerPixel
  805. for x := bounds.Min.X; x < bounds.Max.X; x++ {
  806. d := dBase + x*p.xFactor*bytesPerPixel
  807. copy(dstPix[d:], srcPix[s:s+bytesPerPixel])
  808. s += bytesPerPixel
  809. }
  810. }
  811. }
  812. func (d *decoder) parseIDAT(length uint32) (err error) {
  813. d.idatLength = length
  814. d.img, err = d.decode()
  815. if err != nil {
  816. return err
  817. }
  818. return d.verifyChecksum()
  819. }
  820. func (d *decoder) parseIEND(length uint32) error {
  821. if length != 0 {
  822. return FormatError("bad IEND length")
  823. }
  824. return d.verifyChecksum()
  825. }
  826. func (d *decoder) parseChunk(configOnly bool) error {
  827. // Read the length and chunk type.
  828. if _, err := io.ReadFull(d.r, d.tmp[:8]); err != nil {
  829. return err
  830. }
  831. length := binary.BigEndian.Uint32(d.tmp[:4])
  832. d.crc.Reset()
  833. d.crc.Write(d.tmp[4:8])
  834. // Read the chunk data.
  835. switch string(d.tmp[4:8]) {
  836. case "IHDR":
  837. if d.stage != dsStart {
  838. return chunkOrderError
  839. }
  840. d.stage = dsSeenIHDR
  841. return d.parseIHDR(length)
  842. case "PLTE":
  843. if d.stage != dsSeenIHDR {
  844. return chunkOrderError
  845. }
  846. d.stage = dsSeenPLTE
  847. return d.parsePLTE(length)
  848. case "tRNS":
  849. if cbPaletted(d.cb) {
  850. if d.stage != dsSeenPLTE {
  851. return chunkOrderError
  852. }
  853. } else if cbTrueColor(d.cb) {
  854. if d.stage != dsSeenIHDR && d.stage != dsSeenPLTE {
  855. return chunkOrderError
  856. }
  857. } else if d.stage != dsSeenIHDR {
  858. return chunkOrderError
  859. }
  860. d.stage = dsSeentRNS
  861. return d.parsetRNS(length)
  862. case "IDAT":
  863. if d.stage < dsSeenIHDR || d.stage > dsSeenIDAT || (d.stage == dsSeenIHDR && cbPaletted(d.cb)) {
  864. return chunkOrderError
  865. } else if d.stage == dsSeenIDAT {
  866. // Ignore trailing zero-length or garbage IDAT chunks.
  867. //
  868. // This does not affect valid PNG images that contain multiple IDAT
  869. // chunks, since the first call to parseIDAT below will consume all
  870. // consecutive IDAT chunks required for decoding the image.
  871. break
  872. }
  873. d.stage = dsSeenIDAT
  874. if configOnly {
  875. return nil
  876. }
  877. return d.parseIDAT(length)
  878. case "IEND":
  879. if d.stage != dsSeenIDAT {
  880. return chunkOrderError
  881. }
  882. d.stage = dsSeenIEND
  883. return d.parseIEND(length)
  884. }
  885. if length > 0x7fffffff {
  886. return FormatError(fmt.Sprintf("Bad chunk length: %d", length))
  887. }
  888. // Ignore this chunk (of a known length).
  889. var ignored [4096]byte
  890. for length > 0 {
  891. n, err := io.ReadFull(d.r, ignored[:min(len(ignored), int(length))])
  892. if err != nil {
  893. return err
  894. }
  895. d.crc.Write(ignored[:n])
  896. length -= uint32(n)
  897. }
  898. return d.verifyChecksum()
  899. }
  900. func (d *decoder) verifyChecksum() error {
  901. if _, err := io.ReadFull(d.r, d.tmp[:4]); err != nil {
  902. return err
  903. }
  904. if binary.BigEndian.Uint32(d.tmp[:4]) != d.crc.Sum32() {
  905. return FormatError("invalid checksum")
  906. }
  907. return nil
  908. }
  909. func (d *decoder) checkHeader() error {
  910. _, err := io.ReadFull(d.r, d.tmp[:len(pngHeader)])
  911. if err != nil {
  912. return err
  913. }
  914. if string(d.tmp[:len(pngHeader)]) != pngHeader {
  915. return FormatError("not a PNG file")
  916. }
  917. return nil
  918. }
  919. // Decode reads a PNG image from r and returns it as an [image.Image].
  920. // The type of Image returned depends on the PNG contents.
  921. func Decode(r io.Reader) (image.Image, error) {
  922. d := &decoder{
  923. r: r,
  924. crc: crc32.NewIEEE(),
  925. }
  926. if err := d.checkHeader(); err != nil {
  927. if err == io.EOF {
  928. err = io.ErrUnexpectedEOF
  929. }
  930. return nil, err
  931. }
  932. for d.stage != dsSeenIEND {
  933. if err := d.parseChunk(false); err != nil {
  934. if err == io.EOF {
  935. err = io.ErrUnexpectedEOF
  936. }
  937. return nil, err
  938. }
  939. }
  940. return d.img, nil
  941. }
  942. // DecodeConfig returns the color model and dimensions of a PNG image without
  943. // decoding the entire image.
  944. func DecodeConfig(r io.Reader) (image.Config, error) {
  945. d := &decoder{
  946. r: r,
  947. crc: crc32.NewIEEE(),
  948. }
  949. if err := d.checkHeader(); err != nil {
  950. if err == io.EOF {
  951. err = io.ErrUnexpectedEOF
  952. }
  953. return image.Config{}, err
  954. }
  955. for {
  956. if err := d.parseChunk(true); err != nil {
  957. if err == io.EOF {
  958. err = io.ErrUnexpectedEOF
  959. }
  960. return image.Config{}, err
  961. }
  962. if cbPaletted(d.cb) {
  963. if d.stage >= dsSeentRNS {
  964. break
  965. }
  966. } else {
  967. if d.stage >= dsSeenIHDR {
  968. break
  969. }
  970. }
  971. }
  972. var cm color.Model
  973. switch d.cb {
  974. case cbG1, cbG2, cbG4, cbG8:
  975. cm = color.GrayModel
  976. case cbGA8:
  977. cm = color.NRGBAModel
  978. case cbTC8:
  979. cm = color.RGBAModel
  980. case cbP1, cbP2, cbP4, cbP8:
  981. cm = d.palette
  982. case cbTCA8:
  983. cm = color.NRGBAModel
  984. case cbG16:
  985. cm = color.Gray16Model
  986. case cbGA16:
  987. cm = color.NRGBA64Model
  988. case cbTC16:
  989. cm = color.RGBA64Model
  990. case cbTCA16:
  991. cm = color.NRGBA64Model
  992. }
  993. return image.Config{
  994. ColorModel: cm,
  995. Width: d.width,
  996. Height: d.height,
  997. }, nil
  998. }
  999. func init() {
  1000. }