1
$\begingroup$

Here's a simple "save as image" function:

saveImage[image_Graphics, format_String: "png", resolution_Real: 200] := Export[
   TemplateApply[
     "`basename`.`format`", <|
     "basename" -> SymbolName[Unevaluated[image]],
     "format" -> format|
     >]
   , image
   , ImageResolution -> resolution
   ];

However, I can't make it hold the image name:

myImage = Plot[x, {x, 0, 1}]

saveImage@myImage (* evaluates image to be a Graphics object instead of the symbol *)

What do I do wrong?

$\endgroup$
  • 2
    $\begingroup$ Take a look at HoldFirst but then you need to change image_Graphics as you expect _Symbol. $\endgroup$ – Kuba May 21 '18 at 20:56
  • $\begingroup$ @Kuba: indeed this solves the problem. $\endgroup$ – Adobe May 21 '18 at 21:05
1
$\begingroup$

In order to use Unevaluated, saveImage must be held when calling saveImage. So I give saveImage the attribute HoldFirst. From now on, pattern matching won't work anymore for the first argument. That's why I added /; Head[image] === Graphics at the end.

Try this instead:

ClearAll[saveImage];
SetAttributes[saveImage, HoldFirst];
saveImage[image_, format_String: "png", resolution_Real: 200] := 
  Export[TemplateApply[
     "`basename`.`format`", <|
      "basename" -> SymbolName[Unevaluated[image]], 
      "format" -> format|>
     ]
       , image
       , ImageResolution -> resolution
    ] /; Head[image] === Graphics;
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.