我希望能够对来自URL的图片进行Base64编码和保存。 我找到了几个例子可以从本地文件进行编码,但不是从URL中。 有可能做到吗?
我尝试过类似这样的方法,但没有成功。有什么提示或帮助吗? 感谢您的回答。
public static void main(String[] args) {
String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
String destinationFile = "image.jpg";
try {
// Reading a Image file from file system
URL url = new URL(imageUrl);
InputStream is = url.openStream();
FileInputStream imageInFile = new FileInputStream(is.toString());
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);
}
}
/**
* Encodes the byte array into base64 string
*
* @param imageByteArray - byte array
* @return String a {@link java.lang.String}
*/
public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64URLSafeString(imageByteArray);
}
FileInputStream imageInFile = new FileInputStream(is.toString());
这是错误的,阅读API文档,确保您完全理解代码中每一行的作用。 - Jesper