Module: Jsong
- Defined in:
- lib/jsong.rb,
lib/jsong/version.rb
Constant Summary collapse
- DEFAULT =
{ version: '1.0', transparency: true, size: {}, layers: [{ default_color: { red: 0, green: 0, blue: 0, alpha: 255 }, pixels: [] }] }.freeze
- VERSION =
"0.3.0"
Class Method Summary collapse
- .encode_pixel(px) ⇒ Object
- .from_jsong(text, file_name, yaml = false) ⇒ Object
- .rrggbbaa_to_jsong(i) ⇒ Object
- .to_jsong(file_name, comment = nil, yaml = false) ⇒ Object
Class Method Details
.encode_pixel(px) ⇒ Object
77 78 79 80 81 82 |
# File 'lib/jsong.rb', line 77 def Jsong.encode_pixel(px) r, g = px['red'], px['green'] b, a = px['blue'], px['alpha'] ChunkyPNG::Color.rgba(r, g, b, a) end |
.from_jsong(text, file_name, yaml = false) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/jsong.rb', line 57 def Jsong.from_jsong(text, file_name, yaml = false) text = text.read if text.respond_to? :read data = if yaml; YAML.load text; else; JSON.parse text; end default_color = Jsong.encode_pixel data['layers'][-1]['default_color'] w, h = data['size']['width'], data['size']['height'] png = ChunkyPNG::Image.new(w, h, default_color) png.['Title'] = data['comment'] data['layers'].reverse.each do |layer| layer['pixels'].each do |px| x, y = px['position']['x'], px['position']['y'] pixel = Jsong.encode_pixel px['color'] png.set_pixel x, y, pixel end end png.save(file_name, :interlace => true) end |
.rrggbbaa_to_jsong(i) ⇒ Object
84 85 86 87 88 89 90 91 |
# File 'lib/jsong.rb', line 84 def Jsong.rrggbbaa_to_jsong(i) { red: (i / 16777216).floor, green: (i / 65536).floor & 0xFF, blue: (i / 256).floor & 0xFF, alpha: i & 0xFF } end |
.to_jsong(file_name, comment = nil, yaml = false) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/jsong.rb', line 22 def Jsong.to_jsong(file_name, comment = nil, yaml = false) image = ChunkyPNG::Image.from_file file_name if comment.nil? && image.['Title'] comment = image.['Title'] elsif comment.nil? comment = 'Created with ruby Jsong gem' end data = DEFAULT.dup data[:comment] = comment data[:size][:width] = image.width data[:size][:height] = image.height image.pixels.each_slice(image.width).with_index do |arr, y| arr.each_with_index do |pixel, x| data[:layers][0][:pixels] << { position: { x: x, y: y }, color: Jsong.rrggbbaa_to_jsong(pixel), comment: 'A pixel' } end end if yaml data.to_yaml else data.to_json end end |