Write byte array to storage file in windows phone - c#

I'm using Visual studio 2012, c#, silverlight, windows phone 8 app.
We get our data from a webservice, and through the webservice we get a picture that is an base64 string.
I convert it to a byte array, and now I want to save it so the Storage of the windows phone, using a memory stream? I don't know if it is the right approach. I don't want to save it to isolated storage, just the local folder because I want to show the picture after a person tapped on the link.
this is what I have so far.
byte[] ImageArray;
var image = Attachmentlist.Attachment.ToString();
imagename = Attachmentlist.FileName.ToString();
ImageArray = Convert.FromBase64String(image.ToString());
StorageFolder myfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
await myfolder.CreateFileAsync(imagename.ToString());
StorageFile myfile = await myfolder.GetFileAsync(imagename.ToString());
MemoryStream ms = new MemoryStream();
so after I have initialized the memory stream how do I take the byte array and write it to the storage file, and after that retrieve it again?

To write file to disc try this code:
StorageFile sampleFile = await myfolder.CreateFileAsync(imagename.ToString(),
CreateCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sampleFile, ImageArray);
Memory stream creates stream that writes in memory so it is not applicable to this problem.

StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile imageFile = await folder.CreateFileAsync("Sample.png", CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
{
using (DataWriter dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(imageBuffer);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
//await outputStream.FlushAsync();
}
//await fileStream.FlushAsync();
}

Related

Add image source from StorageFile UWP

I'm trying to add image source from Storage Folder. First I capture photo and save it to the Storage Folder
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
private async void btnPhoto_Click(object sender, RoutedEventArgs e)
{
// Create the file that we're going to save the photo to.
var file = await storageFolder.CreateFileAsync("sample.jpg", CreationCollisionOption.GenerateUniqueName);
// Update the file with the contents of the photograph.
await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);
}
At the next Page I should get the photo from cache, but I have an exception, when I'm creating sampleFile
public async void GetImage()
{
string filename = "sample.jpg";
Windows.Storage.StorageFile sampleFile =
await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename); // Here I have exception {"Access is denied.\r\n"} System.UnauthoriziedAccessException
BitmapImage img = new BitmapImage();
img = await LoadImage(sampleFile);
image1.Source = img;
}
private static async Task<BitmapImage> LoadImage(StorageFile file)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
return bitmapImage;
}
What I'm doing wrong? And how can I get access to Storage Folder?
You can't access the document library unless the user allows you to do that. You can specify document library access in the manifest, but only for certain files, and such app will probably never be published in the Windows Store unless it REALLY requires that access as stated by Microsoft. As you are using .jpg files you have Pictures library for that, and you can specify it in the manifest and everything will work just fine.
Otherwise you get access by file picker, storing the token to recall it later.

Is this a good way to save stream to file in Universal App, Windows 10?

