resize.go 13 KB

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