2011-08-17 78 views
0

當前我正在使用kSoap向C#Web服務發佈數據。現在我已經到了需要使用Base64Binary從我的機器上傳圖像的部分。我搜索了每一個互聯網,但無法提出一個適當的解決方案。Android:Base64示例問題

有一個解決方案與external Base64 class的例子,但我對Android 2.2的原生解決方案感興趣爲there is a API

由於我是新手,我不能自己做。基本上我有一個SD卡文件路徑的圖像,我想將它們轉換成Base64格式上傳。

希望有人能幫助我或指導我正確的文件。

在此先感謝。

回答

0

我想通了這個問題

String Image64 = null; 


     try { 
      Image64 = Base64.encodeToString((getBytesFromFile(new File(path))), DEFAULT); 

     } catch (IOException e) { 
      e.printStackTrace(); 

     } 

//encording 
    public static byte[] getBytesFromFile(File file) throws IOException { 
     InputStream is = new FileInputStream(file); 

     // Get the size of the file 
     long length = file.length(); 

     // You cannot create an array using a long type. 
     // It needs to be an int type. 
     // Before converting to an int type, check 
     // to ensure that file is not larger than Integer.MAX_VALUE. 
     if (length > Integer.MAX_VALUE) { 
      // File is too large 
     } 

     // Create the byte array to hold the data 
     byte[] bytes = new byte[(int)length]; 

     // Read in the bytes 
     int offset = 0; 
     int numRead = 0; 
     while (offset < bytes.length 
       && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { 
      offset += numRead; 
     } 

     // Ensure all the bytes have been read in 
     if (offset < bytes.length) { 
      throw new IOException("Could not completely read file "+file.getName()); 
     } 

     // Close the input stream and return bytes 
     is.close(); 
     return bytes; 
    } 
0

請試試這個,從你指定的鏈接中使用Base64.java。

Bitmap bmImage = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + File.separator + "Your filename"); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bmImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
String encodedString = Base64.encodeBytes(baos.toByteArray()); 

您應該根據您的文件類型更改此Bitmap.CompressFormat.JPEG語句的擴展名。使用下面的代碼

byte[] b; 
b = Base64.decode("base 64 string"); 
final Bitmap unscaledBitmap = BitmapFactory.decodeByteArray(b, 0, b.length); 
+0

這是沒有幫助的可以解碼基地64字符串的形象? – Sandy

+0

我沒有試過對不起。正如我所說我想要本地解決方案。 –