Get a file from PhotoGallery and copy it to your directory in your project resources in Titanium(iPhone or ANDROID).

By | May 3, 2011

This example opens the photogallery and then when you select a file from it , it will be copied to your resources directory.
First manually create a directory in your resources, here the directory is named “mydirectory”.
Call this functiion inside a button click or something

var directory = "mydirectory"
 Titanium.Media.openPhotoGallery({
	success:function(event)
	{
		var cropRect = event.cropRect;
		var image = event.media;
		var mime_type = image.mimeType;  	// Getting the file type.....
		var arr = Array();
		arr = mime_type.split('/');
		var image_type = arr[1];
		if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
		{
			var image_name = "My_img""."+arr[1];
			Ti.API.info(image_name);
			var filename = Titanium.Filesystem.resourcesDirectory +  directory + image_name;
			var bgImage = Titanium.Filesystem.getFile(filename);
			bgImage.write(image);                  	//write the image binary to new image file.
	},
	cancel:function()
	{	Ti.API.info(' Cancelled ');		},
	error:function(error)
	{  	Ti.API.info(' An error occurred!! ');	 	},
	allowEditing:true,
	mediaTypes:[Ti.Media.MEDIA_TYPE_PHOTO]
});

Now after running this code check the directory you have created.

If you want to delete the image use this

var file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory +"/"+My_img.png);
file.deleteFile();

Note: Change it to appropriate file extension.

If you want to list all the files inside the directory use this code…

var my_dir = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory+"/");
		var files = my_dir.getDirectoryListing().toString();
		Ti.API.info('directoryListing = ' + files);
		var files_array = Array();
		files_array = gal_files.split(',');
		var num_of_files = files_array.length;

If you want to delete a directory Use this

	var my_dir= Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory+"/");
		 	if(my_dir.exists()){
				var files = gal_dir.getDirectoryListing().toString();
				var files_array = Array();
				files_array = gal_files1.split(',');
				var num_of_files = gal_files_array1.length;

				for(var j = 0; j < num_of_files ; j++){
					var file1 = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+"/"+directory+"/"+files_array[j]);
					file1.deleteFile();
				}
				my_dir.deleteDirectory();
		 	}

Please leave your valuable comments.

One thought on “Get a file from PhotoGallery and copy it to your directory in your project resources in Titanium(iPhone or ANDROID).

  1. Ammar

    Snippet 1 not working for me.

    Titanium SDK = 2.1.1
    Host OS = Mac OS X 10.6.8
    Mobile platform = iOS 5

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *