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.4.0"
Class Method Summary collapse
-
.encode_pixel(px) ⇒ ChunkyPNG::Color
Converts a single pixel hash to a chunky png pixel.
-
.from_jsong(text, file_name, yaml: false) ⇒ nil
Converts JSON-G or YAML-G data to an image.
-
.rrggbbaa_to_jsong(i) ⇒ Hash<String => Integer>
Converts an integer to JSON-G hash.
-
.to_jsong(file_name, comment: nil, pixel_comment: nil, yaml: false) ⇒ String
Converts a PNG image to JSON-G or YAML-G.
Class Method Details
.encode_pixel(px) ⇒ ChunkyPNG::Color
Converts a single pixel hash to a chunky png pixel.
96 97 98 99 100 101 |
# File 'lib/jsong.rb', line 96 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) ⇒ nil
Converts JSON-G or YAML-G data to an image.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/jsong.rb', line 71 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) ⇒ Hash<String => Integer>
Converts an integer to JSON-G hash.
108 109 110 111 112 113 114 115 |
# File 'lib/jsong.rb', line 108 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, pixel_comment: nil, yaml: false) ⇒ String
Converts a PNG image to JSON-G or YAML-G.
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 56 57 58 59 60 61 62 |
# File 'lib/jsong.rb', line 29 def Jsong.to_jsong(file_name, comment: nil, pixel_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: pixel_comment || 'A pixel' } end end if yaml data.to_yaml else data.to_json end end |