How to save a picture from PhotoChooserTask - c#

I would like to save a photo selected with the PhotoChooserTask, but I am unsure of the proper method. So far, I have implemented the PhotoChooserTask_Completed method, but what is the proper method to save this to a bitmap?
EDIT: added basic implementation. The goal is to update a hubtile image to an image that the user selects from the PhotoChooserTask.
Note: I have placed the Settings class and TileItem class at the bottom for quick reference.
MainPage.xaml
string shareJPEG = "shareImage.jpg";
string linkJPEG = "linkImage.jpg";
BitmapImage shareImg;
BitmapImage linkImg;
public MainPage()
{
InitializeComponent();
CreateHubTiles();
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
}
public void CreateHubTiles()
{
if (Settings.shareImageUpdated.Value == true)
{
//Settings.shareImage.Value = new BitmapImage();
shareImg = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(shareJPEG, FileMode.Open, FileAccess.Read))
{
//Settings.shareImage.Value.SetSource(fileStream);
shareImg.SetSource(fileStream);
//this.img.Height = bi.PixelHeight;
//this.img.Width = bi.PixelWidth;
}
}
//this.img.Source = bi;
}
else
{
//Settings.shareImage.Value = new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative));
shareImg = new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative));
}
if (Settings.linkImageUpdated.Value == true)
{
//Settings.linkImage.Value = new BitmapImage();
linkImg = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(linkJPEG, FileMode.Open, FileAccess.Read))
{
//Settings.linkImage.Value.SetSource(fileStream);
linkImg.SetSource(fileStream);
//this.img.Height = bi.PixelHeight;
//this.img.Width = bi.PixelWidth;
}
}
//this.img.Source = bi;
}
else
{
//Settings.linkImage.Value = new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative));
linkImg = new BitmapImage(new Uri("/Images/shareLinkImage.jpg", UriKind.Relative));
}
List<TileItem> tileItems = new List<TileItem>()
{
//new TileItem() { ImageUri = Settings.shareImage.Value, Title = "status", /*Notification = "last shared link uri",*/ Message = Settings.statusMessage.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Status_Title },
new TileItem() { ImageUri = shareImg, Title = "status", /*Notification = "last shared link uri",*/ Message = Settings.statusMessage.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Status_Title },
//new TileItem() { ImageUri = Settings.linkImage.Value, Title = "link", /*Notification = "last shared status message",*/ Message = Settings.linkUri.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Link_Title },
new TileItem() { ImageUri = linkImg, Title = "link", /*Notification = "last shared status message",*/ Message = Settings.linkUri.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Link_Title },
};
this.tileList.ItemsSource = tileItems;
}
public void changePictureMenuItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var menuItem = (MenuItem)sender;
tileItem = menuItem.DataContext as TileItem; //for PhotoChooserTask_Completed
try
{
photoChooserTask.Show();
}
catch (System.InvalidOperationException ex)
{
//MessageBox.Show("An error occurred");
MessageBox.Show(AppResource.Main_MainPage_ContextMenu_ChangePicture_Error_Message);
}
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
//Debug.WriteLine("***\t In photoChooserTask_Completed function of ChoosePhotoPage\t ***");
if (e.TaskResult == TaskResult.OK)
{
//get the correct hubtile that was clicked and set image source to respective hubtile
string tileTitle = tileItem.Title.ToString();
switch (tileTitle)
{
case "status":
tileItem.ImageUri.SetSource(e.ChosenPhoto); //sets the tile image immediately, but does not persist when the MainPage is navigated away
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(shareJPEG))
{
myIsolatedStorage.DeleteFile(shareJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(shareJPEG);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
Settings.shareImageUpdated.Value = true; //simple boolean value that exists in isolated storage
break;
case "link":
tileItem.ImageUri.SetSource(e.ChosenPhoto); //sets the tile image immediately, but does not persist when the MainPage is navigated away
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(linkJPEG))
{
myIsolatedStorage.DeleteFile(linkJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(linkJPEG);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
Settings.linkImageUpdated.Value = true;
break;
}
}
The Settings and TileItem classes:
Settings.cs (uses key/value pairs to store data in isolated storage)
public static readonly Setting<BitmapImage> shareImage = new Setting<BitmapImage>("shareImage", new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative)));
public static readonly Setting<BitmapImage> linkImage = new Setting<BitmapImage>("linkImage", new BitmapImage(new Uri("/Images/shareLinkImage.jpg", UriKind.Relative)));
public static readonly Setting<bool> shareImageUpdated = new Setting<bool>("shareImageUpdated", false);
public static readonly Setting<bool> linkImageUpdated = new Setting<bool>("linkImageUpdated", false);
TileItem.cs
public class TileItem
{
//public string ImageUri
//{
// get;
// set;
//}
public BitmapImage ImageUri
{
get;
set;
}
public string Title
{
get;
set;
}
public string Notification
{
get;
set;
}
public bool DisplayNotification
{
get
{
return !string.IsNullOrEmpty(this.Notification);
}
}
public string Message
{
get;
set;
}
public string GroupTag
{
get;
set;
}
//for translation purposes (bound to HubTile Title on MainPage)
public string TileName
{
get;
set;
}
}
I do not get any debugging errors when running this application, but it seems thta the bitmaps are not being either saved or retrieved correctly, becuase the original tile image is the only one that persists when the app leaves the MainPage. What am I doing wrong here, and how may I fix this?

