在Java中将Image转换为base64字符串

时间:2016-05-05 08:57:21

标签: java image base64 encode apache-commons-codec

我正在尝试使用apache.commons.codec jar文件将从URL获取的图像文件转换为Base64 String。

Java代码 ..

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;

public class HelloWorld {

public static void main(String args[]) {

     String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
        String destinationFile = "image_1.jpg";

        try {           
            // Reading a Image file from file system
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();

            BufferedInputStream imageInFile = new BufferedInputStream(url.openConnection().getInputStream());
            byte imageData[] = new byte[2048];
            imageInFile.read(imageData);

            // Converting Image byte array into Base64 String
            String imageDataString = encodeImage(imageData);
            System.out.println("imageDataString : " + imageDataString);




            System.out.println("Image Successfully Manipulated!");
        } catch (FileNotFoundException e) {
            System.out.println("Image not found" + e);
        } catch (IOException ioe) {
            System.out.println("Exception while reading the Image " + ioe);
        }

}

public static String encodeImage(byte[] imageByteArray) {
    return Base64.encodeBase64URLSafeString(imageByteArray);
}

}

每当我运行我的代码时,我都会收到以下错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method encodeBase64URLSafeString(byte[]) is undefined for the type Base64

at helloWorld.HelloWorld.encodeImage(HelloWorld.java:51)
at helloWorld.HelloWorld.main(HelloWorld.java:35)

即使在导入Base64类之后,我也无法理解我的错误。请帮助..

修改1

IDE也为方法“encodeImage”

提供以下错误

Error

编辑2:

项目的Java构建路径 build_path

1 个答案:

答案 0 :(得分:0)

根据版本1.4中添加的documentation方法。

仔细检查您正在使用的Jar的版本。