如何在黑莓中构造BitmapImage

时间:2011-04-19 06:01:18

标签: blackberry

我想从黑莓中的url构造一个BitmapImage。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

尝试使用以下代码:

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

其中 getImageFromUrl(String 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();
        }  

希望这能解决你的问题......:)