如何远程读取Base64编码图像文件

moh*_*tum 3 base64 android

我有一个图像文件,我使用Base64编码上传到服务器(通过转换为字符串).服务器将该字符串存储在文本文件中,并为我提供了该文本文件的URL.

任何人都可以指导我,如何远程从该文本文件中获取编码的字符串?

jim*_*zer 5

使用它来解码/编码(只有Java方式)

public static BufferedImage decodeToImage(String imageString) {

    BufferedImage image = null;
    byte[] imageByte;
    try {
        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}

public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();

        BASE64Encoder encoder = new BASE64Encoder();
        imageString = encoder.encode(imageBytes);

        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助

更新

Android的方式

Base64字符串使用中获取图像

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Run Code Online (Sandbox Code Playgroud)

UPDATE2

要从服务器读取文本文件,请使用:

try {
    URL url = new URL("example.com/example.txt");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Run Code Online (Sandbox Code Playgroud)

下次尝试问正确.