resize.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. package imaging
  2. import (
  3. "image"
  4. "math"
  5. )
  6. type indexWeight struct {
  7. index int
  8. weight float64
  9. }
  10. func precomputeWeights(dstSize, srcSize int, filter ResampleFilter) [][]indexWeight {
  11. du := float64(srcSize) / float64(dstSize)
  12. scale := du
  13. if scale < 1.0 {
  14. scale = 1.0
  15. }
  16. ru := math.Ceil(scale * filter.Support)
  17. out := make([][]indexWeight, dstSize)
  18. tmp := make([]indexWeight, 0, dstSize*int(ru+2)*2)
  19. for v := 0; v < dstSize; v++ {
  20. fu := (float64(v)+0.5)*du - 0.5
  21. startu := int(math.Ceil(fu - ru))
  22. if startu < 0 {
  23. startu = 0
  24. }
  25. endu := int(math.Floor(fu + ru))
  26. if endu > srcSize-1 {
  27. endu = srcSize - 1
  28. }
  29. var sum float64
  30. for u := startu; u <= endu; u++ {
  31. w := filter.Kernel((float64(u) - fu) / scale)
  32. if w != 0 {
  33. sum += w
  34. tmp = append(tmp, indexWeight{index: u, weight: w})
  35. }
  36. }
  37. if sum != 0 {
  38. for i := range tmp {
  39. tmp[i].weight /= sum
  40. }
  41. }
  42. out[v] = tmp
  43. tmp = tmp[len(tmp):]
  44. }
  45. return out
  46. }
  47. // Resize resizes the image to the specified width and height using the specified resampling
  48. // filter and returns the transformed image. If one of width or height is 0, the image aspect
  49. // ratio is preserved.
  50. //
  51. // Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
  52. // CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
  53. //
  54. // Usage example:
  55. //
  56. // dstImage := imaging.Resize(srcImage, 800, 600, imaging.Lanczos)
  57. //
  58. func Resize(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
  59. dstW, dstH := width, height
  60. if dstW < 0 || dstH < 0 {
  61. return &image.NRGBA{}
  62. }
  63. if dstW == 0 && dstH == 0 {
  64. return &image.NRGBA{}
  65. }
  66. src := toNRGBA(img)
  67. srcW := src.Bounds().Max.X
  68. srcH := src.Bounds().Max.Y
  69. if srcW <= 0 || srcH <= 0 {
  70. return &image.NRGBA{}
  71. }
  72. // if new width or height is 0 then preserve aspect ratio, minimum 1px
  73. if dstW == 0 {
  74. tmpW := float64(dstH) * float64(srcW) / float64(srcH)
  75. dstW = int(math.Max(1.0, math.Floor(tmpW+0.5)))
  76. }
  77. if dstH == 0 {
  78. tmpH := float64(dstW) * float64(srcH) / float64(srcW)
  79. dstH = int(math.Max(1.0, math.Floor(tmpH+0.5)))
  80. }
  81. var dst *image.NRGBA
  82. if filter.Support <= 0.0 {
  83. // nearest-neighbor special case
  84. dst = resizeNearest(src, dstW, dstH)
  85. } else {
  86. // two-pass resize
  87. if srcW != dstW {
  88. dst = resizeHorizontal(src, dstW, filter)
  89. } else {
  90. dst = src
  91. }
  92. if srcH != dstH {
  93. dst = resizeVertical(dst, dstH, filter)
  94. }
  95. }
  96. return dst
  97. }
  98. func resizeHorizontal(src *image.NRGBA, width int, filter ResampleFilter) *image.NRGBA {
  99. srcBounds := src.Bounds()
  100. srcW := srcBounds.Max.X
  101. srcH := srcBounds.Max.Y
  102. dstW := width
  103. dstH := srcH
  104. dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
  105. weights := precomputeWeights(dstW, srcW, filter)
  106. parallel(dstH, func(partStart, partEnd int) {
  107. for dstY := partStart; dstY < partEnd; dstY++ {
  108. i0 := dstY * src.Stride
  109. j0 := dstY * dst.Stride
  110. for dstX := 0; dstX < dstW; dstX++ {
  111. var r, g, b, a float64
  112. for _, w := range weights[dstX] {
  113. i := i0 + w.index*4
  114. aw := float64(src.Pix[i+3]) * w.weight
  115. r += float64(src.Pix[i+0]) * aw
  116. g += float64(src.Pix[i+1]) * aw
  117. b += float64(src.Pix[i+2]) * aw
  118. a += aw
  119. }
  120. if a != 0 {
  121. aInv := 1 / a
  122. j := j0 + dstX*4
  123. dst.Pix[j+0] = clamp(r * aInv)
  124. dst.Pix[j+1] = clamp(g * aInv)
  125. dst.Pix[j+2] = clamp(b * aInv)
  126. dst.Pix[j+3] = clamp(a)
  127. }
  128. }
  129. }
  130. })
  131. return dst
  132. }
  133. func resizeVertical(src *image.NRGBA, height int, filter ResampleFilter) *image.NRGBA {
  134. srcBounds := src.Bounds()
  135. srcW := srcBounds.Max.X
  136. srcH := srcBounds.Max.Y
  137. dstW := srcW
  138. dstH := height
  139. dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
  140. weights := precomputeWeights(dstH, srcH, filter)
  141. parallel(dstW, func(partStart, partEnd int) {
  142. for dstX := partStart; dstX < partEnd; dstX++ {
  143. for dstY := 0; dstY < dstH; dstY++ {
  144. var r, g, b, a float64
  145. for _, w := range weights[dstY] {
  146. i := w.index*src.Stride + dstX*4
  147. aw := float64(src.Pix[i+3]) * w.weight
  148. r += float64(src.Pix[i+0]) * aw
  149. g += float64(src.Pix[i+1]) * aw
  150. b += float64(src.Pix[i+2]) * aw
  151. a += aw
  152. }
  153. if a != 0 {
  154. aInv := 1 / a
  155. j := dstY*dst.Stride + dstX*4
  156. dst.Pix[j+0] = clamp(r * aInv)
  157. dst.Pix[j+1] = clamp(g * aInv)
  158. dst.Pix[j+2] = clamp(b * aInv)
  159. dst.Pix[j+3] = clamp(a)
  160. }
  161. }
  162. }
  163. })
  164. return dst
  165. }
  166. // resizeNearest is a fast nearest-neighbor resize, no filtering.
  167. func resizeNearest(src *image.NRGBA, width, height int) *image.NRGBA {
  168. dstW, dstH := width, height
  169. srcBounds := src.Bounds()
  170. srcW := srcBounds.Max.X
  171. srcH := srcBounds.Max.Y
  172. dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))
  173. dx := float64(srcW) / float64(dstW)
  174. dy := float64(srcH) / float64(dstH)
  175. parallel(dstH, func(partStart, partEnd int) {
  176. for dstY := partStart; dstY < partEnd; dstY++ {
  177. srcY := int((float64(dstY) + 0.5) * dy)
  178. if srcY > srcH-1 {
  179. srcY = srcH - 1
  180. }
  181. for dstX := 0; dstX < dstW; dstX++ {
  182. srcX := int((float64(dstX) + 0.5) * dx)
  183. if srcX > srcW-1 {
  184. srcX = srcW - 1
  185. }
  186. srcOff := srcY*src.Stride + srcX*4
  187. dstOff := dstY*dst.Stride + dstX*4
  188. copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
  189. }
  190. }
  191. })
  192. return dst
  193. }
  194. // Fit scales down the image using the specified resample filter to fit the specified
  195. // maximum width and height and returns the transformed image.
  196. //
  197. // Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
  198. // CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
  199. //
  200. // Usage example:
  201. //
  202. // dstImage := imaging.Fit(srcImage, 800, 600, imaging.Lanczos)
  203. //
  204. func Fit(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
  205. maxW, maxH := width, height
  206. if maxW <= 0 || maxH <= 0 {
  207. return &image.NRGBA{}
  208. }
  209. srcBounds := img.Bounds()
  210. srcW := srcBounds.Dx()
  211. srcH := srcBounds.Dy()
  212. if srcW <= 0 || srcH <= 0 {
  213. return &image.NRGBA{}
  214. }
  215. if srcW <= maxW && srcH <= maxH {
  216. return Clone(img)
  217. }
  218. srcAspectRatio := float64(srcW) / float64(srcH)
  219. maxAspectRatio := float64(maxW) / float64(maxH)
  220. var newW, newH int
  221. if srcAspectRatio > maxAspectRatio {
  222. newW = maxW
  223. newH = int(float64(newW) / srcAspectRatio)
  224. } else {
  225. newH = maxH
  226. newW = int(float64(newH) * srcAspectRatio)
  227. }
  228. return Resize(img, newW, newH, filter)
  229. }
  230. // Fill scales the image to the smallest possible size that will cover the specified dimensions,
  231. // crops the resized image to the specified dimensions using the given anchor point and returns
  232. // the transformed image.
  233. //
  234. // Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
  235. // CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
  236. //
  237. // Usage example:
  238. //
  239. // dstImage := imaging.Fill(srcImage, 800, 600, imaging.Center, imaging.Lanczos)
  240. //
  241. func Fill(img image.Image, width, height int, anchor Anchor, filter ResampleFilter) *image.NRGBA {
  242. minW, minH := width, height
  243. if minW <= 0 || minH <= 0 {
  244. return &image.NRGBA{}
  245. }
  246. srcBounds := img.Bounds()
  247. srcW := srcBounds.Dx()
  248. srcH := srcBounds.Dy()
  249. if srcW <= 0 || srcH <= 0 {
  250. return &image.NRGBA{}
  251. }
  252. if srcW == minW && srcH == minH {
  253. return Clone(img)
  254. }
  255. srcAspectRatio := float64(srcW) / float64(srcH)
  256. minAspectRatio := float64(minW) / float64(minH)
  257. var tmp *image.NRGBA
  258. if srcAspectRatio < minAspectRatio {
  259. tmp = Resize(img, minW, 0, filter)
  260. } else {
  261. tmp = Resize(img, 0, minH, filter)
  262. }
  263. return CropAnchor(tmp, minW, minH, anchor)
  264. }
  265. // Thumbnail scales the image up or down using the specified resample filter, crops it
  266. // to the specified width and hight and returns the transformed image.
  267. //
  268. // Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
  269. // CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
  270. //
  271. // Usage example:
  272. //
  273. // dstImage := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)
  274. //
  275. func Thumbnail(img image.Image, width, height int, filter ResampleFilter) *image.NRGBA {
  276. return Fill(img, width, height, Center, filter)
  277. }
  278. // ResampleFilter is a resampling filter struct. It can be used to define custom filters.
  279. //
  280. // Supported resample filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
  281. // CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
  282. //
  283. // General filter recommendations:
  284. //
  285. // - Lanczos
  286. // Probably the best resampling filter for photographic images yielding sharp results,
  287. // but it's slower than cubic filters (see below).
  288. //
  289. // - CatmullRom
  290. // A sharp cubic filter. It's a good filter for both upscaling and downscaling if sharp results are needed.
  291. //
  292. // - MitchellNetravali
  293. // A high quality cubic filter that produces smoother results with less ringing than CatmullRom.
  294. //
  295. // - BSpline
  296. // A good filter if a very smooth output is needed.
  297. //
  298. // - Linear
  299. // Bilinear interpolation filter, produces reasonably good, smooth output. It's faster than cubic filters.
  300. //
  301. // - Box
  302. // Simple and fast resampling filter appropriate for downscaling.
  303. // When upscaling it's similar to NearestNeighbor.
  304. //
  305. // - NearestNeighbor
  306. // Fastest resample filter, no antialiasing at all. Rarely used.
  307. //
  308. type ResampleFilter struct {
  309. Support float64
  310. Kernel func(float64) float64
  311. }
  312. // NearestNeighbor is a nearest-neighbor filter (no anti-aliasing).
  313. var NearestNeighbor ResampleFilter
  314. // Box filter (averaging pixels).
  315. var Box ResampleFilter
  316. // Linear filter.
  317. var Linear ResampleFilter
  318. // Hermite cubic spline filter (BC-spline; B=0; C=0).
  319. var Hermite ResampleFilter
  320. // MitchellNetravali is Mitchell-Netravali cubic filter (BC-spline; B=1/3; C=1/3).
  321. var MitchellNetravali ResampleFilter
  322. // CatmullRom is a Catmull-Rom - sharp cubic filter (BC-spline; B=0; C=0.5).
  323. var CatmullRom ResampleFilter
  324. // BSpline is a smooth cubic filter (BC-spline; B=1; C=0).
  325. var BSpline ResampleFilter
  326. // Gaussian is a Gaussian blurring Filter.
  327. var Gaussian ResampleFilter
  328. // Bartlett is a Bartlett-windowed sinc filter (3 lobes).
  329. var Bartlett ResampleFilter
  330. // Lanczos filter (3 lobes).
  331. var Lanczos ResampleFilter
  332. // Hann is a Hann-windowed sinc filter (3 lobes).
  333. var Hann ResampleFilter
  334. // Hamming is a Hamming-windowed sinc filter (3 lobes).
  335. var Hamming ResampleFilter
  336. // Blackman is a Blackman-windowed sinc filter (3 lobes).
  337. var Blackman ResampleFilter
  338. // Welch is a Welch-windowed sinc filter (parabolic window, 3 lobes).
  339. var Welch ResampleFilter
  340. // Cosine is a Cosine-windowed sinc filter (3 lobes).
  341. var Cosine ResampleFilter
  342. func bcspline(x, b, c float64) float64 {
  343. x = math.Abs(x)
  344. if x < 1.0 {
  345. return ((12-9*b-6*c)*x*x*x + (-18+12*b+6*c)*x*x + (6 - 2*b)) / 6
  346. }
  347. if x < 2.0 {
  348. return ((-b-6*c)*x*x*x + (6*b+30*c)*x*x + (-12*b-48*c)*x + (8*b + 24*c)) / 6
  349. }
  350. return 0
  351. }
  352. func sinc(x float64) float64 {
  353. if x == 0 {
  354. return 1
  355. }
  356. return math.Sin(math.Pi*x) / (math.Pi * x)
  357. }
  358. func init() {
  359. NearestNeighbor = ResampleFilter{
  360. Support: 0.0, // special case - not applying the filter
  361. }
  362. Box = ResampleFilter{
  363. Support: 0.5,
  364. Kernel: func(x float64) float64 {
  365. x = math.Abs(x)
  366. if x <= 0.5 {
  367. return 1.0
  368. }
  369. return 0
  370. },
  371. }
  372. Linear = ResampleFilter{
  373. Support: 1.0,
  374. Kernel: func(x float64) float64 {
  375. x = math.Abs(x)
  376. if x < 1.0 {
  377. return 1.0 - x
  378. }
  379. return 0
  380. },
  381. }
  382. Hermite = ResampleFilter{
  383. Support: 1.0,
  384. Kernel: func(x float64) float64 {
  385. x = math.Abs(x)
  386. if x < 1.0 {
  387. return bcspline(x, 0.0, 0.0)
  388. }
  389. return 0
  390. },
  391. }
  392. MitchellNetravali = ResampleFilter{
  393. Support: 2.0,
  394. Kernel: func(x float64) float64 {
  395. x = math.Abs(x)
  396. if x < 2.0 {
  397. return bcspline(x, 1.0/3.0, 1.0/3.0)
  398. }
  399. return 0
  400. },
  401. }
  402. CatmullRom = ResampleFilter{
  403. Support: 2.0,
  404. Kernel: func(x float64) float64 {
  405. x = math.Abs(x)
  406. if x < 2.0 {
  407. return bcspline(x, 0.0, 0.5)
  408. }
  409. return 0
  410. },
  411. }
  412. BSpline = ResampleFilter{
  413. Support: 2.0,
  414. Kernel: func(x float64) float64 {
  415. x = math.Abs(x)
  416. if x < 2.0 {
  417. return bcspline(x, 1.0, 0.0)
  418. }
  419. return 0
  420. },
  421. }
  422. Gaussian = ResampleFilter{
  423. Support: 2.0,
  424. Kernel: func(x float64) float64 {
  425. x = math.Abs(x)
  426. if x < 2.0 {
  427. return math.Exp(-2 * x * x)
  428. }
  429. return 0
  430. },
  431. }
  432. Bartlett = ResampleFilter{
  433. Support: 3.0,
  434. Kernel: func(x float64) float64 {
  435. x = math.Abs(x)
  436. if x < 3.0 {
  437. return sinc(x) * (3.0 - x) / 3.0
  438. }
  439. return 0
  440. },
  441. }
  442. Lanczos = ResampleFilter{
  443. Support: 3.0,
  444. Kernel: func(x float64) float64 {
  445. x = math.Abs(x)
  446. if x < 3.0 {
  447. return sinc(x) * sinc(x/3.0)
  448. }
  449. return 0
  450. },
  451. }
  452. Hann = ResampleFilter{
  453. Support: 3.0,
  454. Kernel: func(x float64) float64 {
  455. x = math.Abs(x)
  456. if x < 3.0 {
  457. return sinc(x) * (0.5 + 0.5*math.Cos(math.Pi*x/3.0))
  458. }
  459. return 0
  460. },
  461. }
  462. Hamming = ResampleFilter{
  463. Support: 3.0,
  464. Kernel: func(x float64) float64 {
  465. x = math.Abs(x)
  466. if x < 3.0 {
  467. return sinc(x) * (0.54 + 0.46*math.Cos(math.Pi*x/3.0))
  468. }
  469. return 0
  470. },
  471. }
  472. Blackman = ResampleFilter{
  473. Support: 3.0,
  474. Kernel: func(x float64) float64 {
  475. x = math.Abs(x)
  476. if x < 3.0 {
  477. return sinc(x) * (0.42 - 0.5*math.Cos(math.Pi*x/3.0+math.Pi) + 0.08*math.Cos(2.0*math.Pi*x/3.0))
  478. }
  479. return 0
  480. },
  481. }
  482. Welch = ResampleFilter{
  483. Support: 3.0,
  484. Kernel: func(x float64) float64 {
  485. x = math.Abs(x)
  486. if x < 3.0 {
  487. return sinc(x) * (1.0 - (x * x / 9.0))
  488. }
  489. return 0
  490. },
  491. }
  492. Cosine = ResampleFilter{
  493. Support: 3.0,
  494. Kernel: func(x float64) float64 {
  495. x = math.Abs(x)
  496. if x < 3.0 {
  497. return sinc(x) * math.Cos((math.Pi/2.0)*(x/3.0))
  498. }
  499. return 0
  500. },
  501. }
  502. }