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