2013-04-26 60 views
3

我有一个图像文件,我上传到服务器使用Base64编码(通过转换为字符串)。 服务器将该字符串存储在文本文件中,并将该URL发送给该文本文件。如何阅读Base64远程编码图像文件

任何人都可以指导我,我怎么能从该文本文件远程获得编码的字符串?

回答

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 stri NG使用

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

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

而且在下一次试着问正确的。

+0

我在安卓或java – mohitum 2013-04-26 12:05:10

+0

找不到包含类BufferedImage或Base64Decoder的包哦,对不起,这只是java的方式。检查更新的答案 – jimpanzer 2013-04-26 12:10:40

+0

我只是问如何获取该文件的内容,其中包含编码的字符串 – mohitum 2013-04-26 12:13:33