Last active
January 4, 2016 13:51
-
-
Save 330k/57356f5d5877b690de74 to your computer and use it in GitHub Desktop.
Import and Export Function of Mathematica/CDF Player with JLink
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
Import and Export Function of Mathematica/CDF Player with JLink | |
This function enables Wolfram CDF Player import and export files. | |
Copyright (c) 2015 330k | |
This software is released under the MIT License. | |
http://opensource.org/licenses/mit-license.php | |
*) | |
ImportWithJLink[filepath_?(FileExistsQ[FindFile[#]] &), format_] := ( | |
Needs["JLink`"]; | |
JLink`InstallJava[]; | |
JLink`JavaBlock[ | |
Module[{br, byte, result}, | |
br = JLink`JavaNew["java.io.BufferedInputStream", | |
JLink`JavaNew["java.io.FileInputStream", FindFile@filepath]]; | |
byte = JLink`JavaNew["[B", {FileByteCount[FindFile@filepath]}]; | |
br@read[byte]; | |
result = | |
ImportString[ | |
FromCharacterCode[ | |
JLink`JavaObjectToExpression[byte] /. x_?Negative :> x + 256], | |
format]; | |
br@close[]; | |
result]]); | |
ExportWithJLink[filepath_, string_String, format : "Text"] := ( | |
Needs["JLink`"]; | |
JLink`InstallJava[]; | |
JLink`JavaBlock[ | |
Module[{bw}, | |
bw = JLink`JavaNew["java.io.BufferedWriter", | |
JLink`JavaNew["java.io.FileWriter", filepath] | |
]; | |
bw@write[string]; | |
bw@close[]; | |
filepath | |
] | |
]); | |
ExportWithJLink[filepath_, image_, format : "PNG" | "BMP" | "JPG"] := ( | |
Needs["JLink`"]; | |
JLink`InstallJava[]; | |
JLink`JavaBlock[ | |
JLink`LoadJavaClass["javax.imageio.ImageIO"]; | |
JLink`LoadJavaClass["java.awt.image.BufferedImage"]; | |
Module[{img, bi, width, height}, | |
img = Rasterize[image]; | |
{width, height} = ImageDimensions[img]; | |
bi = JLink`JavaNew["java.awt.image.BufferedImage", | |
width, height, java`awt`image`BufferedImage`TYPEUINTUBGR | |
]; | |
bi@setRGB[0, 0, width, height, | |
Flatten[ | |
Apply[(#1*2^16 + #2*2^8 + #3) &, | |
ImageData[img, "Byte"], {2}]], | |
0, width]; | |
If[javax`imageio`ImageIO`write[bi, format, | |
JLink`JavaNew["java.io.File", filepath]], | |
filepath, $Failed] | |
] | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment