resize.go 14 KB

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