Way to Read/Write photos from the blackberry device [closed] - blackberry

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm trying to create a blackberry app in which I need to take a photo that the user has saved on or taken on their blackberry and then add it to another photo and save the photo so that when the user goes into their saved photos then the new photo is available. I am currently struggling with how to access the user's photos and then saving the new photo in a place where the user can get it and eventually add it as their background image of their phone.

Code to read Images from Device.
public void checkImages(String imagePath) {
String path = "";
if (imagePath.equals(""))
path = "file:///SDCard/";
else
path = imagePath;
try {
FileConnection fileConnection = (FileConnection)Connector.open(path);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list("*", true);
while(directoryEnumerator.hasMoreElements()) {
contentVector.addElement(directoryEnumerator.nextElement());
}
fileConnection.close();
for (int i = 0 ; i < contentVector.size() ; i ++) {
String name = (String) contentVector.elementAt(i);
checkImages(path + name);
}
}
else {
if (path.toLowerCase().endsWith(".jpg")) {
fileConnection.close();
}
}
} catch (Exception ex) { }
}
Code to save image to device..
private void saveBitmap(int picIndex, Bitmap bmp)
{
String PHOTO_DIR = System.getProperty ("fileconn.dir.photos");
String EXTENSION = ".bmp";
String filePath = PHOTO_DIR + picIndex + EXTENSION;
try
{
FileConnection fconn = (FileConnection)Connector.open(filePath, Connector.READ_WRITE);
if(fconn.exists())
fcomm.delete();
fconn.create();
OutputStream outputStream = fconn.openOutputStream();
PNGEncodedImage encodedImage = PNGEncodedImage.encode(bmp);
byte[] imageBytes = encodedImage.getData();
outputStream.write(imageBytes);
outputStream.close();
fconn.close();
}
catch(Exception e){
System.out.println(" Exception while saving Bitmap:: "+e.toString());
}
}
and get help from Read/Write Image.

Related

System.OutOfMemoryException when tried with 70 files SharpZipLib

I have tried zipping 70 pdf documents but ended up having a System.OutOfMemoryException.
Please look into the following code and let me know whats wrong with it.
Please note that I have posted issue on GitHub as well.
public byte[] DownloadPaperList()
{
try
{
PaperDAO paperDAO = new PaperDAO();
List<PaperModel> papers = paperDAO.GetPaperListByPaperIds(paperIDs);
using (MemoryStream outputMemoryStream = new MemoryStream())
{
using (var zipOutputStream = new ZipOutputStream(outputMemoryStream))
{
papers = papers.OrderBy(x => x.Order).ToList();
foreach (PaperModel paper in papers)
{
byte[] decryptedPaper
= CryptoServices.DecryptFile(paper.FileData, paperDAO.GenerateCloseOpenFile(paper, string.Empty), paper.SEVersion);
ZipEntry zipFileEntry = new ZipEntry(paper.DocName + ".pdf")
{
Size = decryptedPaper.Length
};
zipOutputStream.SetLevel(3);
zipOutputStream.PutNextEntry(zipFileEntry); //EXCEPTION THROWS HERE!!!
StreamUtils.Copy(new MemoryStream(decryptedPaper), zipOutputStream, new byte[4096]);
}
zipOutputStream.CloseEntry();
// Stop ZipStream.Dispose() from also Closing the underlying stream.
zipOutputStream.IsStreamOwner = false;
outputMemoryStream.Position = 0;
}
return outputMemoryStream.ToArray();
}
}
catch (Exception)
{
throw;
}
}

How to Upload a Profile photo in base64 format For Community Users Using ConnectApi.UserProfiles.setPhoto

