Rasterized image together with vector-graphics axes

Following some of the questions here on Mathematica Stack Exchange, I am trying to export an image that contains a rasterized object and vector-graphics axes.

Here is an example:

myArray = Table[{x, y, RandomReal[]}, {x, 0, 100}, {y, 0, 100}];

size = 500;

myImage =
ListDensityPlot[Flatten[myArray, 1], Mesh -> 20,
ColorFunction -> "AvocadoColors", PerformanceGoal -> "Quality",
FrameLabel -> {"\[Mu]", "C"}, FrameStyle -> Directive[14],
ImageSize -> size];

img = Rasterize[Show[myImage, Frame -> None], ImageResolution -> 100,
ImageSize -> size];

g = Graphics[
Inset[img, Scaled[{0.5, 0.5}], {Center, Center}, size],
AbsoluteOptions[myImage]]


Here is the result::

You can notice, if you compare with the original image, that the scaling of the inserted object is not correct.

Now two my questions:

1. How to figure out the size of the object that I insert automatically. Here, if I replace size with 0.21 size I will get a correct image. Why is 0.21?
2. Why the size of ticks and numbering does not coincide with the original image and how to fix it?
-
You have seen and read the discussion here? – halirutan Oct 27 '12 at 17:26
@halirutan No, I did not find this discussion. Thank you. – Artem Oct 27 '12 at 20:48

The main issue here is that once you rasterize, it no longer remembers the original ticks (or data points) and instead, you have pixels. You will need to map the pixels to the original ticks correctly for them to be aligned. Szabolcs wrote a rasterizeBackground function that keeps vectorized frames/ticks and only rasterizes the "image" part of the plot and shared it a few times in chat. I'll reproduce it here:

rasterizeBackground[g_, res_: 450] :=
Show[Rasterize[
ImageMargins -> 0, LabelStyle -> Opacity[0],
FrameTicksStyle -> Opacity[0], FrameStyle -> Opacity[0],
AxesStyle -> Opacity[0], TicksStyle -> Opacity[0],
PlotRangeClipping -> False], ImageResolution -> res] /.
Raster[data_, rect_, rest__] :>
Raster[data,
Transpose@OptionValue[AbsoluteOptions[g, PlotRange], PlotRange],
rest], Sequence @@ Options[g], Sequence @@ Options[g, PlotRange]]


Using the above, calling rasterizeBackground[myImage] (where myImage is as in the question) results in the following, which is what you were after (note: the desired resolution can be provided using the second argument).

-
Great. Thank you. Is there anything similar for 3D graphics by any chance? – Artem Oct 27 '12 at 20:49
@Artem I'm not aware of anything similar for 3D graphics. I'll ping you if I find something – R. M. Oct 30 '12 at 19:45
@Artem See this thread. – Alexey Popkov Oct 31 '12 at 11:24
@AlexeyPopkov Thank you. – Artem Oct 31 '12 at 12:48
Hi, I have a small follow-up question to this solution: It appears that the PlotRange used is not quite right, there's some alignment issues, especially when using Filling. Anyone find a solution to this minor issue? – Guillochon Jan 4 '13 at 22:21