Mathematica: Transparent background with PNG

Viewed 6464

This is most likely a bug in Mathematica 8.0.1 and maybe other versions too. Lets try the following:

Table[
 Export[
  "Res_" <> ToString[r] <> ".png", Rasterize[
  Style[x^2 + y^2, 40],
  Background -> None,
  ImageResolution -> r
 ],
 Background -> None],
 {r, {20, 40, 100, 300, 400, 500, 600}}
]

This is a screen shot of what I obtain:

Output

First thing to notice is that the last two pictures are the wrong size. This is fine to some extent since I'm satisfied with a resolution of 300 or above. Now look at this:

in = 72;
G3D = Graphics3D[AspectRatio -> 0.925, Axes -> {True, True, True}, 
  AxesEdge -> {{-1, -1}, {1, -1}, {-1, -1}}, AxesStyle -> Directive[10, Black],
  BaseStyle -> {FontFamily -> "Arial", FontSize -> 12}, Boxed -> False,
  BoxRatios -> {1, 1, 1}, LabelStyle -> Directive[Black], 
  ImagePadding -> All, ImageSize -> 5 in, PlotRange -> All,
  PlotRangePadding -> None, TicksStyle -> Directive[10], 
  ViewPoint -> {2, -2, 2}, ViewVertical -> {0, 0, 1}, Background -> None
];
surf = Show[
  Graphics3D[Sphere[{0, 0, 0}, 1], Background -> None, 
  AxesLabel -> {"x", "y", "z"}], Options[G3D]
];
fig = Show[surf, AxesStyle -> Directive[Opacity[0]], 
  Background -> None
];

I wish to Export fig as a png file with transparent background with a high resolution. Here goes my lame attempt with the always buggy Mathematica.

Table[
  Export[
    "Res_" <> ToString[r] <> ".png",
    Rasterize[fig, ImageResolution -> r, Background -> None],
    Background -> None
  ], {r, {20, 40, 100, 300, 400, 500}}
]

Here is a screenshow of a few png files.

Images

All of them came out with the expected resolution :). But what happened to my transparent background? I have specified many times through my code Background -> None and yet this doesn't want to work. I looked around the web and I found this:

http://forums.wolfram.com/mathgroup/archive/2009/Feb/msg00943.html

Lets use this idea.

bgImage = Image[ConstantArray[{0, 0, 0, 0}, Reverse[ImageDimensions[fig]]], 
  ColorSpace -> "RGB"];
compImage = ImageCompose[bgImage, fig];
Table[Export["Res_" <> ToString[r] <> ".png", 
  Rasterize[compImage, ImageResolution -> r, Background -> None], 
  Background -> None], {r, {20, 40, 100, 300, 400, 500}}]

Images

No backgrounds!!! :) Great. But what happened to the sizes of my images? The resolution is increasing but the image size started to decrease. I have really been messing around with this problem for too long now. I hope one of you can shed some light into this Mathematica bug and can find a hack in order to achieve a transparent background PNG with high resolution. Please mention the Mathematica version you guys are using if you find an answer.

2 Answers
Related