how to create a photo unique filename for isolated storage - windows-phone-7

I'm adding a Astronomy Picture of The Day to my Windows Phone Astronomy app, and I want to allow users to save the displayed photo to their media library. All of the examples I found show how to do this, but all of the filenames are hard coded and overwrite files that have the existing name. So I need a way to create a unique file name. How can I adjust this example to create a unique filename?
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "fl.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists(tempJPEG))
{
store.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = store.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri("fl.jpg", UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Thanks in advance for any help.

Provided you don't expect multiple saves per second
String tempJPEG = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+".jpg";
Or some variant of that.
Just one way.

Related

How do I read/write image file with its original extension when you receive the image as bytes in Flutter?

Here is the problem I have:
My users can set their profile image either from Facebook (which is a jpeg or gif) or from local device (which could be png or jpg or others).
I get the image from Facebook by using:
// Get the name, email and picture
final graphResponse = await http.get(
'https://graph.facebook.com/v4.0/me?fields=name,email,picture.width(300).height(300)&access_token=$token');
// Decode JSON
final profile = jsonDecode(graphResponse.body);
final String stringData = profile['picture']['data'];
final bytes = Uint8List.fromList(stringData.codeUnits);
And getting image from local device by:
final imagePicker = ImagePicker();
// Call image picker
final pickedFile = await imagePicker.getImage(
source: ImageSource.gallery,
maxWidth: MAX_WIDTH_PROFILE_IMAGE,
);
final imageBytes = await pickedFile.readAsBytes();
Then all I got here are in bytes (Uint8List), how do I save it according to its original extension?
Then later on how do I read them again without checking its extension?
Such as with:
// Setting the filename
// Could be jpg or png or bmp or gif.
// How to determine the extension?
final filename = 'myProfileImage';
// Getting App's local directory
final Directory localRootDirectory =
await getApplicationDocumentsDirectory();
final String filePath = p.join(localRootDirectory.path, path, filename);
final file = File(filePath);
You see, when reading the file we need to specify the full filename. But how to determine the extension then ?
You can avoid dealing with extensions completely by simply not setting an extension in the filename. Extensions only exist to indicate what is likely contained within a file for an OS, but they are not necessary and aren't needed in your case especially since you know that you have some kind of image data in that file and you application is probably the only thing ever using that file.
However, if you really do want to use extensions in the filename, you can use the image package. This provides a Decoder abstract class with multiple implementers for a variety of image encoding methods. To determine which method was used for your file you could check with the isValidFile of each possible decoder type that you need and write an extension accordingly.
Example:
PngDecoder png = PngDecoder();
if(png.isValidFile(data //Uint8List inputted here)) {
print("This file is a PNG");
}

How to copy image from Drawable folder to internal storage ( Xamarin Forms )

I want a method that will allow me to copy an image from the Drawable folder to the internal storage, i searched the internet for solutions but i found some of them that did not work for me like this one :
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, "ic_launcher.PNG");
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close()

Get Images from media library in sequence

I am building app for windows phone 7 ,where i am taking screenshot in every 1 sec and all screenshot's are saving in media library and files name are 1.jpg,2.jpg,3.jpg.........etc. now when i am taking images from library i am getting images randomly like (1.jpg,2.jpg,3.jpg,7.jpg,13.jpg,4.jpg,15.jpg,5.jpg) not in sequence.
how can i get all images in sequence.here is my code
using (MediaLibrary mediaLibrary = new MediaLibrary())
{
PictureCollection AllScreenShot = mediaLibrary.Pictures;
foreach (Picture picture in AllScreenShot)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.DirectoryExists("SavedImg"))
storage.CreateDirectory("SavedImg");
if (storage.FileExists("SavedImg" + "\\" + picture.Name))
storage.DeleteFile("SavedImg" + "\\" + picture.Name);
using (IsolatedStorageFileStream file = storage.CreateFile("SavedImg" + "\\" + picture.Name))
picture.GetImage().CopyTo(file);
}
}
}
Create a list of Images and store all images in a list. It would be like this,
List<Image> listImage = new List<Image>(10); // say 10
listImage.Add(your image Item) in your case its pic 1.jpg; // cast before adding
List<Image> orderedList = listImage.OrderBy(k => k.ToString()).ToList();
Actually its not .ToString(). I declared to make you clear with the concept. In case of Image, you first need to convert it to byte[] and then store the byte[] in list and finally perform OrderBy option which will Order the images in sequence.

Playing a Media File from Isolated Storage

I am reading a wav file saved as a byte stream from a web service and want to play it back when my record is displayed. Phone 7 app.
My approach has been to save the byte stream to a wav file in isolated storage upon navigating to the record and subsequently set the source of my media player (MediaElement1) to that source when a button is clicked and play it back.
Below is my current code in my "PlayButton". (size matches byte stream but no audio results). If I set the stream to a WAV file stored as a resource it does work so perhaps I just need to know how to set the Uri to the Isolated storage file.
(e.g. following code works)
Mediaelement1.Source = new Uri("SampleData\\MyMedia.wav",UriKind.Relative) Works
Mediaelement1.Position = new TimeSpan(0,0,0,0) ;
Mediaelement1.Play() ;
Here is my code sample... any ideas?
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication() ;
IsolatedStorageFileStream str = new IsolatedStorageFileStream(
"MyMedia.wav", FileMode.Open, isf) ;
long size = str.Length;
mediaelement mediaelement = new MediaElement() ;
mediaelement.SetSource(str) ;
mediaElement1.Source = mediaelement.Source ;
mediaElement1.Position = new TimeSpan(0, 0, 0, 0);
mediaElement1.Play();
You shouldn't have to create 2 media elements. Just call .SetSource on mediaElement1 directly.
I have similar code which sets the MediaElement source to a movie in isolated storage and that works fine:
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isfs = new IsolatedStorageFileStream("trailer.wmv", FileMode.Open, isf))
{
this.movie.SetSource(isfs);
}
}
With the above, movie is a MediaElement I've already created in XAML and set autoPlay to true.
I did have a few issues with the above when first getting it working.
I suggest trying the following to help debug:
Ensure that the file has been written to isolated storage correctly and in it's entirety.
Handle the MediaFailed event to find out why it isn't working.
One thing I noticed is that when the device is tethered to the computer the Audio doesn't work... Spent a couple hours with this one when trying to listen to mp3 files.

Read files in Windows Phone 7

I'm trying to open a file in Windows Phone 7, but it says it doesn't exist. Here's the code I'm trying:
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
bool test = file.FileExists("\\ClientBin\\clubs.xml");
And in my project I added a folder called ClientBin, and the clubs.xml is in there. The clubs.xml file properties are:
Build action: Content
Copy to Output Directory: Copy always
I'm not sure what I'm doing wrong. You can see what I have in this screenshot.
Thanks!
When you ship a file with your application, it doesn't get stored in IsolatedStorage. You need use the conventional way of opening a file that ships with the XAP -
XDocument xdoc = XDocument.Load("ClientBin/customers.xml");
var customers = from query in xdoc.Descendants("Customer")
select new Customer
{
Name = (string)query.Element("Name"),
Employees = (int)query.Element("Employees"),
Phone = (string)query.Element("Phone")
};
// Data bind to listbox
listBox1.ItemsSource = customers;
HTH, indyfromoz

Resources