4
$\begingroup$

How to show the plot or graphics on the image property of a form or picturebox with NETLink?

(*plotting*)
p1 = Plot[Sin[x],{x,-4,4}];

Needs["NETLink`"];
InstallNET[];

frm = NETNew["System.Windows.Forms.Form"];
frm@BackgroundImage = ReturnAsNetObject@Rasterize[p1] (*not work*)
ShowNETWindow[frm]

ReturnAsNetObject does not work.

$\endgroup$
3
$\begingroup$

... What to do is to follow the .NET rule to make it.

loadImage[plot_] :=
    Module[ {result},
        (*produce file*)
        file = CreateTemporary[];
        Export[file, plot, "GIF"];

        (*get object*)
        LoadNETType["System.Drawing.Image"];
        result = Image`FromFile[file];

        (*clean*)
        DeleteFile[file];(*may catch Privilege problem*)
        (*return as object*)
        Return[result];
    ]

then pass the object produced to the property.

p1 = Plot[Sin[x], {x, -4, 4}];

Needs["NETLink`"];
InstallNET[];

LoadNETType["System.Windows.Forms.ImageLayout"];

frm = NETNew["System.Windows.Forms.Form"];
frm@Width = 500;
frm@Height = 300;
frm@BackgroundImageLayout = ImageLayout`Stretch;
frm@BackgroundImage = loadImage[p1]; (*now ok*)

ShowNETWindow[frm]

enter image description here

However, I don't know would it be efficient on large projects.

Update: use FileStream to avoid priviledge problem.

loadImage2[plot_] :=
 NETBlock@Module[{fs, result},
   (*produce file*)
   file = CreateTemporary[];
   Export[file, plot, "GIF"];

   (*get object*)
   LoadNETType["System.Drawing.Image"];
   LoadNETType["System.IO.FileMode"];
   LoadNETType["System.IO.FileAccess"];

   fs = NETNew["System.IO.FileStream", file, FileMode`Open, 
     FileAccess`Read];
   result = Image`FromStream[fs];

   (*clean*)
   fs@Close[];
   DeleteFile[file];
   (*return as object*)
   Return[result];
   ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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