Mathematica: Transparent background with PNG
Asked Answered
N

2

14

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.

Narcoanalysis answered 13/6, 2011 at 3:1 Comment(6)
Just a quick comment. I worked with transparent bkg only a few times, but always did that in the RGBA channel representation.Actual
On version 7, the x^2 + y^2 graphic renders correctly, and the first set of spheres is exported with transparency. Therefore, I have added the mathematica-8 tag.Bechuana
@Mr.Wizard, Do you mean version 7.0.0? I tried the x^2 + y^2 in version 7.0.1 and Res_400.png appears the same as Res_500.png and Res_600.png. Thank you for adding the tag.Narcoanalysis
@belisarius, What do you mean by RGBA channel representation? I checked ColorSpace and the allowed values are "Grayscale", "RGB", "CMYK" and "HSB".Narcoanalysis
See my answer below for the output I get.Bechuana
@Narcoanalysis RGBA is normal RGB with the alpha channel added. Try Graphics3D[{RGBColor[0, 1, 0, .3], Sphere[]}]Actual
H
5

First of all: do not use ImageResolution when exporting! This buggy options is useless most of the time and does not do what one can expect. It works as an analog of ImageSize.

Instead, use Magnify command and Magnification option of Style. They do what we want to get from ImageResolution!

Now about the reason for the behavior showed in the first part of the question. Yes, it happens. And yes, it is machine-dependent. Is it a bug? Yes, at least a great imperfection. It it completely unexpected? As for me - not.

It seems that the source of the problem is that rendering of graphics is in really made by the FrontEnd and the latter uses default settings for Cell when converting graphics to raster.

In[1]:= Options[Cell, PageWidth]
Out[1]= {PageWidth -> WindowWidth}

Lets try to see how output of

Table[Rasterize[Style[x^2 + y^2, 40], Background -> None, 
  ImageResolution -> r], {r, {300, 400, 500, 600}}]

looks at different run-time sizes of the notebook window:

enter image description here

One can see the obvious dependence of the output on the notebook window size.

A workaround is to pass PageWidth directly to Cell:

Rasterize[
 Cell[BoxData@ToBoxes@Style[x^2 + y^2, 40], PageWidth -> Infinity], 
 ImageResolution -> 600]

enter image description here


P.S. In addition. The only case I know when ImageResolution works as expected is PDF export with "AllowRasterization"->True:

First@ImportString[
  ExportString[Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}], "PDF", 
   "AllowRasterization" -> True, ImageResolution -> 200], "PDF"]

But it does not allow to specify transparent background.

Hangup answered 14/6, 2011 at 13:14 Comment(0)
B
0

For the purpose of tracking down the extent of the error, here are the images I get from Mathematica 7.0.1 on Windows XP

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

20: enter image description here

40: enter image description here

100: enter image description here

300: enter image description here

400: enter image description here

500: enter image description here

600: enter image description here


The output that I get for the first method with the spheres appears to match the output that you get with the second method. That is, a transparent background, but different sizes. I will upload these outputs if requested.

Bechuana answered 13/6, 2011 at 5:11 Comment(4)
So the first method in my post results in the output of the second in your machine? This is crazy. Talk about portable code.Narcoanalysis
well, I think I broke my mathematica. I tried to run a code just to try to experiment with the ImageResolution. First it ran fine with imageresultion of 300 then I changed to 500 and it M8 crashed. I tried again back with 300 and it crashed. Restarted my macbook pro, tried again, and it crashed. This must be a sign that I need to go to sleep. Good luck Mr.Wizard. Here is the code I was trying to run: #6302176, oh, set in=72.Narcoanalysis
Never mind. The reason was because in the preferences I changed Antialiasing to highest quality. I changed it back to lowest and it worked. Question: Have you tried to get a transparent background with a pdf file? EDIT: Make a rasterized version of a figure and make the background transparent.Narcoanalysis
@Narcoanalysis regarding raster with alpha in PDF, I have not tried that that I can recall. Why don't you post that as a new question?Bechuana

© 2022 - 2024 — McMap. All rights reserved.