I use this code to save an Stream to file
StorageFolder coverImageFolder = await StorageFolder.GetFolderFromPathAsync(AppInfo.LF_CoverFolder_Path);
string coverName = System.IO.Path.GetRandomFileName();
// Create an instance of ArchiveReader.
ArchiveReader reader = new ArchiveReader(pickedFile);
// Get a first image (stream) from archive.
using (var imageStream = await reader.GetFirstEntryStream()) { // IRandomAccessStream
// Save ImageStream to 'CoverImage' folder
StorageFile coverFile = await coverImageFolder.CreateFileAsync(coverName);
var coverStream = await coverFile.OpenAsync(FileAccessMode.ReadWrite); // IRandomAccessStream
using (var coverOutputStream = coverStream.AsStreamForWrite()) { // Stream
using (var imageInputStream = imageStream.AsStreamForRead()) { // Stream
await imageInputStream.CopyToAsync(coverOutputStream);
await coverOutputStream.FlushAsync();
}
}
It works as it should be. But, I want to know that is this a good or correct way to save .NET stream to file in Universal App?
If I understand correctly, you were trying to save the imageStream(IRandomAccessStream) to a coverFile(StrorageFile).
AsStreamForWrite and AsStreamForRead are both the Windows Runtime extension methods in .NET. In this case, you don’t need to convert Windows Runtime Stream to .NET IO stream (it will take some extra performance cost). I will suggest you using the way as following (without using .NET class library).
var src = await KnownFolders
.PicturesLibrary
.GetFileAsync("210644575939381015.jpg")
.AsTask();
var target = await KnownFolders
.PicturesLibrary
.CreateFileAsync("new_file.jpg")
.AsTask();
using (var srcStream = await src.OpenAsync(FileAccessMode.Read))
using (var targetStream = await target.OpenAsync(FileAccessMode.ReadWrite))
using (var reader = new DataReader(srcStream.GetInputStreamAt(0)))
{
var output = targetStream.GetOutputStreamAt(0);
await reader.LoadAsync((uint)srcStream.Size);
while (reader.UnconsumedBufferLength > 0)
{
uint dataToRead = reader.UnconsumedBufferLength > 64
? 64
: reader.UnconsumedBufferLength;
IBuffer buffer = reader.ReadBuffer(dataToRead);
await output.WriteAsync(buffer);
}
await output.FlushAsync();
}

Launch PDF from IsolatedStorage in Windows Phone 8.1

My aim is like this:
1. Save PDF to IsolatedStorage
2. Launch it from IsolatedStorage
I have tried all codes, but not getting the output.
My PDF document remains blank. I stuck here, don't getting what is wrong with it
See my code.
Uri uri = new Uri("https://aaaaa.com/aaaa");
WebClient wc = new WebClient();
wc.OpenReadAsync(uri);
wc.OpenReadCompleted += wc_OpenReadCompleted;
async void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length];
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storageFile.OpenFile("Test.pdf", FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile pdffile = await local.GetFileAsync("Test.pdf");
await Windows.System.Launcher.LaunchFileAsync(pdffile);
}
The code seems correct (it's a Windows Phone 8.1 Silverlight). What application use to read the PDF?
I tried same code with the following link http://phonegap2014.azurewebsites.net/wp-content/uploads/2014/10/phonegap-Windows-Universal-App-contest-final-rules.pdf and the official app "PDF Reader" correctly shows local pdf saved.
Try with same or other link and PDF Reader. ;-)

Download and Save image in Pictures Library through Windows 8 Metro XAML App

I am trying to develop a simple Windows 8 Metro app which simply downloads an image file from a given URL (say http://sample.com/foo.jpg) and then save it to Pictures Library.
I have an image control in the UI to display the downloaded image.
I'm also facing difficulty in setting the image source for the image control to the newly downloaded image (actually I'm not even able to download it).
Also, is it possible to store the image file in a particular folder in the Pictures library (if it doesn't exist, then the app should create it)?
I'm really stuck here.
Please help me.
Here's some rough code that I believe accomplishes what you want. It assumes you have two image controls (Image1 and Image2) and that you have the Pictures Library capability checked in the manifest. Take a look at the XAML images sample as well
Uri uri = new Uri("http://www.picsimages.net/photo/lebron-james/lebron-james_1312647633.jpg");
var fileName = Guid.NewGuid().ToString() + ".jpg";
// download pic
var bitmapImage = new BitmapImage();
var httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(uri);
byte[] b = await httpResponse.Content.ReadAsByteArrayAsync();
// create a new in memory stream and datawriter
using (var stream = new InMemoryRandomAccessStream())
{
using (DataWriter dw = new DataWriter(stream))
{
// write the raw bytes and store
dw.WriteBytes(b);
await dw.StoreAsync();
// set the image source
stream.Seek(0);
bitmapImage.SetSource(stream);
// set image in first control
Image1.Source = bitmapImage;
// write to pictures library
var storageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
fileName,
CreationCollisionOption.ReplaceExisting);
using (var storageStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), storageStream.GetOutputStreamAt(0));
}
}
}
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using ( var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read) )
{
bitmapImage.SetSource(pictureStream);
}
Image2.Source = bitmapImage;
}

Create a stream from a bitmap on Windows Runtime

I would like to create a stream from a bitmap. First I did it with :
Stream imgStream = typeof(Main).GetTypeInfo().Assembly.GetManifestResourceStream("ApplicationBlockBase.Assets.testimage.jpg");
But now I need to create a Stream from a local image. Do you have any ideas?
Thanks for your time, regards.
Let me know it this works or not.
StorageFile imageFile = await (await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets")).GetFileAsync("testimage.jpg");
Stream imgStream = await imageFile.OpenStreamForReadAsync();

Categories

Resources