How to save stream of image data to the root of the local app data folder in windows phone? - windows-phone-7

I am trying to save the stream of image data to a file. I was able to save it to Pictures library though.
But I want to save it to a file in the root of my application/ project.
I was trying the below but it doesn't work.
using (MediaLibrary mediaLibrary = new MediaLibrary())
mediaLibrary.SavePicture(#"\DefaultScreen.jpg", stream);

In this case you should use LocalStorage.
Here is a simple solution to do this:
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.FileExists(fileName)
{
var sr = Application.GetResourceStream(new Uri(fileName, UriKind.Relative));
using (var br = new BinaryReader(sr.Stream))
{
byte[] data = br.ReadBytes((int)sr.Stream.Length);
string strBaseDir = string.Empty;
const string DelimStr = "/";
char[] delimiter = DelimStr.ToCharArray();
string[] dirsPath = fileName.Split(delimiter);
// Recreate the directory structure
for (int i = 0; i < dirsPath.Length - 1; i++)
{
strBaseDir = Path.Combine(strBaseDir, dirsPath[i]);
isoStore.CreateDirectory(strBaseDir);
}
using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
{
bw.Write(data);
}
}
}
}
Here you can find all info about data in Windows Phone:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402541(v=vs.105).aspx

Related

Creating Excel files directly on blob

I have following function which works fine when saving to disk. I am executing the code from an Azure function. Is there anyway to to write to a blob storage instead without saving to disk?
private void ExportDataSet(DataTable ds, string destination)
{
using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
uint sheetId = 1;
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = "Sites" };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in ds.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (System.Data.DataRow dsrow in ds.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
I would expect you maybe could save to a Stream?
Save to stream is the solution if you don't like to save it to a disk(In azure function, you can save it to a disk in azure function kudu like D:\home etc.).
If you choose to save to stream, just a few changes to your code, like below:
private void ExportDataSet(DataTable ds, MemoryStream memoryStream)
{
using (var workbook = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
//your code logic here
}
//here, the code to upload to azure blob storage.
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("test1");
CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("myexcel.xlsx");
//upload to blob storage
memoryStream.Position = 0;
myblob.UploadFromStream(memoryStream)
//or you can use Asnyc mehtod like myblob.UploadFromStreamAsync(memoryStream)
}
Note: if you're using the latest azure blob storage sdk Microsoft.Azure.Storage.Blob, version 9.4.0 or later, you can use either UploadFromStreamAsync or UploadFromStream method in azure function v2.

Windows 10 Store App - save URI as file

I am writing a Windows 10 Store app. In the app the User can input a Text, and then press "Read Text" and Cortana reads the text loud. That works fine.
Now I want to add the feature, to press a button called "Save" or something like that and then save Cortanas output as mp3 file. This should work via a normal save-file dialog.
This is what I got so far.
private static MediaElement mediaplayer = new MediaElement();
/// ... mediaplayer element gets content ...
Uri file = mediaplayer.Source;
Instead of an Uri element I could also get an SpeechSynthesisStream with this information.
How can I save this Uri / Stream to a file?
EDIT:
this is the final code:
var stream2 = stream.CloneStream();
//... use stream2 as mediaelement ...
if(stream != null)
{
using (var reader = new DataReader(stream))
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("WAV", new List<string>() { ".wav" });
savePicker.SuggestedFileName = "sound.wav";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (var writer = new DataWriter(outputStream.GetOutputStreamAt(0)))
{
long writtenBytes = 0;
const int bufferSize = 8192;
uint loadedBytes = 0;
while ((loadedBytes = (await reader.LoadAsync(bufferSize))) > 0) //!!!
{
IBuffer buffer = reader.ReadBuffer(loadedBytes);
writer.WriteBuffer(buffer);
uint tmpWritten = await writer.StoreAsync(); //!!!
writtenBytes += tmpWritten;
}
}
}
}
}
}
If you're trying to write the output to a file instead (or as well as) rendering it audibly to a MediaElement, you probably want something like this in here as well.
SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);
var stream2 = synthesisStream.CloneStream();
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
savePicker.FileTypeChoices.Add("WAV", new List<string>() { ".wav" });
savePicker.SuggestedFileName = "sound.wav";
StorageFile file = await savePicker.PickSaveFileAsync();
using (var reader = new DataReader(synthesisStream))
{
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (var writer = new DataWriter(outputStream.GetOutputStreamAt(0)))
{
long writtenBytes = 0;
const int bufferSize = 8192;
uint loadedBytes = 0;
while ((loadedBytes = (await reader.LoadAsync(bufferSize))) > 0) //!!!
{
IBuffer buffer = reader.ReadBuffer(loadedBytes);
writer.WriteBuffer(buffer);
uint tmpWritten = await writer.StoreAsync(); //!!!
writtenBytes += tmpWritten;
}
}
}
}
// Set the source and start playing the synthesized audio stream.
media.AutoPlay = true;
media.SetSource(stream2, synthesisStream.ContentType);
media.Play();
The one problem is that the synthesisStream isn't rewindable (so far as I can tell), so you might have to synthesize it twice, or make a second (in memory) copy of the stream if you want to make it audible at the same time.

