# Define spacings for Grid when exporting

I want to combine graphics and non-graphics items in a Grid and export the result to an image file (e.g., png). There are good reasons not to use GraphicsGrid, see, e.g., this and this post. But how can I control the vertical spacing between the rows? Here is one example:

im = Grid[{{1, 2, 3}, {Graphics[Circle[]], Graphics[Circle[]],
Graphics[Circle[]]}, {4, 5, 6}}, Spacings -> {0, 0}]


Looks good in the notebook:

but not when I export it

Export["test.png", im, ImageResolution -> 500];


How can I export it just as it is shown in the notebook?

I tried:

Export["/home/felix/test.png", im, ImageResolution -> 500,
ImageSize -> {2000, 1000}, AspectRatio -> 1/2];


yielding a distorted image and AspectRatio has no effect:

• This appears to be a problem with Magnify, or at least that function also exhibits the problem. Mar 2 '17 at 0:17
• You are right, any value larger 3 in Magnify[im, 3] leads to the same distortion. Similarly, ImageResolution->200 works fine, ImageResolution->300 doesn't. As a workaround, is there another way to "magnify" the result to obtain a decent resolution without running into this problem? Mar 2 '17 at 0:25
• Have you tried setting ImageSizeMultipliers -> 1 and/or playing with ItemSize? Providing explicit ImageSize for every Graphics? Mar 2 '17 at 4:26

Magnify also exhibits the problem, e.g.

ImageResize[Rasterize @ Magnify[im, 5], 400]


This seems to be related to The mysterious gap inside Grid.

Since Grid does not work correctly with the built-in method to rescale arbitrary expressions (Magnify) I can only suggest rasterizing the individual grid elements:

rasterize[rez_] :=
Show[Rasterize[#, "Image", ImageResolution -> rez], Magnification -> 1] &;

rasterGrid[Grid[a_, x___], rez_] := Grid[Map[rasterize[rez], a, {2}], x]


Test:

Export["testgrid.png", rasterGrid[im, 300]];

Import["testgrid.png"]


Import["testgrid.png"] // ImageDimensions

{4500, 1679}


Based on Mr. Wizard's observation that the issue is with Magnify, one more option is to export and re-import to a vector graphics format:

im2 = ImportString[ExportString[im, "pdf"]];
Export["test.png", im2, ImageResolution -> 500];


If there are no issues with the pdf export, then the new im2 image can be exported with any resolution. Sometimes, I have the magnify issue also with the pdf export, which I found can be solved by setting ItemSize in the grid explicitly (to small values).

• Good solution! I have exported to PDF and then converted to images outside of Mathematica to handle other glitches; reimporting the Graphics is a nice touch and much more handy. Mar 2 '17 at 2:22