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

3
我有一个图片文件,使用Base64编码(转换为字符串)上传到服务器。服务器将该字符串存储在文本文件中,并给了我指向该文本文件的url。
请问有人可以指导我如何远程获取该文本文件中的编码字符串吗?
1个回答

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;
}

希望这可以帮到你

更新

Android方式

要从Base64字符串获取图像,请使用以下方法:

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

更新2

如果要从服务器读取文本文件,请使用以下方法:

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) {
}

下次请尽量正确地提问。

我在Android或Java中找不到包含类BufferedImage或Base64Decoder的包。 - mohitum
我只是在询问如何获取包含编码字符串的文件内容。 - mohitum
那么问题应该是:“如何从远程服务器加载文本文件并读取其内容”。请检查更新的答案。 - jimpanzer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接