ImagePreview.coffee 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. class ImagePreview extends Class
  2. constructor: ->
  3. @width = 0
  4. @height = 0
  5. @preview_data = ""
  6. @pixel_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  7. getSize: (target_width, target_height) ->
  8. return @calcSize(@width, @height, target_width, target_height)
  9. calcSize: (source_width, source_height, target_width, target_height) ->
  10. width = target_width
  11. height = width * (source_height / source_width);
  12. if height > target_height
  13. height = target_height
  14. width = height * (source_width / source_height)
  15. return [Math.round(width), Math.round(height)]
  16. setPreviewData: (@preview_data) =>
  17. [@width, @height, colors, pixels] = @preview_data.split(",")
  18. getPreviewUri: (target_width=10, target_height=10) ->
  19. @logStart "Render"
  20. [@width, @height, colors, pixels] = @preview_data.split(",")
  21. [width, height] = @getSize(target_width, target_height)
  22. colors = colors.match(/.{3}/g)
  23. pixels = pixels.split("")
  24. canvas = document.createElement("canvas")
  25. canvas.width = width
  26. canvas.height = height
  27. ctx = canvas.getContext('2d')
  28. image_data = ctx.createImageData(width, height)
  29. color_codes = {}
  30. for color, i in colors
  31. color_codes[@pixel_chars[i]] = color
  32. di = 0
  33. for pixel in pixels
  34. hex = color_codes[pixel]
  35. r = parseInt(hex[0], 16) * 17
  36. g = parseInt(hex[1], 16) * 17
  37. b = parseInt(hex[2], 16) * 17
  38. image_data.data[di] = r
  39. image_data.data[di+1] = g
  40. image_data.data[di+2] = b
  41. image_data.data[di+3] = 255
  42. di += 4
  43. #ctx.putImageData(image_data, 1, 0)
  44. #ctx.putImageData(image_data, 0, 1)
  45. ctx.putImageData(image_data, 0, 0)
  46. # Add some blur for more smooth image
  47. canvas2 = document.createElement("canvas")
  48. canvas2.width = width*3
  49. canvas2.height = height*3
  50. ctx = canvas2.getContext('2d')
  51. ctx.filter = "blur(1px)"
  52. ctx.drawImage(canvas, -5, -5, canvas.width*3 + 10, canvas.height*3 + 10)
  53. ctx.drawImage(canvas, 0, 0, canvas.width*3, canvas.height*3)
  54. back = canvas2.toDataURL("image/png")
  55. @logEnd "Render"
  56. return back
  57. window.ImagePreview = ImagePreview