繁体   English   中英

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

[英]Convert Image to base64 String in Java

我正在尝试使用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”提供以下错误

错误

编辑2:

Java构建项目的路径 build_path

根据1.4版本中添加该方法的文档

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM