imagetobytes.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2017 The Ebiten Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ebiten
  15. import (
  16. "image"
  17. "image/color"
  18. "image/draw"
  19. )
  20. // imageToBytes gets RGBA bytes from img.
  21. //
  22. // Basically imageToBytes just calls draw.Draw.
  23. // If img is a paletted image, an optimized copying method is used.
  24. //
  25. // If img is *image.RGBA and its length is same as 4*width*height, imageToBytes returns its Pix.
  26. func imageToBytes(img image.Image) []byte {
  27. size := img.Bounds().Size()
  28. w, h := size.X, size.Y
  29. switch img := img.(type) {
  30. case *image.Paletted:
  31. bs := make([]byte, 4*w*h)
  32. b := img.Bounds()
  33. x0 := b.Min.X
  34. y0 := b.Min.Y
  35. x1 := b.Max.X
  36. y1 := b.Max.Y
  37. palette := make([]uint8, len(img.Palette)*4)
  38. for i, c := range img.Palette {
  39. rgba := color.RGBAModel.Convert(c).(color.RGBA)
  40. palette[4*i] = rgba.R
  41. palette[4*i+1] = rgba.G
  42. palette[4*i+2] = rgba.B
  43. palette[4*i+3] = rgba.A
  44. }
  45. // Even img is a subimage of another image, Pix starts with 0-th index.
  46. idx0 := 0
  47. idx1 := 0
  48. d := img.Stride - (x1 - x0)
  49. for j := 0; j < y1-y0; j++ {
  50. for i := 0; i < x1-x0; i++ {
  51. p := int(img.Pix[idx0])
  52. bs[idx1] = palette[4*p]
  53. bs[idx1+1] = palette[4*p+1]
  54. bs[idx1+2] = palette[4*p+2]
  55. bs[idx1+3] = palette[4*p+3]
  56. idx0++
  57. idx1 += 4
  58. }
  59. idx0 += d
  60. }
  61. return bs
  62. case *image.RGBA:
  63. if len(img.Pix) == 4*w*h {
  64. return img.Pix
  65. }
  66. return imageToBytesSlow(img)
  67. default:
  68. return imageToBytesSlow(img)
  69. }
  70. }
  71. func imageToBytesSlow(img image.Image) []byte {
  72. size := img.Bounds().Size()
  73. w, h := size.X, size.Y
  74. bs := make([]byte, 4*w*h)
  75. dstImg := &image.RGBA{
  76. Pix: bs,
  77. Stride: 4 * w,
  78. Rect: image.Rect(0, 0, w, h),
  79. }
  80. draw.Draw(dstImg, image.Rect(0, 0, w, h), img, img.Bounds().Min, draw.Src)
  81. return bs
  82. }