Here is the working code for storing image in Isolated storage and Loading it back. Check it.
string tempJPEG = "image.jpg";
void photoTask_Completed(object sender, PhotoResult e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
}
//Code to load image from IsolatedStorage anywhere in your app
private void Button_Click_1(object sender, RoutedEventArgs e)
{
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.img.Height = bi.PixelHeight;
this.img.Width = bi.PixelWidth;
}
}
this.img.Source = bi;
}

Related

How to download an image URL to switch to byte [] up and read it WP8 C#

for (int i = 3; i < 10; i++)
{
Uri uriimg = new Uri("http://i.msdn.microsoft.com/dynimg/IC53593" + i + ".jpg", UriKind.RelativeOrAbsolute);
SaveToLocalStorage(ImageToArray(uriimg), "anh1.jpg");
}
private byte[] ImagesToArray(Uri uriimg)
{
var image = new BitmapImage(uriimg);
MemoryStream ms = new MemoryStream();
image.ImageOpened += (s, e) =>
{
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
};
return ms.ToArray();
}
public async void SaveToLocalStorage(byte[] _imageBytes, string fileName)
{
if (_imageBytes == null)
{
return;
}
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists("dataImages"))
{
isoFile.CreateDirectory("dataImages");
}
string filePath = System.IO.Path.Combine("dataImages", fileName);
using (var stream = isoFile.CreateFile(filePath))
{
await stream.WriteAsync(_imageBytes, 0, _imageBytes.Length);
}
}
public ImageSource LoadFromLocalStorage(string fileName)
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
ImageSource imageSource = null;
if (isoFile.DirectoryExists("dataImages"))
{
string filePath = System.IO.Path.Combine("dataImages", fileName);
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
imageSource = PictureDecoder.DecodeJpeg(imageStream);
}
}
return imageSource;
}
I get the value as byte [0] it can not convert to byte [].
The problem I see is in ImagesToArray. You create a new MemoryStream, subscribe to an event that sets it, and then immediately return it. I'm pretty sure that ms will have 0 bytes when it is returned.
You should instead not use image.ImageOpened, and just put that code in the ImagesToArray method directly:
private byte[] ImagesToArray(Uri uriimg)
{
var image = new BitmapImage(uriimg);
MemoryStream ms = new MemoryStream();
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
return ms.ToArray();
}

Store and retrieve binary image in WPF

I have saved Image in database as binary :
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
if (fd.ShowDialog() == true)
{
ILogo.Source = new BitmapImage(new Uri(fd.FileName));
Stream stream = File.OpenRead(fd.FileName);
binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
}
_merchantInfo.Logo = binaryImage;
I want to read the image and showing it image tool, I tried this:
_merchantInfo = new MerchantInfo();
_merchantInfo = _context.MerchantInfo.FirstOrDefault();
byte[] binaryPhoto = (byte[])_merchantInfo.Logo;
Stream stream = new MemoryStream(binaryPhoto);
_merchantLogo = new BitmapImage();
_merchantLogo.StreamSource = stream;
ILogo.Source = _merchantLogo;
No Error, But the image does not showing in image box :(
Is there error in my code?
Thanks.
Universal Binary Storage Method -> You must read all the bites of the picture/file and save them in a binary array.
OpenFileDialog FileDialog = new OpenFileDialog();
byte[] BinaryData = new byte[]{};
if(FileDialog.ShowDialog())
{
BinaryData = System.IO.File.ReadAllBytes(FileDialog.FileName);
}
Binary Retrieval(For Images Only in WPF) -> You must set an BitmapImage and store all the binary information within it with the help of a MemoryStream.
BitmapImage image = new BitmapImage();
byte[] binary = new byte{}; /* <--- The array where
we stored the binary
information of the picture*/
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(binary)
image.EndInit();
Universal Binary Retrieval and Binary File Upload Method ->
byte[] BinaryData = new byte[]{};
private void Download()
{
OpenFileDialog FileDialog = new OpenFileDialog();
if(FileDialog.ShowDialog())
{
BinaryData = System.IO.File.ReadAllBytes(FileDialog.FileName);
}
}
private void Save()
{
OpenFileDialog FileDialog = new SaveFileDialog();
if(FileDialog.ShowDialog())
{
using(System.IO.Stream stream = new File.Open(FileDialog.FileName, FileMode.Create))
{
using (var BinaryWriter = new BinaryWriter(stream))
{
BinaryWriter.Write(BinaryData);
BinaryWriter.Close();
}
}
}
}
Finally I have solved this, here is the code for store and retrieve the image in database as binary :
To store the image:
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
if (fd.ShowDialog() == true)
{
ILogo.Source = new BitmapImage(new Uri(fd.FileName));
Stream stream = File.OpenRead(fd.FileName);
binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
}
_merchantInfo.Logo = binaryImage;
_context.SaveChanges();
Image retrieval and display:
merchantInfo = new MerchantInfo();
_merchantInfo = _context.MerchantInfo.FirstOrDefault();
byte[] binaryPhoto = (byte[])_merchantInfo.Logo;
Stream stream = new MemoryStream(binaryPhoto);
_merchantLogo = new BitmapImage();
_merchantLogo.BeginInit();
_merchantLogo.StreamSource = stream;
_merchantLogo.EndInit();
ILogo.Source = _merchantLogo;
Thanks for everyone helped me :)
i create this class and i am using it without any problems, try it and share it.
/// <summary>
/// created by Henka Programmer.
/// Class to make the converting images formats and data structs so easy.
/// This Class supporte the following types:
/// - BtimapImage,
/// - Stream,
/// - ByteImage
///
/// and the other option is image resizing.
/// </summary>
public class Photo
{
public BitmapImage BitmapImage;
public System.IO.Stream Stream;
public byte[] ByteImage;
public Photo(Uri PhotoUri)
{
this.BitmapImage = new BitmapImage(PhotoUri);
this.Stream = new MemoryStream();
this.Stream = this.BitmapImage.StreamSource;
this.ByteImage = StreamToByteArray(this.Stream);
}
public Photo(Bitmap Photo_Bitmap)
: this((ImageSource)(new ImageSourceConverter().ConvertFrom(Photo_Bitmap)))
{
/*
ImageSourceConverter c = new ImageSourceConverter();
byte[] bytes = (byte[])TypeDescriptor.GetConverter(Photo_Bitmap).ConvertTo(Photo_Bitmap, typeof(byte[]));
Photo ph = new Photo(bytes);*/
}
public Photo(ImageSource PhotoSource) : this(PhotoSource as BitmapImage) { }
public Photo(BitmapImage BitmapPhoto)
{
this.BitmapImage = BitmapPhoto;
this.ByteImage = GetByteArrayFromImageControl(BitmapPhoto);
this.Stream = new MemoryStream();
WriteToStream(this.Stream, this.ByteImage);
}
public Photo(string path)
{
try
{
this.Stream = System.IO.File.Open(path, System.IO.FileMode.Open);
this.BitmapImage = new BitmapImage();
BitmapImage.BeginInit();
BitmapImage.StreamSource = Stream;
BitmapImage.EndInit();
this.ByteImage = StreamToByteArray(this.Stream);
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
public Photo(byte[] byteimage)
{
this.ByteImage = new byte[byteimage.Length];
this.ByteImage = byteimage;
// WriteToStream(this.Stream, this.ByteImage);
//MemoryStream ms = new MemoryStream(byteimage);
this.Stream = new MemoryStream(byteimage);
}
private void WriteToStream(Stream s, Byte[] bytes)
{
using (var writer = new BinaryWriter(s))
{
writer.Write(bytes);
}
}
private byte[] StreamToByteArray(Stream inputStream)
{
if (!inputStream.CanRead)
{
throw new ArgumentException();
}
// This is optional
if (inputStream.CanSeek)
{
inputStream.Seek(0, SeekOrigin.Begin);
}
byte[] output = new byte[inputStream.Length];
int bytesRead = inputStream.Read(output, 0, output.Length);
Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
return output;
}
private BitmapImage BitmapImageFromBytes(byte[] bytes)
{
BitmapImage image = new BitmapImage();
using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())
{
imageStream.Write(ByteImage, 0, ByteImage.Length);
imageStream.Seek(0, System.IO.SeekOrigin.Begin);
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = imageStream;
image.EndInit();
//image.Freeze();
}
return image;
}
public BitmapImage GetResizedBitmap(int width, int height)
{
ImageSource imgSrc = CreateResizedImage(this.ByteImage, width, height);
return new Photo(GetEncodedImageData(imgSrc, ".jpg")).BitmapImage;
}
private ImageSource CreateResizedImage(byte[] imageData, int width, int height)
{
BitmapImage bmpImage = new BitmapImage();
bmpImage.BeginInit();
if (width > 0)
{
bmpImage.DecodePixelWidth = width;
}
if (height > 0)
{
bmpImage.DecodePixelHeight = height;
}
bmpImage.StreamSource = new MemoryStream(imageData);
bmpImage.CreateOptions = BitmapCreateOptions.None;
bmpImage.CacheOption = BitmapCacheOption.OnLoad;
bmpImage.EndInit();
Rect rect = new Rect(0, 0, width, height);
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawImage(bmpImage, rect);
}
RenderTargetBitmap resizedImage = new RenderTargetBitmap(
(int)rect.Width, (int)rect.Height, // Resized dimensions
96, 96, // Default DPI values
PixelFormats.Default); // Default pixel format
resizedImage.Render(drawingVisual);
return resizedImage;
}
internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)
{
byte[] returnData = null;
BitmapEncoder encoder = null;
switch (preferredFormat.ToLower())
{
case ".jpg":
case ".jpeg":
encoder = new JpegBitmapEncoder();
break;
case ".bmp":
encoder = new BmpBitmapEncoder();
break;
case ".png":
encoder = new PngBitmapEncoder();
break;
case ".tif":
case ".tiff":
encoder = new TiffBitmapEncoder();
break;
case ".gif":
encoder = new GifBitmapEncoder();
break;
case ".wmp":
encoder = new WmpBitmapEncoder();
break;
}
if (image is BitmapSource)
{
MemoryStream stream = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));
encoder.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
returnData = new byte[stream.Length];
BinaryReader br = new BinaryReader(stream);
br.Read(returnData, 0, (int)stream.Length);
br.Close();
stream.Close();
}
return returnData;
}
public byte[] GetByteArrayFromImageControl(BitmapImage imageC)
{
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
return memStream.GetBuffer();
}
public ImageSource ToImageSource()
{
ImageSource imgSrc = this.BitmapImage as ImageSource;
return imgSrc;
}
public System.Windows.Controls.Image ToImage()
{
System.Windows.Controls.Image Img = new System.Windows.Controls.Image();
Img.Source = this.ToImageSource();
return Img;
}
}

