Thursday, April 22, 2010

Fetch image from url in blackberry

First make a class and paste the code as it is.

package reports;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;

public class UrlToImage
{
public static Bitmap _bmap;
UrlToImage(String url)
{
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;

try
{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}

final String result = rawResponse.toString();
dataArray = result.getBytes();
}
catch (final Exception ex)
{ }

finally
{
try
{
inputStream.close();
inputStream = null;
connection.close();
connection = null;
}
catch(Exception e){}
}

bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
// this will scale your image acc. to your height and width of bitmapfield

int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(480));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(360));//width
bitmap = bitmap.scaleImage32(multW,multH);

_bmap=bitmap.getBitmap();
}
public Bitmap getbitmap()
{
return _bmap;

}


}

Now in ur main class where you want to display picture write the code


package reports;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.MainScreen;

public class First extends UiApplication{
public static void main(String[] args)
{
First theapp = new First();
theapp.enterEventDispatcher();

}
public First()
{
pushScreen(new scr());
}

}
class scr extends MainScreen
{
Bitmap bit ;
BitmapField pic;
public scr()
{
String url ="http://www.somesite.image.jpg";
UrlToImage img = new UrlToImage( url);
bit =img.getbitmap();
pic = new BitmapField(bit);
add(pic);

}
}

2 comments:

  1. Do visit.
    http://nileshoppingexperience.blogspot.com/

    ReplyDelete
  2. Thankss Aman ... U rock!!!
    thanks Dude....thanks for urs code
    i was in big trouble..plz b in touch
    manish_prasad143@yahoo.com


    thanks for urs help

    ReplyDelete