Random Images in Wp7

I am making an application for windows phone in which i have to display random images whenever the new page is loaded...i am using the following code:-
private Random rand = new Random();
private Image GetRandomImage(string PastScannerResults)
{
string[] files = Directory.GetFiles("/PastScanner/Results");
int i = rand.Next(files.Length);
return Image.FromFile(files[i]);
}
but not getting the results:-(
Please suggest something..Thanks in Advance.
Directory.GetFiles is the syntax for XBOX.
In order to work with files on WP7 you need to use isolated storage.
Something like this should work:
IsolatedStorageFile userFile = IsolatedStorageFile.GetUserStoreForApplication();
var files = userFile.GetFileNames();
Random r = new Random();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(files[r.next(0,files.count], FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.img.Height = bi.PixelHeight;
this.img.Width = bi.PixelWidth;
}
this.img.Source = bi;
public void image_random()
{
List<string> pics = new List<string>()
{
"Assets/1.jpg",
"Assets/2.jpg",
"Assets/3.jpg",
"Assets/4.jpg",
"Assets/5.jpg",
"Assets/6.jpg",
"Assets/7.jpg",
"Assets/8.jpg",
"Assets/9.jpg",
"Assets/10.jpg",
"Assets/11.jpg",
"Assets/12.jpg",
"Assets/13.jpg",
"Assets/14.jpg",
"Assets/15.jpg"
};
Random rnd = new Random();
ImageBrush brush1 = new ImageBrush();
brush1.ImageSource = new BitmapImage(new Uri(pics[rnd.Next(0, 7)],
UriKind.Relative));
ImageBrush brush2 = new ImageBrush();
brush2.ImageSource = new BitmapImage(new Uri(pics[rnd.Next(0, 7)],
UriKind.Relative));
img.Source = brush1.ImageSource;
img1.Source = brush2.ImageSource;
}

How do you get from a byte[] or from a MemoryStream to a System.Windows.Controls.Image in WP7?

I need to make a GET request that requires oauth, for and image to display in a page. Is there a way to do this without building a custom webrequest or httpwebrequest?
If it's an image make sure that you are reading the stream as binary data.
Something like:
var httpRequest = (HttpWebRequest)ar.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(ar);
int lengthInBytes = Convert.ToInt32(httpResponse.ContentLength);
BinaryReader br = new BinaryReader(httpResponse.GetResponseStream());
byte[] imageInBytes = new byte[lengthInBytes];
using (br)
{
for (int i = 0; i < lengthInBytes; i++)
{
imageInBytes[i] = br.ReadByte();
}
}
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
MemoryStream rawBytesStream = new MemoryStream(imageInBytes);
BitmapImage img = new BitmapImage();
img.SetSource(rawBytesStream);
imageInUI.Source = img;
});

In Windows Phone 7 how can I save a BitmapImage to local storage?

In Windows Phone 7 how can I save a BitmapImage to local storage? I need to save the image for caching and reload if it is requested again in the next few days.
If you save the file into IsolatedStorage you can set a relative path to view it from there.
Here's a quick example saving a file that was included in the XAP (as a resource) into Isolated Storage.
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.FileExists(fileName)
{
var sr = Application.GetResourceStream(new Uri(fileName, UriKind.Relative));
using (var br = new BinaryReader(sr.Stream))
{
byte[] data = br.ReadBytes((int)sr.Stream.Length);
string strBaseDir = string.Empty;
const string DelimStr = "/";
char[] delimiter = DelimStr.ToCharArray();
string[] dirsPath = fileName.Split(delimiter);
// Recreate the directory structure
for (int i = 0; i < dirsPath.Length - 1; i++)
{
strBaseDir = Path.Combine(strBaseDir, dirsPath[i]);
isoStore.CreateDirectory(strBaseDir);
}
using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
{
bw.Write(data);
}
}
}
}
You may also be interested in the image caching converters created by Ben Gracewood and Peter Nowaks. They both show saving images into isolated storage and loading them from there.
Another approach I've used is to pass the stream you retrieve for the image in your xap straight into an isolated storage file. Not a lot of moving parts.
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
var bi = new BitmapImage();
bi.SetSource(picStreamFromXap);
var wb = new WriteableBitmap(bi);
using (var isoFileStream = isoStore.CreateFile("pic.jpg"))
Extensions.SaveJpeg(wb, isoFileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}

Resources