1Am Uploading Profile Photo for Community Users in base64 format By Using ConnectApi.UserProfiles.setPhoto Method. But am getting "ConnectApi.ConnectApiException: The file you uploaded doesn't appear to be a valid image" This error, Help me to Fix this issue.
Hi you can try the below method:
public PageReference upload() {
Blob b;
document.AuthorId = UserInfo.getUserId();
document.FolderId = UserInfo.getUserId(); // put it in running user's folder
try {
document.type = 'jpg';
document.IsPublic = true;
insert document;
// ImageId = '06990000001HnuB';
b = document.Body;
//ConnectApi.ChatterUsers newPhoto = new ConnectApi.ChatterUsers();
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error uploading file'));
return null;
} finally {
document.body = null; // clears the viewstate
document = new Document();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'File uploaded successfully : ' + b));
String communityId = null;
String userId = UserInfo.getUserId();
//ID fileId = ImageId;
// Set photo
ConnectApi.Photo photo = ConnectApi.ChatterUsers.setPhoto(communityId, userId, new ConnectApi.BinaryInput(b, 'image/jpg', 'userImage.jpg'));
return null;
}
I was getting the same error, there isn't too much detail so I'm not too sure about your problem. I solved the problem using the code below. Modify as needed.
public static Boolean updateUserProfilePic(String userProfilePicString, String userId, String fileType){
Boolean updateSuccessful = true;
System.debug('-------------' + userProfilePicString.length());
try{
Blob blobImage = EncodingUtil.base64Decode(userProfilePicString);
ConnectApi.BinaryInput fileUpload = new ConnectApi.BinaryInput(blobImage, 'image/jpg', 'userImage.jpg');
ConnectApi.Photo photoProfile = ConnectApi.UserProfiles.setPhoto(null, userId, fileUpload);
}
catch(Exception exc){
updateSuccessful = false;
}
return updateSuccessful;
}

how to display images present in blackberry device into my application

I am developing a blackberry application where i want to select an image present in device and display it in my application. How to do it.
UPDATE
hi I used FilePicker to get the path of the file and i am storing it in "Selection(String)"
and i am using below code to display image in my application but i am getting exception. can anybody tell me where i did mistake.
try {
FileConnection fconn = (FileConnection)Connector.open(selection,Connector.READ);
// If no exception is thrown, then the URI is valid, but the file may or may not exist.
if (fconn.exists()) {
InputStream input = fconn.openInputStream();
int available = input.available();
byte[] data = new byte[available];
input.read(data, 0, available);
EncodedImage image = EncodedImage.createEncodedImage(data,0,data.length);
Bitmap b = image.getBitmap();
BitmapField picture = new BitmapField(b);
add(picture);
add(new LabelField("Data Length:" + data.length));
}
else {
add(new LabelField("Picture does not exist"));
}
fconn.close();
}
catch (Exception ioe) {
add(new LabelField("Error"));
}
If your target OS is 6.0+ you can use RIM component FilePicker.
For lower OS versions you can use also this component: File Selection Popup

XNA XBOX highscore port

I'm trying to port my pc XNA game to the xbox and have tried to implement xna easystorage alongside my existing pc file management for highscores. Basically trying to combine http://xnaessentials.com/tutorials/highscores.aspx/tutorials/highscores.aspx with http://easystorage.codeplex.com/
I'm running into one specific error regarding the LoadHighScores() as error with 'return (data);' - Use of unassigned local variable 'data'.
I presume this is due to async design of easystorage/xbox!? but not sure how to resolve - below are code samples:
ORIGINAL PC CODE: (works on PC)
public static HighScoreData LoadHighScores(string filename)
{
HighScoreData data; // Get the path of the save game
string fullpath = "Content/highscores.lst";
// Open the file
FileStream stream = File.Open(fullpath, FileMode.Open,FileAccess.Read);
try
{ // Read the data from the file
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
data = (HighScoreData)serializer.Deserialize(stream);
}
finally
{ // Close the file
stream.Close();
}
return (data);
}
XBOX PORT: (with error)
public static HighScoreData LoadHighScores(string container, string filename)
{
HighScoreData data;
if (Global.SaveDevice.FileExists(container, filename))
{
Global.SaveDevice.Load(container, filename, stream =>
{
File.Open(Global.fileName_options, FileMode.Open,//FileMode.OpenOrCreate,
FileAccess.Read);
try
{
// Read the data from the file
XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
data = (HighScoreData)serializer.Deserialize(stream);
}
finally
{
// Close the file
stream.Close();
}
});
}
return (data);
}
Any ideas?
Assign data before return. ;)
data = (if_struct) ? new your_struct() : null;
if (Global.SaveDevice.FileExists(container, filename))
{
......
}
return (data);
}

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