Home > Computer Graphics, Languages, Mathematica, Software > Exporting Pixel-Perfect Graphics in Mathematica

Exporting Pixel-Perfect Graphics in Mathematica

September 2nd, 2008

I keep having to figure out how to export pixel-perfect raster images from Mathematica, which I use for test images with my software. I found that it’s simpler to use ArrayPlot than Raster now, so I’m documenting this for my future use (and any one else’s).
Here’s a simple image function that generates a grid of black pixels alternating with nearly-transparent red pixels. I use this sort of image to ensure that I’m sampling correctly.

imageFunction[x_, y_] :=
 If[BitAnd[x, 1] == BitAnd[y, 1],
  {0, 0, 0, 1},
  {1, 0, 0, 0.01}]

Table then makes a 256 x 128 array of RGBA values from the image function. This is non-square for this example to ensure that the width and height are in the right order later.

imageData = Table[
   imageFunction[x, y],
   {y, 0, 127}, {x, 0, 255}];

ArrayPlot makes the pixel array viewable by converting it into a Graphics. The ColorFunction produces RGBA pixels (the default ignores alpha), PixelConstrained aligns the image to exact pixel boundaries, and ImageSize produces a result that’s exactly the right size.

apic = ArrayPlot[
  imageData,
  ColorFunction -> RGBColor,
  PixelConstrained -> True,
  ImageSize -> Reverse[Take[Dimensions[imageData], 2]]]

This produces the image:

APic.png

Which is then exported like this:

Export["~/Desktop/APic.tif", apic];

The result is a pixel-perfect file resulting from a raster image defined in Mathematica.

Computer Graphics, Languages, Mathematica, Software

Comments are closed.