An External Rasterizer in Mathematica

In a recent post, Jan Korvink was battling to obtain a “precise” Raster[] of some Graphics[] objects. My suggestion is to use an external rasterizer and have the procedure of exporting from Mathematica, converting, and re-importing into Mathematica, fully automatized. GhostScript and ImageMagick are two popular sets of command-line utilities that are available for Windows, Linux, Solaris, and Mac OS X, among others.

The following function provides you with a way to use them from within Mathematica to rasterize any arbitrary graphic object:

Options[Rasterize] = {ImageSize -> 288};
Rasterize[g_, opts___?OptionQ] := With[{
  f = Close@OpenTemporary[],
  fullopts = Join[{opts}, Options@Rasterize]},
    Export[f, g, "EPS"];
    Run@StringForm["sh -l -c 'convert -resize `2` eps:`1` bmp:`1`'",
  f,
  Replace[Replace[ImageSize, fullopts], {
  n_Integer :> StringForm["`1`x`1`", n],
  {x_, y_} :> StringForm["``x``!", x, y]}]];
    With[{bmp = Import[f, "BMP"]},
    DeleteFile[f];
    bmp]]

For instance, you can rasterize a Torus by evaluating the following expressions:

<< Graphics`Shapes`
g = Graphics3D[Torus[],
  Boxed -&gt; False,
  Background -&gt; RGBColor[16^^df/256, 16^^df/256, 16^^c4/256]];
Show[Rasterize[g]]

This produces the following picture:

The rasterized torus