writer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package png
  5. import (
  6. "bufio"
  7. "compress/zlib"
  8. "hash/crc32"
  9. "image"
  10. "image/color"
  11. "io"
  12. "strconv"
  13. )
  14. // Encoder configures encoding PNG images.
  15. type Encoder struct {
  16. CompressionLevel CompressionLevel
  17. }
  18. type encoder struct {
  19. enc *Encoder
  20. w io.Writer
  21. m image.Image
  22. cb int
  23. err error
  24. header [8]byte
  25. footer [4]byte
  26. tmp [4 * 256]byte
  27. }
  28. type CompressionLevel int
  29. const (
  30. DefaultCompression CompressionLevel = 0
  31. NoCompression CompressionLevel = -1
  32. BestSpeed CompressionLevel = -2
  33. BestCompression CompressionLevel = -3
  34. // Positive CompressionLevel values are reserved to mean a numeric zlib
  35. // compression level, although that is not implemented yet.
  36. )
  37. // Big-endian.
  38. func writeUint32(b []uint8, u uint32) {
  39. b[0] = uint8(u >> 24)
  40. b[1] = uint8(u >> 16)
  41. b[2] = uint8(u >> 8)
  42. b[3] = uint8(u >> 0)
  43. }
  44. type opaquer interface {
  45. Opaque() bool
  46. }
  47. // Returns whether or not the image is fully opaque.
  48. func opaque(m image.Image) bool {
  49. if o, ok := m.(opaquer); ok {
  50. return o.Opaque()
  51. }
  52. b := m.Bounds()
  53. for y := b.Min.Y; y < b.Max.Y; y++ {
  54. for x := b.Min.X; x < b.Max.X; x++ {
  55. _, _, _, a := m.At(x, y).RGBA()
  56. if a != 0xffff {
  57. return false
  58. }
  59. }
  60. }
  61. return true
  62. }
  63. // The absolute value of a byte interpreted as a signed int8.
  64. func abs8(d uint8) int {
  65. if d < 128 {
  66. return int(d)
  67. }
  68. return 256 - int(d)
  69. }
  70. func (e *encoder) writeChunk(b []byte, name string) {
  71. if e.err != nil {
  72. return
  73. }
  74. n := uint32(len(b))
  75. if int(n) != len(b) {
  76. e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b)))
  77. return
  78. }
  79. writeUint32(e.header[:4], n)
  80. e.header[4] = name[0]
  81. e.header[5] = name[1]
  82. e.header[6] = name[2]
  83. e.header[7] = name[3]
  84. crc := crc32.NewIEEE()
  85. crc.Write(e.header[4:8])
  86. crc.Write(b)
  87. writeUint32(e.footer[:4], crc.Sum32())
  88. _, e.err = e.w.Write(e.header[:8])
  89. if e.err != nil {
  90. return
  91. }
  92. _, e.err = e.w.Write(b)
  93. if e.err != nil {
  94. return
  95. }
  96. _, e.err = e.w.Write(e.footer[:4])
  97. }
  98. func (e *encoder) writeIHDR() {
  99. b := e.m.Bounds()
  100. writeUint32(e.tmp[0:4], uint32(b.Dx()))
  101. writeUint32(e.tmp[4:8], uint32(b.Dy()))
  102. // Set bit depth and color type.
  103. switch e.cb {
  104. case cbG8:
  105. e.tmp[8] = 8
  106. e.tmp[9] = ctGrayscale
  107. case cbTC8:
  108. e.tmp[8] = 8
  109. e.tmp[9] = ctTrueColor
  110. case cbP8:
  111. e.tmp[8] = 8
  112. e.tmp[9] = ctPaletted
  113. case cbTCA8:
  114. e.tmp[8] = 8
  115. e.tmp[9] = ctTrueColorAlpha
  116. case cbG16:
  117. e.tmp[8] = 16
  118. e.tmp[9] = ctGrayscale
  119. case cbTC16:
  120. e.tmp[8] = 16
  121. e.tmp[9] = ctTrueColor
  122. case cbTCA16:
  123. e.tmp[8] = 16
  124. e.tmp[9] = ctTrueColorAlpha
  125. }
  126. e.tmp[10] = 0 // default compression method
  127. e.tmp[11] = 0 // default filter method
  128. e.tmp[12] = 0 // non-interlaced
  129. e.writeChunk(e.tmp[:13], "IHDR")
  130. }
  131. func (e *encoder) writePLTEAndTRNS(p color.Palette) {
  132. if len(p) < 1 || len(p) > 256 {
  133. e.err = FormatError("bad palette length: " + strconv.Itoa(len(p)))
  134. return
  135. }
  136. last := -1
  137. for i, c := range p {
  138. c1 := color.NRGBAModel.Convert(c).(color.NRGBA)
  139. e.tmp[3*i+0] = c1.R
  140. e.tmp[3*i+1] = c1.G
  141. e.tmp[3*i+2] = c1.B
  142. if c1.A != 0xff {
  143. last = i
  144. }
  145. e.tmp[3*256+i] = c1.A
  146. }
  147. e.writeChunk(e.tmp[:3*len(p)], "PLTE")
  148. if last != -1 {
  149. e.writeChunk(e.tmp[3*256:3*256+1+last], "tRNS")
  150. }
  151. }
  152. // An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks,
  153. // including an 8-byte header and 4-byte CRC checksum per Write call. Such calls
  154. // should be relatively infrequent, since writeIDATs uses a bufio.Writer.
  155. //
  156. // This method should only be called from writeIDATs (via writeImage).
  157. // No other code should treat an encoder as an io.Writer.
  158. func (e *encoder) Write(b []byte) (int, error) {
  159. e.writeChunk(b, "IDAT")
  160. if e.err != nil {
  161. return 0, e.err
  162. }
  163. return len(b), nil
  164. }
  165. // Chooses the filter to use for encoding the current row, and applies it.
  166. // The return value is the index of the filter and also of the row in cr that has had it applied.
  167. func filter(cr *[nFilter][]byte, pr []byte, bpp int) int {
  168. // We try all five filter types, and pick the one that minimizes the sum of absolute differences.
  169. // This is the same heuristic that libpng uses, although the filters are attempted in order of
  170. // estimated most likely to be minimal (ftUp, ftPaeth, ftNone, ftSub, ftAverage), rather than
  171. // in their enumeration order (ftNone, ftSub, ftUp, ftAverage, ftPaeth).
  172. cdat0 := cr[0][1:]
  173. cdat1 := cr[1][1:]
  174. cdat2 := cr[2][1:]
  175. cdat3 := cr[3][1:]
  176. cdat4 := cr[4][1:]
  177. pdat := pr[1:]
  178. n := len(cdat0)
  179. // The up filter.
  180. sum := 0
  181. for i := 0; i < n; i++ {
  182. cdat2[i] = cdat0[i] - pdat[i]
  183. sum += abs8(cdat2[i])
  184. }
  185. best := sum
  186. filter := ftUp
  187. // The Paeth filter.
  188. sum = 0
  189. for i := 0; i < bpp; i++ {
  190. cdat4[i] = cdat0[i] - pdat[i]
  191. sum += abs8(cdat4[i])
  192. }
  193. for i := bpp; i < n; i++ {
  194. cdat4[i] = cdat0[i] - paeth(cdat0[i-bpp], pdat[i], pdat[i-bpp])
  195. sum += abs8(cdat4[i])
  196. if sum >= best {
  197. break
  198. }
  199. }
  200. if sum < best {
  201. best = sum
  202. filter = ftPaeth
  203. }
  204. // The none filter.
  205. sum = 0
  206. for i := 0; i < n; i++ {
  207. sum += abs8(cdat0[i])
  208. if sum >= best {
  209. break
  210. }
  211. }
  212. if sum < best {
  213. best = sum
  214. filter = ftNone
  215. }
  216. // The sub filter.
  217. sum = 0
  218. for i := 0; i < bpp; i++ {
  219. cdat1[i] = cdat0[i]
  220. sum += abs8(cdat1[i])
  221. }
  222. for i := bpp; i < n; i++ {
  223. cdat1[i] = cdat0[i] - cdat0[i-bpp]
  224. sum += abs8(cdat1[i])
  225. if sum >= best {
  226. break
  227. }
  228. }
  229. if sum < best {
  230. best = sum
  231. filter = ftSub
  232. }
  233. // The average filter.
  234. sum = 0
  235. for i := 0; i < bpp; i++ {
  236. cdat3[i] = cdat0[i] - pdat[i]/2
  237. sum += abs8(cdat3[i])
  238. }
  239. for i := bpp; i < n; i++ {
  240. cdat3[i] = cdat0[i] - uint8((int(cdat0[i-bpp])+int(pdat[i]))/2)
  241. sum += abs8(cdat3[i])
  242. if sum >= best {
  243. break
  244. }
  245. }
  246. if sum < best {
  247. best = sum
  248. filter = ftAverage
  249. }
  250. return filter
  251. }
  252. func writeImage(w io.Writer, m image.Image, cb int, level int) error {
  253. zw, err := zlib.NewWriterLevel(w, level)
  254. if err != nil {
  255. return err
  256. }
  257. defer zw.Close()
  258. bpp := 0 // Bytes per pixel.
  259. switch cb {
  260. case cbG8:
  261. bpp = 1
  262. case cbTC8:
  263. bpp = 3
  264. case cbP8:
  265. bpp = 1
  266. case cbTCA8:
  267. bpp = 4
  268. case cbTC16:
  269. bpp = 6
  270. case cbTCA16:
  271. bpp = 8
  272. case cbG16:
  273. bpp = 2
  274. }
  275. // cr[*] and pr are the bytes for the current and previous row.
  276. // cr[0] is unfiltered (or equivalently, filtered with the ftNone filter).
  277. // cr[ft], for non-zero filter types ft, are buffers for transforming cr[0] under the
  278. // other PNG filter types. These buffers are allocated once and re-used for each row.
  279. // The +1 is for the per-row filter type, which is at cr[*][0].
  280. b := m.Bounds()
  281. var cr [nFilter][]uint8
  282. for i := range cr {
  283. cr[i] = make([]uint8, 1+bpp*b.Dx())
  284. cr[i][0] = uint8(i)
  285. }
  286. pr := make([]uint8, 1+bpp*b.Dx())
  287. gray, _ := m.(*image.Gray)
  288. rgba, _ := m.(*image.RGBA)
  289. paletted, _ := m.(*image.Paletted)
  290. nrgba, _ := m.(*image.NRGBA)
  291. for y := b.Min.Y; y < b.Max.Y; y++ {
  292. // Convert from colors to bytes.
  293. i := 1
  294. switch cb {
  295. case cbG8:
  296. if gray != nil {
  297. offset := (y - b.Min.Y) * gray.Stride
  298. copy(cr[0][1:], gray.Pix[offset:offset+b.Dx()])
  299. } else {
  300. for x := b.Min.X; x < b.Max.X; x++ {
  301. c := color.GrayModel.Convert(m.At(x, y)).(color.Gray)
  302. cr[0][i] = c.Y
  303. i++
  304. }
  305. }
  306. case cbTC8:
  307. // We have previously verified that the alpha value is fully opaque.
  308. cr0 := cr[0]
  309. stride, pix := 0, []byte(nil)
  310. if rgba != nil {
  311. stride, pix = rgba.Stride, rgba.Pix
  312. } else if nrgba != nil {
  313. stride, pix = nrgba.Stride, nrgba.Pix
  314. }
  315. if stride != 0 {
  316. j0 := (y - b.Min.Y) * stride
  317. j1 := j0 + b.Dx()*4
  318. for j := j0; j < j1; j += 4 {
  319. cr0[i+0] = pix[j+0]
  320. cr0[i+1] = pix[j+1]
  321. cr0[i+2] = pix[j+2]
  322. i += 3
  323. }
  324. } else {
  325. for x := b.Min.X; x < b.Max.X; x++ {
  326. r, g, b, _ := m.At(x, y).RGBA()
  327. cr0[i+0] = uint8(r >> 8)
  328. cr0[i+1] = uint8(g >> 8)
  329. cr0[i+2] = uint8(b >> 8)
  330. i += 3
  331. }
  332. }
  333. case cbP8:
  334. if paletted != nil {
  335. offset := (y - b.Min.Y) * paletted.Stride
  336. copy(cr[0][1:], paletted.Pix[offset:offset+b.Dx()])
  337. } else {
  338. pi := m.(image.PalettedImage)
  339. for x := b.Min.X; x < b.Max.X; x++ {
  340. cr[0][i] = pi.ColorIndexAt(x, y)
  341. i += 1
  342. }
  343. }
  344. case cbTCA8:
  345. if nrgba != nil {
  346. offset := (y - b.Min.Y) * nrgba.Stride
  347. copy(cr[0][1:], nrgba.Pix[offset:offset+b.Dx()*4])
  348. } else {
  349. // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
  350. for x := b.Min.X; x < b.Max.X; x++ {
  351. c := color.NRGBAModel.Convert(m.At(x, y)).(color.NRGBA)
  352. cr[0][i+0] = c.R
  353. cr[0][i+1] = c.G
  354. cr[0][i+2] = c.B
  355. cr[0][i+3] = c.A
  356. i += 4
  357. }
  358. }
  359. case cbG16:
  360. for x := b.Min.X; x < b.Max.X; x++ {
  361. c := color.Gray16Model.Convert(m.At(x, y)).(color.Gray16)
  362. cr[0][i+0] = uint8(c.Y >> 8)
  363. cr[0][i+1] = uint8(c.Y)
  364. i += 2
  365. }
  366. case cbTC16:
  367. // We have previously verified that the alpha value is fully opaque.
  368. for x := b.Min.X; x < b.Max.X; x++ {
  369. r, g, b, _ := m.At(x, y).RGBA()
  370. cr[0][i+0] = uint8(r >> 8)
  371. cr[0][i+1] = uint8(r)
  372. cr[0][i+2] = uint8(g >> 8)
  373. cr[0][i+3] = uint8(g)
  374. cr[0][i+4] = uint8(b >> 8)
  375. cr[0][i+5] = uint8(b)
  376. i += 6
  377. }
  378. case cbTCA16:
  379. // Convert from image.Image (which is alpha-premultiplied) to PNG's non-alpha-premultiplied.
  380. for x := b.Min.X; x < b.Max.X; x++ {
  381. c := color.NRGBA64Model.Convert(m.At(x, y)).(color.NRGBA64)
  382. cr[0][i+0] = uint8(c.R >> 8)
  383. cr[0][i+1] = uint8(c.R)
  384. cr[0][i+2] = uint8(c.G >> 8)
  385. cr[0][i+3] = uint8(c.G)
  386. cr[0][i+4] = uint8(c.B >> 8)
  387. cr[0][i+5] = uint8(c.B)
  388. cr[0][i+6] = uint8(c.A >> 8)
  389. cr[0][i+7] = uint8(c.A)
  390. i += 8
  391. }
  392. }
  393. // Apply the filter.
  394. f := ftNone
  395. if level != zlib.NoCompression {
  396. f = filter(&cr, pr, bpp)
  397. }
  398. // Write the compressed bytes.
  399. if _, err := zw.Write(cr[f]); err != nil {
  400. return err
  401. }
  402. // The current row for y is the previous row for y+1.
  403. pr, cr[0] = cr[0], pr
  404. }
  405. return nil
  406. }
  407. // Write the actual image data to one or more IDAT chunks.
  408. func (e *encoder) writeIDATs() {
  409. if e.err != nil {
  410. return
  411. }
  412. var bw *bufio.Writer
  413. bw = bufio.NewWriterSize(e, 1<<15)
  414. e.err = writeImage(bw, e.m, e.cb, levelToZlib(e.enc.CompressionLevel))
  415. if e.err != nil {
  416. return
  417. }
  418. e.err = bw.Flush()
  419. }
  420. // This function is required because we want the zero value of
  421. // Encoder.CompressionLevel to map to zlib.DefaultCompression.
  422. func levelToZlib(l CompressionLevel) int {
  423. switch l {
  424. case DefaultCompression:
  425. return zlib.DefaultCompression
  426. case NoCompression:
  427. return zlib.NoCompression
  428. case BestSpeed:
  429. return zlib.BestSpeed
  430. case BestCompression:
  431. return zlib.BestCompression
  432. default:
  433. return zlib.DefaultCompression
  434. }
  435. }
  436. func (e *encoder) writeIEND() { e.writeChunk(nil, "IEND") }
  437. // Encode writes the Image m to w in PNG format. Any Image may be
  438. // encoded, but images that are not image.NRGBA might be encoded lossily.
  439. func Encode(w io.Writer, m image.Image) error {
  440. var e Encoder
  441. return e.Encode(w, m)
  442. }
  443. // Encode writes the Image m to w in PNG format.
  444. func (enc *Encoder) Encode(w io.Writer, m image.Image) error {
  445. // Obviously, negative widths and heights are invalid. Furthermore, the PNG
  446. // spec section 11.2.2 says that zero is invalid. Excessively large images are
  447. // also rejected.
  448. mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy())
  449. if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 {
  450. return FormatError("invalid image size: " + strconv.FormatInt(mw, 10) + "x" + strconv.FormatInt(mh, 10))
  451. }
  452. var e encoder
  453. e.enc = enc
  454. e.w = w
  455. e.m = m
  456. var pal color.Palette
  457. // cbP8 encoding needs PalettedImage's ColorIndexAt method.
  458. if _, ok := m.(image.PalettedImage); ok {
  459. pal, _ = m.ColorModel().(color.Palette)
  460. }
  461. if pal != nil {
  462. e.cb = cbP8
  463. } else {
  464. switch m.ColorModel() {
  465. case color.GrayModel:
  466. e.cb = cbG8
  467. case color.Gray16Model:
  468. e.cb = cbG16
  469. case color.RGBAModel, color.NRGBAModel, color.AlphaModel:
  470. if opaque(m) {
  471. e.cb = cbTC8
  472. } else {
  473. e.cb = cbTCA8
  474. }
  475. default:
  476. if opaque(m) {
  477. e.cb = cbTC16
  478. } else {
  479. e.cb = cbTCA16
  480. }
  481. }
  482. }
  483. _, e.err = io.WriteString(w, pngHeader)
  484. e.writeIHDR()
  485. if pal != nil {
  486. e.writePLTEAndTRNS(pal)
  487. }
  488. e.writeIDATs()
  489. e.writeIEND()
  490. return e.err
  491. }