how can i store image in to StorageFile from image control in windows store apps?
I'm using following link but that is not useful for me
StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync(" ", new Uri(user.ProfilePicUrl), new RandomAccessStream());
http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.storagefile.createstreamedfileasync.aspx
I need clear solution for my problem. How can I do this?
You can use the following method to save an image from an url to a file in LocalFolder:
public async Task<string> DownloadFileAsync(Uri uri, string filename)
{
using (var fileStream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(filename, CreationCollisionOption.ReplaceExisting))
{
var webStream = await new HttpClient().GetStreamAsync(uri);
await webStream.CopyToAsync(fileStream);
webStream.Dispose();
}
return (await ApplicationData.Current.LocalFolder.GetFileAsync(filename)).Path;
}
Related
I'm using FileIO to append Json data in a LocalStorage file.
public static async Task AppendToJsonLocalStorage<T>(string filename, T objectToWrite) where T : new()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
}
AppendTextAsync should only add new text at the end of the existing file, wright ?
Because when I check the file in my file explorer with a text editor it's always overwriting the former text in it.
Use CreationCollisionOption.OpenIfExists instead of CreationCollisionOption.ReplaceExisting when you create the file:
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
ReplaceExisting replaces any existing file as the name suggests. Please refer to the docs for more information.
How to read a formatted text file (say code file) in Windows Phone 8.1 app? I read a text file like this below, but when it has one line comments, for example it messes the whole read content..
private async Task<string> GetFileContent()
{
string str = "";
string strResourceReference = "ms-appx:///Helpers/MyJavaScriptFile.js";
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(strResourceReference, UriKind.Absolute));
Stream sr = await file.OpenStreamForReadAsync();
await FileIO.ReadLinesAsync(file);
foreach (string s in await FileIO.ReadLinesAsync(file))
{
str += s;
}
return str;
}
Since you're just concatenating the individual lines returned by FileIO.ReadLinesAsync, you should call FileIO.ReadTextAsync instead to get all the file contents in a single string from the start. This way you won't need to foreach over them and lose new lines in the process:
private async Task<string> GetFileContent()
{
string strResourceReference = "ms-appx:///Helpers/MyJavaScriptFile.js";
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(strResourceReference, UriKind.Absolute));
using (Stream sr = await file.OpenStreamForReadAsync())
{
return await FileIO.ReadTextAsync(file);
}
}
I also added a using statement to properly close the stream, once you're done reading.
In my windows phone application i'm trying to create a new contact and add an image that taken from the camera, but it didn't seems to work.
No matter what i do the photo is blank.
The only way it works for me is by using an image that i added in the assets folder (and not from camera), even trying to add the image to the local assets folder and then to upload it - don't work...
(there is no error, but the contact that was added don't have a photo).
await contact.SetDisplayPictureAsync(stream.AsStream().AsInputStream());
Here is my code:
when i get the selected image from store i save it to a bitmapImage and use its pixel buffer.
public async void AddContact(string displayName, string mobile, string email, byte[] data)
{
var store = await ContactStore.CreateOrOpenAsync();
var contact = new StoredContact(store)
{
DisplayName = displayName
};
var props = await contact.GetPropertiesAsync();
props.Add(KnownContactProperties.Email, email);
props.Add(KnownContactProperties.MobileTelephone, mobile);
using (var stream = bitmap.PixelBuffer.AsStream())
{
await contact.SetDisplayPictureAsync(stream.AsInputStream());
}
await contact.SaveAsync();
}
Please help!
I was doing the same to set profile picture in for contact and it was not working. But when I get IRandomAccessStream from storage file it worked here is what I am doing
var file = await folder.GetFileAsync("filename.jpeg"));
//Or you can get file direclty from localfolder
// var file = await ApplicationData.Current.LocalFolder.GetFileAsync("filename.jpeg");
using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
await contact.SetDisplayPictureAsync(fileStream);
}
await contact.SaveAsync();
Edit
How to Save picture to local storage using media capture.
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
//Save file to local storage
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"MyPhoto.jpg", CreationCollisionOption.ReplaceExisting);
await mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, file);
Once the image is saved in local storage you can get that image from me first example
Edit 2
If you are using File open picker you can try this.
public async void ContinueFileOpenPicker(Windows.ApplicationModel.Activation.FileOpenPickerContinuationEventArgs args)
{
if (args.Files.Count > 0)
{
var filePath = args.Files[0].Path;
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);
using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
await contact.SetDisplayPictureAsync(fileStream);
}
}
Basically I'm trying to set a Windows 8 account picture from a "Console Application". The only API to set the picture that I found is in the WinRT API. Basically the same question (Windows 8 Set User Account Image) led me at least being able to build the hybrid, but it doesn't seem to be working.
private static async Task SetAccountPicture(string employeeId)
{
// Download image
string imagePath = DownloadImage(employeeId);
// Set account picture
Stream fileStream = File.Open(imagePath, FileMode.Open);
IRandomAccessStream winRTStream = await DotNetToWinRTStream(fileStream);
SetAccountPictureResult result = await UserInformation.SetAccountPicturesFromStreamsAsync(null, winRTStream, null);
// Clean up download file
File.Delete(imagePath);
}
public static async Task<IRandomAccessStream> DotNetToWinRTStream(Stream dotNetStream)
{
IBuffer buffer;
var inputStream = dotNetStream.AsInputStream();
using (var reader = new DataReader(inputStream))
{
await reader.LoadAsync((uint)dotNetStream.Length);
buffer = reader.DetachBuffer();
}
var memoryStream = new InMemoryRandomAccessStream();
await memoryStream.WriteAsync(buffer);
return memoryStream;
}
The SetAccountPictureResult says 'failure' without any other information. What could be happening here?
I'm currently trying to save an stream containing a jpeg image I got back from the camera to the local storage folder. The files are being created but unfortunately contain no data at all. Here is the code I'm trying to use:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(UsefulOperations.StreamToBytes(file));
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
public static class UsefulOperations
{
public static byte[] StreamToBytes(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
Any help saving files this way would be greatly appreciated - all help I have found online refer to saving text. I'm using the Windows.Storage namespace so it should work with Windows 8 too.
Your method SaveToLocalFolderAsync is working just fine. I tried it out on a Stream I passed in and it copied its complete contents as expected.
I guess it's a problem with the state of the stream that you are passing to the method. Maybe you just need to set its position to the beginning beforehand with file.Seek(0, SeekOrigin.Begin);. If that doesn't work, add that code to your question so we can help you.
Also, you could make your code much simpler. The following does exactly the same without the intermediate classes:
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}