Controlling the Rasterize[] width for notebook-related expressions

喜夏-厌秋 提交于 2019-12-01 07:41:32

If it is practical to use the clipboard in this operation you might use: FrontEnd`CopySpecial["MGF"] (copy as bitmap).

I managed to do this by copying the selection to a new notebook, rasterizing the full notebook, then closing it.

CreatePalette@Button["Preview",
  Module[{target},
   target = 
    CreateDocument[{}, WindowSelected -> False, Visible -> False];
   NotebookWrite[target, NotebookRead[SelectedNotebook[]]];
   CreateDialog[{Rasterize[target], DefaultButton[]}];
   NotebookClose[target]
   ]
  ]

The WindowSize -> 500 option can be added to CreateDocument to set the rasterization width to 500 pixels.


Note some disadvantages (advantages in some cases) of this method compared to copying as bitmap:

  • Custom styles are lost
  • In/Out labels are lost
  • Notebook magnification value is lost

If there's a need, some of these can be remedied by explicitly transferring some notebook options from the SelectedNotebook to the newly created one.

I think this should work without you needing to make a new notebook:

button = Button["Preview", 
   Module[{expr = NotebookRead@InputNotebook[]}, 
    If[expr =!= {}, 
     With[{img = 
        Rasterize[expr, 
         ImageFormattingWidth -> 
          First@(WindowSize /. 
             AbsoluteOptions[InputNotebook[], WindowSize])]}, 
      MessageDialog[
       Column[{"Would you like to perform the action?", 
         img}], {"Do it!" :> doIt[img], "Cancel" :> Null},
       WindowSize -> {First@ImageDimensions@img, All}]]]]];
CreateDialog[button,
 WindowFloating -> True,
 WindowClickSelect -> False,
 Selectable -> False
 ]

I used a little option searcher to find ImageFormattingWidth and by passing the image width as the window width you can make the dialog fit the picture nicely and still display the button.

Here's a demo of its results:

Rasterizing a cell from a pallete

Gregory Klopper

Have you tried using ExportString[] to create the graphic into memory? (technically into a temp file, but what do you care:] )

ExportString[your_mathematica_stuff_here,"PNG",Background->None]

See the output on a colored background to verify transparent BG:

Framed[ImportString[ExportString[x^2,"PNG",Background->None]
                    ,"PNG"]
       ,Background->Yellow]

For images with many color variations (like 3D plots), I recommend JPEG2000 format, and for solid-colored images where transparency is not necessary, use GIF to preserve color detail.

Yes, you can control ImageSize when you export string of the image.


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!