Add photo from library to contact in wp8.1 - c#

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);
}
}

Related

System.Runtime.InteropServices.COMException occurred in mscorlib.ni.dll but was not handled in user code

I am developing a windows application in 8.1 and I am getting a following error.
my application includes a procedure in which I will be moving a file from local storage to SD card.
My code is as follows
namespace MoveFile
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private async void btnCreateFolder_Click(object sender, RoutedEventArgs e)
{
await ReadFile();
//Error is showing here
**await WriteToFile();
}
public async Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.txtSafakCount.Text.ToCharArray());
//I got the error in this line.....showing interopservice exception
** StorageFolder knownFolder = await KnownFolders.RemovableDevices.CreateFolderAsync("bdfbdfb", CreationCollisionOption.ReplaceExisting);
StorageFolder sdCard = (await knownFolder.GetFoldersAsync()).FirstOrDefault();
// Create a new file named DataFile.txt.
var file = await sdCard.CreateFileAsync("kaaaaammmmfewfwmHoJa.txt", CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
public async Task ReadFile()
{
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
// Get the DataFolder folder.
var dataFolder = await local.GetFolderAsync("DataFolder");
// Get the file.
await dataFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.ReplaceExisting);
var file = await dataFolder.OpenStreamForReadAsync("DataFile.txt");
// Read the data.
using (StreamReader streamReader = new StreamReader(file))
{
this.txtSafakCount.Text = streamReader.ReadToEnd();
}
}
}
}
}
I want to know why this exception occurred and how it can be resolved.
Thanks in advance.
You are doing it wrong - first you should get SD card, then create folder. As the name KnownFolders.RemovableDevices says devices (not single device) - so you get the first of them as SD card (note that Universal Apps are not only for phones). So the working code can look like this:
// first get the SD card
StorageFolder sdCard = (await KnownFolders.RemovableDevices.GetFoldersAsync()).FirstOrDefault();
// then perform some actions - create folders, files ...
StorageFolder myFolder = await sdCard.CreateFolderAsync("bdfbdfb", CreationCollisionOption.ReplaceExisting);
Note also that you also need to add Capabilities in package.appxmanifest file, and Declarations if you want to use files (File Type Associations).
You will also find more help at MSDN.

Setting Windows 8 account picture with .NET/WinRT hybrid

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?

Stream image to file from SavePicker in Windows 8

I need to save Image from Local Storage Folder to file selected from SavePicker.
Should I use stream?
Here is my code:
StorageFile file = await savePicker.PickSaveFileAsync();
if (null != file)
{
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile current_photo = await localFolder.GetFileAsync(img.Tag.ToString());
// TODO Stream from current_photo to file
}
CopyAsync should do it:
await current_photo.CopyAndReplaceAsync(file);

Store image in to StorageFile from image control

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;
}

Saving a stream containing an image to Local folder on Windows Phone 8

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);
}
}

Categories