Base 64 encoding an image file in Groovy using Apache Commons

2.1k views Asked by At

I am trying to encode an image file to a Base64 String using the directions on this site. The only difference is I have a groovy script (instead of Java), my entire script is just....

  @Grapes(
    @Grab(group='commons-io', module='commons-io', version='2.6')
  )

 import org.apache.commons.io.FileUtils
 import org.apache.commons.codec.binary.Base64


  byte[] fileContent = FileUtils.readFileToByteArray(new File('/Users/me/Test.jpeg'));
  String encodedString = Base64.getEncoder().encodeToString(fileContent);

When I run this I get the below exception and can't figure out why...

 groovy.lang.MissingMethodException: 
 No signature of method: static org.apache.commons.codec.binary.Base64.getEncoder() is applicable for argument types: () values: []
 Possible solutions: encode([B), encode(java.lang.Object)
1

There are 1 answers

0
aventurin On

You're importing org.apache.commons.codec.binary.Base64.

With Base64.getEncoder().encodeToString(fileContent) you're calling java.util.Base64, which has methods other than org.apache.commons.codec.binary.Base64.

Since java.util.* is one of Groovy's default imports your code should work when you remove import org.apache.commons.codec.binary.Base64.