How to save a BitmapImage to StorageFolder in C# Windows Phone 8

I'm trying to save a BitmapImage, which I download from a url, in to the app StorageFolder.
I tryed to make a function which saves te image for me. This is what I got so far:
public async Task<string> savePhotoLocal(BitmapImage photo, string photoName)
{
var profilePictures = await storageRoot.CreateFolderAsync("profilePictures", CreationCollisionOption.OpenIfExists);
var profilePicture = await profilePictures.CreateFileAsync(photoName+".jpg", CreationCollisionOption.ReplaceExisting);
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
using (Stream outputStream = await profilePicture.OpenStreamForWriteAsync())
{
await stream.CopyToAsync(outputStream);
}
}
return profilePicture.Path;
}
But this isn't working and I don't get any errors back, so i realy don't know whats going wrong here. Any help or code samples would be awesom.
public async Task<string> savePhotoLocal(BitmapImage photo, string photoName)
{
string folderName ="profilePictures";
var imageName =photoName+".jpg";
Stream outputStream = await profilePictures.OpenStreamForWriteAsync();
if(outputStream!=null)
{
this.SaveImages(outputStream,folderName,imageName );
}
return imageName ;
}
private void SaveImages(Stream data, string directoryName, string imageName)
{
IsolatedStorageFile StoreForApplication =IsolatedStorageFile.GetUserStoreForApplication();
try
{
using (MemoryStream memoryStream = new MemoryStream())
{
data.CopyTo(memoryStream);
memoryStream.Position = 0;
byte[] buffer = null;
if (memoryStream != null && memoryStream.Length > 0)
{
BinaryReader binaryReader = new BinaryReader(memoryStream);
buffer = binaryReader.ReadBytes((int)memoryStream.Length);
Stream stream = new MemoryStream();
stream.Write(buffer, 0, buffer.Length);
stream.Seek(0, SeekOrigin.Begin);
string FilePath = System.IO.Path.Combine(directoryName, imageName);
IsolatedStorageFileStream isoFileStream = new IsolatedStorageFileStream(FilePath, FileMode.Create, StoreForApplication);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
bitmapImage.SetSource(stream);
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
writeableBitmap.SaveJpeg(isoFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
});
}
}
}
catch (Exception ex)
{
//ExceptionHelper.WriteLog(ex);
}
}
Try this:
Download an image via HttpWebRequest:
linkRequest = (HttpWebRequest)WebRequest.Create(uri);
linkRequest.Method = "GET";
WebRequestState webRequestState = new WebRequestState(linkRequest, additionalDataObject);
linkRequest.BeginGetResponse(client_DownloadImageCompleted, webRequestState);
and then:
private void client_DownloadImageCompleted(IAsyncResult asynchronousResult)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
WebRequestState webRequestState = asynchronousResult.AsyncState as WebRequestState;
AdditionalDataObject file = webRequestState._object;
using (HttpWebResponse response = (HttpWebResponse)webRequestState.Request.EndGetResponse(asynchronousResult))
{
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (Stream stream = response.GetResponseStream())
{
BitmapImage b = new BitmapImage();
b.SetSource(stream);
WriteableBitmap wb = new WriteableBitmap(b);
using (var isoFileStream = isoStore.CreateFile(yourImageFolder + file.Name))
{
var width = wb.PixelWidth;
var height = wb.PixelHeight;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
}
});
}
And WebRequestState class is:
public class WebRequestState
{
public HttpWebRequest Request { get; set; }
public object _object { get; set; }
public WebRequestState(HttpWebRequest webRequest, object obj)
{
Request = webRequest;
_object = obj;
}
}

