2011-08-18 58 views
2

即時通訊新到Android,上傳Android上通過imgur照片編程

我需要使用,imgur的API,上傳照片,顯然檢索鏈接幫助。

IMGUR API: http://api.imgur.com/resources_anon

進出口新的API與我這麼光禿禿的。

我能夠獲得需要上傳的圖片的URI,但是我如何實現上面的api, 我下載了mime4j和httpmime並將它們添加到庫中,但我似乎無法理解如何使用其中,

我看着這一點,但它讓我感到困惑: Sending images using Http Post

如果有人可以給我一個例子,這將有助於非常多。 謝謝

+0

嘗試看imgur網站上的Java示例 - HTTP://api.imgur。 com/examples#uploading_java – hrickards

+0

IMAGE.IO不存在於android中,那麼我該如何解決? – asd2005

+0

假設您使用位圖存儲圖像,請參閱http://stackoverflow.com/questions/6344694/get-foreground-application-icon-convert-to-base64 – hrickards

回答

3

只是從快速瀏覽imgurthis question,我想出了(幾乎只是將兩者結合)以下內容。讓我知道如果它不起作用。

Bitmap bitmap = yourBitmapHere; 

// Creates Byte Array from picture 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // Not sure whether this should be jpeg or png, try both and see which works best 
URL url = new URL("http://api.imgur.com/2/upload"); 

//encodes picture with Base64 and inserts api key 
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encode(baos.toByteArray(), Base64.DEFAULT).toString(), "UTF-8"); 
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(YOUR_API_KEY, "UTF-8"); 

// opens connection and sends data 
URLConnection conn = url.openConnection(); 
conn.setDoOutput(true); 
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
wr.write(data); 
wr.flush(); 

編輯:看來,我們需要通過Base64.DEFAULT作爲第二選項Base64.encode。更新了上面的例子。

編輯2:您可以使用下面的代碼,根據the oracle site,並報告它所輸出:

BufferedReader in = new BufferedReader(
          new InputStreamReader(
          conn.getInputStream())); 

String inputLine; 

while ((inputLine = ic.readLine()) != null) 
    System.out.println(inputLine); 
in.close(); 
+0

我現在會測試,謝謝 – asd2005

+0

部分,「URLEncoder.encode(Base64.encode(baos.toByteArray()),」UTF-8「);出現了一個問題,Base64.encode(byte [],int)不適用於參數(字節[]) – asd2005

+0

好的。我更新了上面的代碼,但似乎解決方案是將Base64.DEFAULT作爲第二個參數傳遞給Base64.encode。 – hrickards