I would like save a profile picture in a file on localstorage.
With this code retrieval IRandomAccessStreamWithContentType but I don't understand how to save it on disk.
var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();
contactPicker.CommitButtonText = "Select";
var contact = await contactPicker.PickSingleContactAsync();
using (IRandomAccessStreamWithContentType stream = await contact.GetThumbnailAsync())
{
//Save stream on LocalFolder
}
Assuming IRandomAccessStreamWithContentType works like any other stream, this should do the trick:
using (IRandomAccessStreamWithContentType stream = await contact.GetThumbnailAsync())
{
using(FileStream fs = new FileStream("path", FileMode.CreateNew))
{
stream.CopyTo(fs);
}
}
Related
Hi so I'm trying to save an image selected by the user to file so that i can later upload it to my mySQL database.
So I have this code:
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Please pick a selfie"
});
var stream = await result.OpenReadAsync();
resultImage.Source = ImageSource.FromStream(() => stream);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.WriteLine(GetImageBytes(stream).ToString());
}
using (var streamReader = new StreamReader(filename))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}
Here's the GetImageBytes(..) function:
private byte[] GetImageBytes(Stream stream)
{
byte[] ImageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
ImageBytes = memoryStream.ToArray();
}
return ImageBytes;
}
The code kind of works, it creates a file but doesn't save the image. Instead it saves "System.Bytes[]". It saves the name of the object, not the contents of the object.
myfile
enter image description here
Any help would be really appreciated. Thanks!
StreamWriter is for writing formatted strings, not binary data. Try this instead
File.WriteAllBytes(filename,GetImageBytes(stream));
Encode the byte array as a base64 string, then store that in the file:
private string GetImageBytesAsBase64String(Stream stream)
{
var imageBytes;
using (var memoryStream = new System.IO.MemoryStream())
{
stream.CopyTo(memoryStream);
imageBytes = memoryStream.ToArray();
}
return Convert.ToBase64String(imageBytes);
}
If you later need to retrieve the image bytes from the file, you can use the corresponding Convert.FromBase64String(imageBytesAsBase64String) method.
I'm trying to upload a byte array to a mysql column type mediumblob. after the upload I see the blob has a size in kilobytes, however, when I download the file and view it in notepad... it's just empty white space.
here's how I am getting my bytes from an image PNG file:
private async void artworkFileBTN_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
artworkfile = await openPicker.PickSingleFileAsync();
if (artworkfile != null)
{
artworkSet = true;
//var stream = await musicfile.OpenAsync(Windows.Storage.FileAccessMode.Read);
artworkFileBTN.Content = artworkfile.DisplayName;
var stream = await artworkfile.OpenAsync(FileAccessMode.Read);
var streamBytes = await artworkfile.OpenStreamForReadAsync();
var bytes = new byte[(int)streamBytes.Length];
ArtworkRawData =bytes;
}
else
{
//
}
}
can anyone tell me why my array contains only whitespace?
Solved.
byte[] result;
using (Stream streambytes = await artworkfile.OpenStreamForReadAsync())
{
using (var memoryStream = new MemoryStream())
{
streambytes.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}
ArtworkRawData = result;
I would like to ask how I can save image from stream to file. I have created this FileSavePicker, but I don not know how i can save image from Uri
Thanks
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadLine(); // URi with image
private async void saveClick(object sender, RoutedEventArgs e)
{
var Picker = new FileSavePicker();
Picker.FileTypeChoices.Add("Image", new List<string>() { ".jpg" });
StorageFile file = await Picker.PickSaveFileAsync();
}
I assume you already have downloaded the image into dataStream. If not you can do so with the HttpClient class:
var uri = new Uri("http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png");
Windows.Web.Http.HttpClient httpClient = new HttpClient();
var stream = await httpClient.GetInputStreamAsync(uri);
Stream dataStream = stream.AsStreamForRead();
You can get a writeable stream to your picked file by calling OpenStreamForWriteAsync on the StorageFile. With two streams you can call CopyTo to copy from the dataStream to the save stream.
var Picker = new FileSavePicker();
Picker.FileTypeChoices.Add("Image", new List<string>() { ".jpg" });
StorageFile file = await Picker.PickSaveFileAsync();
using (Stream saveStream = await file.OpenStreamForWriteAsync())
{
dataStream.Seek(0, SeekOrigin.Begin);
await dataStream.CopyToAsync(saveStream);
}
I'm trying to convert an old game of mine to windows 8 and I'm having a lot of trouble with my file loading. I'm trying a simple test with DataReader but I don't get the correct values.
First I write like this:
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync("file.dat",CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter writer = new DataWriter(outputStream))
{
try
{
writer.UnicodeEncoding = UnicodeEncoding.Utf8;
writer.ByteOrder = ByteOrder.LittleEndian;
writer.WriteInt32(1);
writer.WriteInt32(2);
await writer.StoreAsync();
writer.DetachStream();
}
catch (IOException)
{
}
}
}
}
Then I read
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync("file.dat");
using (var fileStream = await file.OpenReadAsync())
{
using (IInputStream inputStream = fileStream.GetInputStreamAt(0))
{
using (DataReader reader = new DataReader(inputStream))
{
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
reader.ByteOrder = ByteOrder.LittleEndian;
await reader.LoadAsync((uint)fileStream.Size);
var number = reader.ReadInt32();
var number2 = reader.ReadInt32();
reader.DetachStream();
}
}
}
But I don't get 1 and 2 when I read, just two really big numbers. So, something I missed this is now how you do it? I'm also trying to figure out the best way to work with strings, am I suppose to also write the byte length now as it ask for a "codeUnitCount" when I read?
It just seems like everything is a step back from the old binary reader.
I'm having trouble when creating a StreamWriter object in windows-8, usually I just create an instance just passing a string as a parameter, but in Windows 8 I get an error that indicates that it should recieve a Stream, but I noticed that Stream is an abstract class, Does anybody knows how will be the code to write an xml file?, BTW I'm using .xml because I want to save the serialized object, or does anyone knows how to save to a file a serialized object in Windows 8?.
Any ideas?
Currently using Windows 8 Consumer Preview
Code:
StreamWriter sw = new StreamWriter("person.xml");
Error:
The best overloaded method match for 'System.IO.StreamWriter.StreamWriter(System.IO.Stream)' has some invalid arguments
Instead of StreamWriter you would use something like this:
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
//TODO: Replace "Bytes" with the type you want to write.
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
You can look at the StringIOExtensions class in the WinRTXamlToolkit library for sample use.
EDIT*
While all the above should work - they were written before the FileIO class became available in WinRT, which simplifies most of the common scenarios that the above solution solves since you can now just call await FileIO.WriteTextAsync(file, contents) to write text into file and there are also similar methods to read, write or append strings, bytes, lists of strings or IBuffers.
You can create a common static method which you can use through out application like this
private async Task<T> ReadXml<T>(StorageFile xmldata)
{
XmlSerializer xmlser = new XmlSerializer(typeof(List<myclass>));
T data;
using (var strm = await xmldata.OpenStreamForReadAsync())
{
TextReader Reader = new StreamReader(strm);
data = (T)xmlser.Deserialize(Reader);
}
return data;
}
private async Task writeXml<T>(T Data, StorageFile file)
{
try
{
StringWriter sw = new StringWriter();
XmlSerializer xmlser = new XmlSerializer(typeof(T));
xmlser.Serialize(sw, Data);
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteString(sw.ToString());
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
catch (Exception e)
{
throw new NotImplementedException(e.Message.ToString());
}
}
to write xml simply use
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("data.xml",CreationCollisionOption.ReplaceExisting);
await writeXml(Data,file);
and to read xml use
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.xml");
Data = await ReadXml<List<myclass>>(file);