resize.go 15 KB

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