What line of code can you use in the Ruby API to export as tif?


#1

I’m trying to write code in the Ruby API to do the equivalent of File>Export>2D Graphic. Is this possible?


#2

Have a look at View#write_image


#3

yes it quite easy…

ask in the dev forum…

john


#4

When I use write_image, it gives true. However, when I go to the directory in which the image is supposed to be located, it isn’t there. Any idea what may be going on?


#5

Can you provide a snippet of the code you are using? It works for me, so you must be doing something different.

PS: moving this topic to the developers category.


#6

you can always check what ruby expects as a path by going to one in Ruby Console…

 UI.openpanel("Open SKP File", "~/Desktop", "*.skp")

john


#7

`model = Sketchup.active_model
view = model.active_view
keys = {
:filename => “C:\Users\Eptri\Desktop\write_image.tif”,
:width => 1616,
:height => 927,
:antialias => false,
:compression => 0.9,
:transparent => true
}
view.write_image(keys)


#8

I believe your problem is with the format of the file path. In Ruby, a backslash in a string is an escape that affects the interpretation of the next character. You need to either use forward slashes (preferred - it will work in Windows) or double up on the backslashes so that Ruby doesn’t mangle the path to your file. I’m on a Mac, but when I simply replace the file path with a valid one on my system, your snippet works.


#9
:filename => File.join( ENV["HOME"].gsub(/\\/,'/'), "Desktop", "image.tif" )

Ruby can also expand "~" into the pathstring specified by the “HOME” environment variable. HOME is always defined under Unix-like OSes (like OSX,) but is named “USERPROFLIE” on PC. So SketchUp has defined a “HOME” alias since SketchUp 2014.

So this can also work, if ENV["HOME"] is defined:

:filename => File.expand_path("Desktop/image.tif","~")

For older SketchUp versions a fallback statement can make sure it is defined.
This leverages that nil is returned for undefined environment variables:

ENV["HOME"]= ENV["USERPROFILE"] if ENV["HOME"].nil?

You can also just change the directory temporarily while doing file operations,
using the block form of the Dir::chdir class method:

  model = Sketchup.active_model
  view  = model.active_view
  path  = File.expand_path("Desktop","~")

  Dir::chdir( path ) {
    view.write_image(
      :filename => "write_image.tif",
      :width => 1616,
      :height => 927,
      :antialias => false,
      :compression => 0.9,
      :transparent => true
    )
  } 
  # the previous working directory is restored after block

You usually can pass hash arguments literally to most methods in Ruby. Ruby will collect them into an anonymous hash and pass it to the method.