Skip to content

Commit f4e3287

Browse files
committed
Refactor: Convert from-base64 impl. to Scala
1 parent 4143824 commit f4e3287

2 files changed

Lines changed: 38 additions & 29 deletions

File tree

src/main/BitmapExtension.java

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -116,35 +116,6 @@ public void perform(Argument args[], Context context)
116116
}
117117
}
118118

119-
public static class FromBase64 implements Reporter {
120-
121-
public Syntax getSyntax() {
122-
return SyntaxJ.reporterSyntax(new int[] { Syntax.StringType() }, Syntax.WildcardType());
123-
}
124-
125-
public String getAgentClassString() {
126-
return "OTPL";
127-
}
128-
129-
public Object report(Argument args[], Context context)
130-
throws ExtensionException, LogoException {
131-
String[] splits = args[0].getString().split(",");
132-
if (splits.length != 2) {
133-
throw new ExtensionException("Base 64 string must start with a preamble like 'data:image/png;base64,...'");
134-
}
135-
String base64 = splits[1];
136-
byte[] bytes = Base64.getDecoder().decode(base64);
137-
try {
138-
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
139-
return new LogoBitmap(image);
140-
}
141-
catch (final IOException ex) {
142-
throw new ExtensionException(ex);
143-
}
144-
}
145-
146-
}
147-
148119
public static class ToBase64 implements Reporter {
149120

150121
public Syntax getSyntax() {

src/main/BitmapExtension.scala

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package org.nlogo.extensions.bitmap
2+
3+
import java.io.{ ByteArrayInputStream, IOException }
4+
import java.util.Base64
5+
6+
import javax.imageio.ImageIO
7+
8+
import org.nlogo.api.{ Argument, Context, ExtensionException, Reporter }
9+
import org.nlogo.core.Syntax
10+
11+
class FromBase64 extends Reporter {
12+
13+
def getSyntax: Syntax = Syntax.reporterSyntax(ret = Syntax.WildcardType, right = List(Syntax.StringType))
14+
def getAgentClassString: String = "OTPL"
15+
16+
def report(args: Array[Argument], context: Context): AnyRef = {
17+
18+
val arr = args(0).getString.split(",")
19+
20+
val base64 =
21+
if (arr.length == 2) {
22+
arr(1)
23+
} else {
24+
throw new ExtensionException("This primitive only accepts input that is base64-encoded.")
25+
}
26+
27+
val bytes = Base64.getDecoder().decode(base64)
28+
29+
try {
30+
val image = ImageIO.read(new ByteArrayInputStream(bytes))
31+
new LogoBitmap(image)
32+
} catch {
33+
case ex: IOException => throw new ExtensionException(ex)
34+
}
35+
36+
}
37+
38+
}

0 commit comments

Comments
 (0)