2

In a game that I play called Starbound I'm trying to create a modded item. In the game, the item code is based on JSON strings. An example of a string on an item that I created uses the following JSON to distinguish a drawable item in game:

[{
    "image":"/particles/ash/3.png?setcolor=090909",
    "position":[0,0]
},
    ... and so on for each pixel in the image ...
]

Is there a way that I can take a sprite that has already been created in image editing software in PNG format, keeping transparency, and rasterize the colors and pixel locations into this JSON format? Something like a batch file that converts the PNG image into this format would do. (I could write the JSON manually, but I really don't want to have to do that.)

From what I understand, the game provides some limited set of tiles which you can use to draw your image. In general, I my image should be rasterized into this JSON format based upon their provided tiles:

[ { "image": "tile.png?setcolor=FFFFFF", "position": [X,Y] }, ... ]

(where in this format, the setcolor variable can be any six digit hex-code color).

doppelgreener
  • 4,809
  • 10
  • 46
  • 63
Sandwich
  • 159
  • 4
  • You say you want to keep transparency, but you only have RGB hexes there in your example which don't have capacity to express transparency. How is a partially transparent pixel indicated in this format? Is there an alpha value? Do they use a colour to designate transparency (e.g. magic purple, magic green)? Will we be dealing with partial transparency, or are pixels exclusively either fully transparent or fully opaque? – doppelgreener Jul 04 '15 at 04:42

1 Answers1

1

Use Ruby

You'll need to install two gems: rmagick and color.

The code is fairly short:

require 'Rmagick'
require 'color'
require 'json'

def rasterize_to_json(inImagePath, outJsonPath)
  image = Magick::Image.read(inImagePath)

  pixels = []

  image.each_pixel do |px,col,row|
    hsla = px.to_hsla
    if hsla[3] > 0.75 # ignore pixels that are less than 75% opaque
      # Need to convert the HSL into HTML hex code (dropping the '#')
      hexcode = (Color::HSL.new(*hsla[0,2]).to_rgb.html.upcase)[1,6]
      pixels << { :image => "/tile.png?setcolor=#{hexcode}", :position => [col, row] }
    end
  end

  f = File.new(outJsonPath, "w")
  f.write(pixels.to_json)
  f.close
end

You could add some other bits to make this runnable from the command prompt, or just require it in irb and call the function there.

Community
  • 1
  • 1
Grubermensch
  • 573
  • 1
  • 4
  • 8