6

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:

enter image description here

but not when I export it

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

enter image description here

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:

enter image description here

Felix
  • 3,871
  • 13
  • 33
  • 1
    This appears to be a problem with Magnify, or at least that function also exhibits the problem. – Mr.Wizard Mar 02 '17 at 00: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? – Felix Mar 02 '17 at 00:25
  • Have you tried setting ImageSizeMultipliers -> 1 and/or playing with ItemSize? Providing explicit ImageSize for every Graphics? – Alexey Popkov Mar 02 '17 at 04:26

2 Answers2

3

Magnify also exhibits the problem, e.g.

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

enter image description here

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"]

enter image description here

Import["testgrid.png"] // ImageDimensions
{4500, 1679}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2

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];

enter image description here

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).

Felix
  • 3,871
  • 13
  • 33
  • 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. – Mr.Wizard Mar 02 '17 at 02:22