Here is my code where i am getting profile image bytes from twitter api,
new Thread() {
public void run() {
byte dbata[] = getBitmap(profle_pic_str);
if (dbata != null) {
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
Bitmap image =bitmap_img.getBitmap();
final Bitmap profle_pic_bmp = image;
final Bitmap scld_bmp = new Bitmap(90, 100);
Application.getApplication().invokeLater(new Runnable() {
public void run() {
if (profle_pic_bmp != null) {
profle_pic_bmp.scaleInto(scld_bmp, Bitmap.FILTER_LANCZOS);
phot_profle.setBitmap(scld_bmp);
} else {
Dialog.alert("null");
}
}
});
// } else {
// Dialog.alert("bytes are null");
}
}
}.start();
Here i have method getBitmap(profle_pic_str); which returning bytes array of image,
public byte[] getBitmap(String url) {
Bitmap bitmap = null;
String strg = HttpConnector.getConnectionString();
byte b[] = null;
try {
b = getXML(url + strg);
} catch (IOException ie) {
ie.printStackTrace();
}
return b;
}
the url which i used is this one
http://api.twitter.com/1/users/profile_image?screen_name=screen_nameof_user&size=bigger
public byte[] getXML(String url) throws IOException {
ContentConnection connection =
(ContentConnection) javax.microedition.io.Connector.open(url);
java.io.DataInputStream iStrm = connection.openDataInputStream();
java.io.ByteArrayOutputStream bStrm = null;
byte xmlData[] = null;
try {
// ContentConnection includes a length method
int length = (int) connection.getLength();
if (length != -1) {
xmlData = new byte[length];
// Read the png into an array
// iStrm.read(imageData);
iStrm.readFully(xmlData);
} else // Length not available...
{
bStrm = new java.io.ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) bStrm.write(ch);
xmlData = bStrm.toByteArray();
bStrm.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Clean up
if (iStrm != null) iStrm.close();
if (connection != null) connection.close();
if (bStrm != null) bStrm.close();
}
return xmlData;
}
When i am trying to convert byte array to EncodedImage
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
in this line of code i am getting illegal argument exception.
same code is working for Facebook profile image. I dont know why this code giving error when i am doing for twitter. Please help me friends.
try this -
EncodedImage _encoded_img = EncodedImage.createEncodedImage(dbata, 0, dbata.length);
On your code,
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0,-1);
-1 is the length of the array. Its not static. Change -1 to dbata.length.
Related
I create a app to read ZipArchive(100+ photo),And Use Stream, MemoryStream, IRandomAccessStream, and BinaryReader to setSource of the bitmapImage.
private byte[] GetBytes(ZipArchiveEntry entity)
{
Stream stream = entity.Open();
MemoryStream ms = new MemoryStream();
BinaryReader reader = null;
byte[] imageData = null;
try
{
stream.CopyTo(ms);
imageData = new byte[ms.Length];
string fileclass = "";
reader = new BinaryReader(ms);
ms.Seek(0, 0);
imageData = reader.ReadBytes((int)ms.Length);
//Verify png jpg bmp
some code and return imageData
//throw exception,return null
else
{
throw new Exception();
}
}
catch (Exception ex)
{
return null;
}
//Dispose
}
BitmapImage.SetSource by byte[]
public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
MangaPageEntity mpe = new MangaPageEntity();
mpe.Index = index;
IRandomAccessStream iras = null;
try
{
byte[] data = GetBytes(entity);
iras = data.AsBuffer().AsStream().AsRandomAccessStream();
iras.Seek(0);
await mpe.Picture.SetSourceAsync(iras);
}//catch and dispose
return mpe;
In this way, It use too many memory too run at phone ..
Try to put your streams and other IDisposable into using statement:
private byte[] GetBytes(ZipArchiveEntry entity)
{
using (Stream stream = entity.Open())
using (MemoryStream ms = new MemoryStream())
{
byte[] imageData = null;
try
{
stream.CopyTo(ms);
imageData = new byte[ms.Length];
string fileclass = "";
using (BinaryReader reader = new BinaryReader(ms))
{
ms.Seek(0, 0);
imageData = reader.ReadBytes((int)ms.Length);
}
//Verify png jpg bmp some code and return imageData
//throw exception,return null
else
{
throw new Exception();
}
}
catch (Exception ex)
{
return null;
}
}
//Dispose
}
public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
MangaPageEntity mpe = new MangaPageEntity();
mpe.Index = index;
try
{
byte[] data = GetBytes(entity);
using (IRandomAccessStream iras = data.AsBuffer().AsStream().AsRandomAccessStream())
{
iras.Seek(0);
await mpe.Picture.SetSourceAsync(iras);
}
}//catch and dispose
return mpe;
}
When your code leaves using it calls Dispose(). Some more to read: Uses of “using” in C#, What is the C# Using block and why should I use it? and probably some more.
I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance
I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.
The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate
I am developing a blackberry application which retrieves image from the server , some of images are being retreived and other give error in the encodedImage Line
ImageFromUrl _img = new ImageFromUrl(item.getThumbLink());
byte[] bytes = _img.getbitmap();
Bitmap newBitmap = new Bitmap(width, fieldHeight);
if (bytes != null) {
// bitmap = Bitmap.createBitmapFromBytes(bytes, 0,
// bytes.length, Bitmap.SCALE_TO_FIT);
EncodedImage image = EncodedImage.createEncodedImage(bytes,
0, bytes.length);
}
and that's the connection which get the bytes
ImageFromUrl(String url) {
this.url = url;
}
public byte[] getbitmap() {
try {
connection = (HttpConnection) Connector.open(
url + Connection.getBlackBerryConnectionParams(),
Connector.READ, true);
InputStream is = connection.openInputStream();
DataInputStream dis = new DataInputStream(is);
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = dis.read()) != -1) {
// System.out.println((char) ch);
// msg = msg + (char) ch;
bStrm.write(ch);
}
dataArray = bStrm.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return dataArray;
}
how can I solve that to get all images without errors ?
Try this code:
public Bitmap getBitmapFromUrl(String url)
{
Bitmap bitmap=null;
try
{
HttpConnection connection=(HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
InputStream is=connection.openInputStream();
int length=is.available();
byte[] data=new byte[length];
data=IOUtilities.streamToBytes(is);
connection.close();
is.close();
bitmap=Bitmap.createBitmapFromBytes(data,0,data.length,1);
if(bitmap!=null)
return bitmap;
else
return bitmap=Bitmap.getBitmapResource("noimage.png");
}
catch (Exception e)
{
return bitmap=Bitmap.getBitmapResource("noimage.png");
}
}
I want to get the Bitmap from URL like -
"https://graph.facebook.com/100003506521332/picture"
I tried how-i-can-display-images-from-url-in-blackberry . But its showing http error 302 .It dont showing the Bitmap. How to resolve the problem ?.
String url = "https://graph.facebook.com/100003506521332/picture";
try
{
bitmap = globleDeclaration.getLiveImage(url, 50, 50);
bitmapField.setBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
Dialog.alert(e.getMessage());
}
public Bitmap getLiveImage(String url,int width,int height) throws IOException
{
Bitmap bitmap = null;
try
{
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true);
String location=httpconnection.getHeaderField("location");
if(location!=null){
httpconnection = (HttpConnection) Connector.open(location, Connector.READ, true);
}else{
httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true);
}
inputStream = httpconnection.openInputStream();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = httpconnection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}
final String result = rawResponse.toString();
byte[] dataArray = result.getBytes();
encodeImageBitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
}
catch (final Exception ex)
{
System.out.print("Exception (" + ex.getClass() + "): " + ex.getMessage());
}
finally
{
try
{
inputStream.close();
inputStream = null;
httpconnection.close();
httpconnection = null;
}
catch(Exception e){}
}
return bitmap;
}
If you done get responce from this code httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true); which is mention in above answer than u can also use alternative solution for that..
You can pass your your id here http://graph.facebook.com/100003506521332/?fields=picture&type=large than you will get one json responce like that {"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/70678_100003506521332_1415569305_n.jpg"}
parse this json and get which you want exaclty .. than you will get responce using httpconnection = (HttpConnection) Connector.open(url, Connector.READ, true); also .
if you dont want larger image than remove &type=large from the above url.
//YOUR PACKAGE NAME
package ...........;
//*************************
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.system.Bitmap;
public class Util_ImageLoader {
public static Bitmap getImageFromUrl(String url) {
Bitmap bitmap = null;
try {
String bitmapData = getDataFromUrl(url);
bitmap = Bitmap.createBitmapFromBytes(bitmapData.getBytes(), 0,
bitmapData.length(), 1);
} catch (Exception e1) {
e1.printStackTrace();
}
return bitmap;
}
private static String getDataFromUrl(String url) {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0;
int ch = 0;
try {
c = (HttpConnection) Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
b.append((char) ch);
}
}
is.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
}
return b.toString();
}
}
copy this to your package....
Now, to use this class do like this>>>>>>>>
CREATE BITMAP OBJECT:
Bitmap IMAGE;
After That:
IMAGE=Util_ImageLoader.getImageFromUrl("https://graph.facebook.com/100003506521332/picture");
By the way, I think you have missed extension
like JPG,PNG, on your URL.... Check That
Now, add your bitmap where you would like to display the image......
ENJOY!
add(IMAGE);
My C# application is shooting an image every 3 minutes and I get the image from the EDSDK as expected every time. My problem is that the application is leaking about 5 mb for every shot and Iøm very sure that the problem is the EDSDK.
Code:
private uint CameraObjectEvent(uint inEvent, IntPtr inRef, IntPtr inContext)
{
switch (inEvent)
{
case EDSDK.ObjectEvent_DirItemRequestTransfer:
GetCapturedItem(inRef);
break;
}
return EDSDKErrorCodes.EDS_ERR_OK;
}
private void GetCapturedItem(IntPtr directoryItem)
{
uint error = EDSDKErrorCodes.EDS_ERR_OK;
IntPtr stream = IntPtr.Zero;
//Get information of the directory item.
EDSDK.EdsDirectoryItemInfo dirItemInfo;
error = EDSDK.EdsGetDirectoryItemInfo(directoryItem, out dirItemInfo);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsGetDirectoryItemInfo failed.");
return;
}
//Create a file stream for receiving image.
error = EDSDK.EdsCreateMemoryStream(dirItemInfo.Size, out stream);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsCreateMemoryStream failed");
return;
}
//Fill the stream with the resulting image
error = EDSDK.EdsDownload(directoryItem, dirItemInfo.Size, stream);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsDownload failed.");
return;
}
error = EDSDK.EdsDownloadComplete(directoryItem);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsDownloadComplete failed.");
return;
}
//Copy the stream to a byte[]
IntPtr pointerToBytes = IntPtr.Zero;
EDSDK.EdsGetPointer(stream, out pointerToBytes);
MemoryStream imageStream = null;
Image image = null;
try
{
byte[] buffer = new byte[dirItemInfo.Size];
GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.Copy(pointerToBytes, buffer, 0, (int)dirItemInfo.Size);
//Create a MemoryStream and return the image
imageStream = new MemoryStream(buffer);
image = Image.FromStream(imageStream);
}
catch (Exception ex)
{
OnCameraErrorRaised(999999, string.Format("Failed while retrieving image from camera. Exception: {0}.", ex.Message));
}
finally
{
if (imageStream != null)
imageStream.Dispose();
}
//If image was captured then send ImageCaptured event
if (image != null)
OnImageCaptured(image);
//Clean up
EDSDK.EdsRelease(pointerToBytes);
pointerToBytes = IntPtr.Zero;
EDSDK.EdsRelease(stream);
stream = IntPtr.Zero;
EDSDK.EdsRelease(directoryItem);
directoryItem = IntPtr.Zero;
}
The line OnImageCaptured(image) just sends the image to a controller which merges the image from the camera with another image and then disposes both images after saving the finale merged image:
private void ImageCaptured(Image originalImage)
{
Image watermark = null;
//Merge images
try
{
watermark = Image.FromFile(Settings.Default.ImageWatermarkFilename);
_imageController.Merge(originalImage, watermark);
_imageController.SaveImage(originalImage);
}
catch (Exception ex)
{
LogManager.Instance.UpdateLog(string.Format("Error - Failed to merge and save images. Exception: {0}.", ex.Message));
//HACK:
System.Windows.Forms.Application.Restart();
App.Current.Shutdown();
}
finally
{
originalImage.Dispose();
if (watermark != null)
watermark.Dispose();
}
}
So why does the app memory leak - any ideas?
/Cheers
release your GCHandle. it is the culprit eating memory every time when you are taking shoot
gcHandle.Free()