2011-04-19 60 views

回答

1

嘗試使用以下代碼:

Bitmap img=Bitmap.createBitmapFromBytes((getImageFromUrl(url)).getBytes()), 0,-1, 1); 

其中getImageFromUrl(字符串URL)是從URL獲取圖像的方法。

public static String getImageFromUrl(String url) { 
      //Image img = null; 
      String imageData = null; 
      try 
      {    
       imageData = getDataFromUrl(url); 
       //img = Image.createImage(imageData.getBytes(), 0,imageData.length());   
      } 
      catch(Exception e1) { 
       e1.printStackTrace(); 
      } 

      return imageData; 
     } 

     public static String getDataFromUrl(String url) 
       throws IOException { 

      StringBuffer b = new StringBuffer(); 
      InputStream is = null; 
      HttpConnection c = null; 

      long len = 0 ; 
      int ch = 0; 

      ConnectionFactory connFact = new ConnectionFactory(); 
       ConnectionDescriptor connDesc; 
       connDesc = connFact.getConnection(url); 

       if (connDesc != null) 
       { 
        //HttpConnection httpConn; 
        c = (HttpConnection)connDesc.getConnection(); 
       } 

      // c = (HttpConnection)Connector.open(url); 
      is = c.openInputStream(); 
      len = c.getLength(); 
      if(len != -1) { 
       // Read exactly Content-Length bytes 
       for(int i =0 ; i < len ; i++) 
        if((ch = is.read()) != -1) { 
        b.append((char) ch); 
        } 
      } else { 
       //Read until the connection is closed. 
       while ((ch = is.read()) != -1) { 
        len = is.available() ; 
        b.append((char)ch); 
       } 
      } 

      is.close(); 
      c.close(); 
      return b.toString(); 
     } 

希望這將解決您的問題... :)

+2

只是想標記一個珍聞到這一點。由於這是使用HTTP調用,所以請確保您在自己的Thread中運行此操作,因爲它是阻止調用。 – jprofitt 2011-04-19 13:29:29