2013-04-26 59 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