Set Secondary Tile BackgroundImage from Image in Isolated Storage

This is how I get the stream from an image url:
using (var httpClient = new HttpClient())
{
response = await httpClient.GetStreamAsync(new Uri(IMAGEURL_HERE, UriKind.Absolute));
}
SaveImage(response);
And this is how I save it to IsoloatedStorage:
private void SaveImage(Stream result)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(result);
var wb = new WriteableBitmap(bitmap);
using (IsolatedStorageFileStream fileStream = file.CreateFile("FILENAME.jpg"))
{
int width = wb.PixelWidth;
int height = wb.PixelHeight;
if (wb.PixelWidth > 336)
{
width = 336;
}
if (wb.PixelHeight > 336)
{
height = 336;
}
Extensions.SaveJpeg(wb, fileStream, width, height, 0, 100);
}
}
}
So let's say the file is FILENAME.jpg, I thought I could set it as BackgroundImage to a Secondary Tile like this:
var tileData = new FlipTileData()
{
...
BackgroundImage = new Uri("isostore:/Shared/ShellContent/FILENAME.jpg", UriKind.Absolute),
...
It won't work. It throws no exception, only the image won't be displayed. What do I miss? Of course if I put the Image Url as Uri to BackgroundImage it works, but this is not what I want.
Edit: And I have seen similar questions here but it did not help me with my code.
Try this. May be its help.
string imageFolder = #"\Shared\ShellContent";
string shareJPEG = "FILENAME.jpg";
private void SaveImage(Stream result)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
if(!myIsolatedStorage.DirectoryExists(imageFolder))
{
myIsolatedStorage.CreateDirectory(imageFolder);
}
if (myIsolatedStorage.FileExists(shareJPEG))
{
myIsolatedStorage.DeleteFile(shareJPEG);
}
string filePath = System.IO.Path.Combine(imageFolder, shareJPEG);
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(filePath);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
int width = wb.PixelWidth;
int height = wb.PixelHeight;
if (wb.PixelWidth > 336)
{
width = 336;
}
if (wb.PixelHeight > 336)
{
height = 336;
}
Extensions.SaveJpeg(wb, fileStream, width, height, 0, 100);
fileStream.Close();
}
}
private void CreateTile()
{
var tileData = new FlipTileData()
{
....
string filePath = System.IO.Path.Combine(imageFolder, shareJPEG);
BackgroundImage = new Uri(#"isostore:" + filePath, UriKind.Absolute);
....
}
}

System.InvalidOperationException occur when load saved Image from IsolatedStorage

I have found a class from the link ImageCaching
but when i load from isolated storage i got an exeption "System.InvalidOperationException"
here is my code
public static object DownloadFromWeb(Uri imageFileUri)
{
WebClient m_webClient = new WebClient(); //Load from internet
BitmapImage bm = new BitmapImage();
m_webClient.OpenReadCompleted += (o, e) =>
{
if (e.Error != null || e.Cancelled) return;
WriteToIsolatedStorage(IsolatedStorageFile.GetUserStoreForApplication(), e.Result, GetFileNameInIsolatedStorage(imageFileUri));
bm.SetSource(e.Result);
e.Result.Close();
};
m_webClient.OpenReadAsync(imageFileUri);
return bm;
}
public static object ExtractFromLocalStorage(Uri imageFileUri)
{
byte[] data;
string isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri); //Load from local storage
if (null == _storage)
{
_storage = IsolatedStorageFile.GetUserStoreForApplication();
}
using (IsolatedStorageFileStream sourceFile = _storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
{
// Read the entire file and then close it
sourceFile.Read(data, 0, data.Length);
sourceFile.Close();
BitmapImage bm = new BitmapImage();
bm.SetSource(sourceFile);///here got the exeption
return bm;
}
}
so that i can't set the image.
I'm using the converter you mentioned and it works but you modified the method.
Your ExtractFromLocalStorage method isn't the same. You close your stream before to use it with the SetSource method.
Here is the original method code:
private static object ExtractFromLocalStorage(Uri imageFileUri)
{
string isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri); //Load from local storage
using (var sourceFile = _storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
{
BitmapImage bm = new BitmapImage();
bm.SetSource(sourceFile);
return bm;
}
}

Categories