Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.09 KB | None | 0 0
  1.     public static String encodeToString(BufferedImage image)
  2.     {
  3.         String imageString = null;
  4.         ByteArrayOutputStream bos = new ByteArrayOutputStream();
  5.         try
  6.         {
  7.             ImageIO.write(image, "png", bos);
  8.             byte[] imageBytes = bos.toByteArray();
  9.             BASE64Encoder encoder = new BASE64Encoder();
  10.             imageString = encoder.encode(imageBytes);
  11.             bos.close();
  12.         } catch (IOException e) {
  13.             e.printStackTrace();
  14.         }
  15.         return imageString;
  16.     }
  17.    
  18.     public static String imgurUpload(BufferedImage image) throws Exception
  19.     {
  20.         String clientID = "790910198fb7921";
  21.         //create needed strings
  22.         String address = "https://api.imgur.com/3/image.json";
  23.    
  24.         //Create HTTPClient and post
  25.         HttpClient client = new DefaultHttpClient();
  26.         HttpPost post = new HttpPost(address);
  27.    
  28.         String dataImage = encodeToString(image);
  29.         //add header
  30.         post.addHeader("Authorization", "Client-ID " + clientID);
  31.         //add image
  32.         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
  33.         nameValuePairs.add(new BasicNameValuePair("image", dataImage));
  34.         post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  35.  
  36.         //execute
  37.         HttpResponse response = client.execute(post);
  38.  
  39.         //read response
  40.         BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
  41.  
  42.         //loop through response
  43.         String line = rd.readLine();
  44.         StringBuffer sb = new StringBuffer();
  45.         while (line != null)
  46.         {
  47.             sb.append(line);
  48.             line = rd.readLine();
  49.         }
  50.         String all = sb.toString();
  51.         JSONObject jo = new JSONObject(all);
  52.         JSONObject data = jo.getJSONObject("data");
  53.        
  54.         String link = null;
  55.         if (data.has("link"))
  56.         {
  57.             link = data.getString("link");
  58.         } else if (data.has("error")) {
  59.             link = data.getString("error");
  60.         }
  61.         return link;
  62.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement