Blackberry: Download and display .jpg image - blackberry

I am trying to pull a .jpg image off of a server, and display it as and EncodedImage in a ZoomScreen. Because this .jpg could be very large I want to save the .jpg to a file and read it from there so i don't have the whole thing sitting in memory.
The problem I'm facing is that Connector.open("http.url.com/file.jpg") is either throwing an IOException with the message "Bad Socket Id", or it is throwing a ClassCastException when i attempt to open a FileConnection to the URL. Here is an example of what i've tried:
try {
FileConnection fileIn = (FileConnection)Connector.open(fileURL);
FileConnection fileOut = (FileConnection)Connector.open(fileDest);
if(!fileOut.exists())
fileOut.create();
InputStream is = fileIn.openInputStream();
OutputStream os = fileOut.openOutputStream();
while(fileIn.canRead() && fileOut.canWrite()){
os.write(is.read());
}
is.close();
os.close();
fileIn.close();
fileOut.close();
EncodedImage image = EncodedImage.getEncodedImageResource(fileDest);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(image));
} catch (Exception e) {
e.printStackTrace();
}
I'm getting most of this from RIM, but I'm missing something. I know the url is correct because i use the same format when i stream audio from the same server. The exception is being thrown on the first line, when i attempt to connect to the server.
Does anyone have experience with this?

Figured it out.
try {
HttpConnection conn = (HttpConnection) Connector.open(fileURL);
InputStream fileIn = conn.openInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
for(int i = fileIn.read(); i > -1; i = fileIn.read()){
os.write(i);
}
byte[] data = os.toByteArray();
EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(image));
} catch (Exception e) {
e.printStackTrace();
}
I hope other people will find this useful.

public void run(){
try{
StreamConnection streamC = (StreamConnection) Connector.open(url+";deviceside=true");
InputStream in = streamC.openInputStream();
byte[] data = new byte[4096];
data = IOUtilities.streamToBytes(in);
in.close();
EncodedImage eImage = EncodedImage.createEncodedImage(data, 0, data.length);
}
catch(Exception e)
{
e.printStackTrace();
}

Related

Blackberry convert Base64 data to byte array showing IOException

I have developed the below code to convert base64 string data to byte array but it's showing IOException
public static EncodedImage getProfileByteArray(String profilePic){
byte[] data=profilePic.getBytes();
byte[] base64Data;
Bitmap bitmap=null;
EncodedImage fullImage=null;
try {
base64Data = Base64InputStream.decode(data, 0, data.length);
fullImage = EncodedImage.createEncodedImage(base64Data, 0, base64Data.length);
bitmap = fullImage.getBitmap();
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
System.out.println(e+"lkllllllllllllllll");
}
catch(Exception e){
System.out.println(e+"lkllllllllllllllll");
}
return fullImage;
}
The way is that i am calling a webservice through which i am getting base64 image string and trying to convert this base64 string to byte array to display image in EncodedImage format.
Are you trying to display an image from the url fetched from the webservice? The url is the image returned from the webservice? If that is so, please try the below code and let me know:
public Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url+ ";deviceside=true;ConnectionUID=S TCP");
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}

convert the bytes in to readable string format in blackberry?

I am working on an BB app in which I need to maintain a HTTP connection and with a name of image which is stored on server to get the text written in that image document.
I am getting the response in RTF format.
When I directly hit the server on open browser Chrome, I RTF file get downloaded.
Now I needs to perform that programetically,
1) Either convert the bytes which are coming in response in a simple string format so that I can read that.
or
2) Download the file as its happening on the browser manually so that by reading that file I read the information written in the document.
please suggest me how can I read the data from server by hitting any URL?
Currently I am working with this code:
try {
byte []b = send("new_image.JPG");
String s = new String(b, "UTF-8");
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
public byte[] send(String Imagename) throws Exception
{
HttpConnection hc = null;
String imageName = "BasicExp_1345619462234.jpg";
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open("http://webservice.tvdevphp.com/basisexpdemo/webservices/ocr.php?imgname="+imageName);
hc.setRequestProperty("Content-Type", "multipart/form-data;");
hc.setRequestMethod(HttpConnection.GET);
int ch;
StringBuffer sb= new StringBuffer();
is = hc.openInputStream();
while ((ch = is.read()) != -1)
{
bos.write(ch);
sb.append(ch);
}
System.out.println(sb.toString());
res = bos.toByteArray();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
return res;
}
The response is like:
{\rtf1\ansi\ansicpg1252\uc1\deflang1033\adeflang1033...................
I can read the data but its not formatted, so that i can read that programetically too.
I have done with this task....
Actually the mistake was on server side.
When they were performing OCR, the format parameter was not corrected that was reason.

How to copy database into device in Blackberry

i am developing app for blackberry which have Database as back-end. Database has some data so i am import that database from res to sdcard it is working perfectely in the simulator.
When i install my app into device then it is not working what can be the issue i could not understand. Below is my code..
call Method
DatabseCopy db=new DatabseCopy();
db.copyFile("/nm.db","file:///SDCard/Databases/nm.db");
Method
public void copyFile(String srFile, String dtFile)
{
try
{
FileConnection fconn;
fconn = (FileConnection) Connector.open(dtFile,Connector.READ_WRITE);
if(!fconn.exists()) // if file does not exists , create a new one
{
fconn.create();
}
InputStream is = (InputStream)this.getClass().getResourceAsStream(srFile);
OutputStream os =fconn.openOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
{
os.write(buf, 0, len);
}
is.close();
os.close();
}
catch(IOException e)
{
System.out.println("Exception"+e.getMessage()) ;
}
}
Try this:
Before trying this: you have to check the SDCARD is there or not and
System.getProperty("fileconn.dir.memorycard")
Gives directly the path upto:
file:///SDCard/
and then your filename;
private void copyFromResToSDCard()
{
try
{
InputStream is=(InputStream)getClass().getResourceAsStream("/ManualRecords.db");
FileConnection fileconn=(FileConnection)Connector.open(System.getProperty("fileconn.dir.memorycard")+"ManualRecords.db");//Here set your Path with new fileName.db;
if(fileconn.exists())
{
fileconn.delete();
}
fileconn.create();
byte data[]=new byte[is.available()];
data=IOUtilities.streamToBytes(is);
OutputStream os=fileconn.openOutputStream();
os.write(data);
fileconn.close();
is.close();
os.close();
}
catch (Exception e)
{
System.out.println("=============="+e.getMessage());
}
}
Enough;

Download image in blackberry and display

I use following code to download jpg image and display in blackberry curve 8900 simulator. When I am trying to load my code, it strucks completely and stop responding. Please some one help me.
public DisplayBusinessDetail(String city,Business business)
{
AbsoluteFieldManager absoluteFieldManager = new AbsoluteFieldManager();
absoluteFieldManager.add(new BitmapField(connectServerForImage("http://www.mobileapples.com/Assets/Content/Wallpapers/Blackberry.jpg")),0,0);
add(absoluteFieldManager);
}
public static Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
Thank you in advance
You need to move the socket code off of the main UI event thread. Your code does the download on the UI thread, meaning no UI responsiveness while downloading the bytes.

Save media files to Blackberry SD card

I am creating a multimedia app that allows the user to save wallpapers and ringtones. I know the path I need to save them to is "SDCard/BlackBerry/ringtones/file.mp3" (or "/pictures" for wallpapers). I have searched forums and post for a couple days and the only thing I found was how to write text files. For now, assume that the ringtones and pictures are saved in the projects resource folder. If you could provide any input, I would greatly appreciate it.
Saving anything should be about the same. Try something like this:
FileConnection fc;
try {
String fullFile = usedir + filename;
fc = (FileConnection) Connector.open(fullFile, Connector.READ_WRITE);
if (fc.exists()) {
Dialog.alert("file exists");
} else {
fc.create();
fileOS = fc.openOutputStream();
fileOS.write(raw_media_bytes, raw_offset, raw_length);
}
} catch (Exception x) {
Dialog.alert("file save error);
} finally {
try {
if (fileOS != null) {
fileOS.close();
}
if (fc != null) {
fc.close();
}
} catch (Exception y) {
}
}
usedir and filename are your path components, raw_media_bytes is your data, etc etc.
Thanks for your help cjp. Here is the code to saving a resource mp3 file to a sd card:
byte[] audioFile = null;
try {
Class cl = Class.forName("com.mycompany.myproject.myclass");
InputStream is = cl.getResourceAsStream("/" + audioClip);
audioFile = IOUtilities.streamToBytes(is);
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/ringtones/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/ringtones/" + audioClip, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(audioFile);
outStream.close();
fc.close();
Dialog.alert("Ringtone saved to BlackBerry SDcard.");
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
} catch (Exception e) {
Dialog.alert(e.toString());
}
As cjp pointed out, here is how to save an image resource to a SD card:
EncodedImage encImage = EncodedImage.getEncodedImageResource(file.jpg");
byte[] image = encImage.getData();
try {
// create folder as above (just change directory)
// create file as above (just change directory)
} catch(Exception e){}

Resources