【发布时间】:2014-06-25 20:13:17
【问题描述】:
我想在 Base64 中编码和保存 URL 图像。 我发现了几个从本地文件而不是从 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 文档,确保您准确理解代码中每一行的作用。 -
我知道这是错误的部分。我举了一个例子,它拿了一个文件。但我尝试使用 URL 和 InputStream 来调整它