InvalidOperationException when using SavePictureToCameraRoll of MediaLibrary - windows-phone-7

I get an exception trying to save a picture on a CameraCaptureTask callback. Why is that ? I'm debugging through WPConnect.exe, and I do have to capability ID_CAP_MEDIALIB.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
string fileName = adViewModel.Id + DateTime.Now.Ticks + ".jpg";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName))
{
myIsolatedStorage.DeleteFile(fileName);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(fileName);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
MediaLibrary library = new MediaLibrary();
// this line throw the exception
Picture pic = library.SavePictureToCameraRoll(fileName, fileStream);
}
}
}

According to this MSDN entry SavePicture will throw an exception if the phone is tethered to the computer. I imagine SavePictureToCameraRoll will be the same.

Related

Any way to save a resized BitmapImage in WP 8.1

How can I save a resized BitmapImage? I can't find the way to do this in Windows Phone 8.1 Here is my code:
BitmapImage bitm = new BitmapImage();
await bitm.SetSourceAsync(stream);
bitm.DecodePixelWidth = 200;
bitm.DecodePixelHeight = 250;
myImage.ImageSource= bitm;
(Now I want to store in a file because the saved image is too big)
You can use WriteableBitmap for saving the image.
private async void SaveImage(object sender, RoutedEventArgs e)
{
BitmapImage bitm = new BitmapImage();
await bitm.SetSourceAsync(stream);
bitm.DecodePixelWidth = 200;
bitm.DecodePixelHeight = 250;
WriteableBitmap wb = new WriteableBitmap(bitm);
wb.Invalidate();
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/hello.jpg", System.IO.FileMode.Create, isf))
{
wb.SaveJpeg(imageStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
}
}

Storing images in isolated storage in background

I am developing app in which i have check first the images is present in isolated storage.If image is not there then i download first and then store them in isolated storage .But I got exception "An exception of type 'System.ObjectDisposedException' occurred in mscorlib.ni.dll but was not handled in user code " at using (IsolatedStorageFileStream mystream = istore.CreateFile(item.ImageUrl)).
private void checkimage(Model item)
{
using (IsolatedStorageFile istore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (istore.FileExists(item.ImageUrl))
{
}
else
{
BitmapImage imgage = new BitmapImage(new Uri(item.ImageUrl, UriKind.Absolute));
imgage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
imgage.ImageOpened += (o, e) =>
{
using (IsolatedStorageFileStream mystream = istore.CreateFile(item.ImageUrl))
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(mystream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Extensions.SaveJpeg(wb, mystream, wb.PixelWidth, wb.PixelHeight, 0, 85);
mystream.Close();
}
};
}
}
}
It looks like istore has been destroyed at the time, when you trying to create the file. Try to create (istore) again in the event body or use global variable and handle dispose by hand.
For example: move BitmapImage imgage... outside the first using and create istore again.

How to load an image from isolated storage into image control on windows phone?

I am using this code for storing the image into isolate storage at the time of camera action completed.
void camera_Completed(object sender, PhotoResult e)
{
BitmapImage objImage = new BitmapImage();
//objImage.SetSource(e.ChosenPhoto);
//Own_Image.Source = objImage;
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
fnam = e.OriginalFileName.Substring(93);
MessageBox.Show(fnam);
if (isolatedStorage.FileExists(fnam))
isolatedStorage.DeleteFile(fnam);
IsolatedStorageFileStream fileStream = isolatedStorage.CreateFile(fnam);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 100, 100);
MessageBox.Show("File Created");
fileStream.Close();
}
}
Now I want to take the image from isolated storage and display it in my image control.
Is it possible?
Yes it is. You can use this function to load image from IsolatedStorage:
private static BitmapImage GetImageFromIsolatedStorage(string imageName)
{
var bimg = new BitmapImage();
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = iso.OpenFile(imageName, FileMode.Open, FileAccess.Read))
{
bimg.SetSource(stream);
}
}
return bimg;
}
Usage:
ImageControl.Source = GetImageFromIsolatedStorage(fnam);
Something like this:
public BitmapImage LoadImageFromIsolatedStorage(string path) {
var isf = IsolatedStorageFile.GetUserStoreForApplication();
using (var fs = isf.OpenFile(path, System.IO.FileMode.Open)) {
var image = new BitmapImage();
image.SetSource(fs);
return image;
}
}
In your code
image1.Source = LoadImageFromIsolatedStorage("image.jpg");
check this snippet
public static void SaveImage( string name)
{
var bitmap = new BitmapImage();
bitmap.SetSource(attachmentStream);
var wb = new WriteableBitmap(bitmap);
var temp = new MemoryStream();
wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("foldername"))
{
myIsolatedStorage.CreateDirectory("foldername");
}
var filePath = Path.Combine("foldername", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
{
fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
fileStream.Close();
}
}
}

save image locally & display windows phone 7

I'm trying to implement an app of news (feedrss) by using WP7 i've tried this solution , but it does'nt work for me , here is my code :
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();}
private void Go_Click(object sender, RoutedEventArgs e)
{
WebClient _client = new WebClient();
_client.DownloadStringCompleted += Feed;
Location.Text = "http://www.aufaitmaroc.com/feeds/ma-vie.xml";
_client.DownloadStringAsync(new Uri((Location.Text)));
InitializeComponent();
}
private void Feed(object Sender, DownloadStringCompletedEventArgs e)
{
XElement _xml;
try
{
if (!e.Cancelled)
{
_xml = XElement.Parse(e.Result);
List<FeedItem> l = new List<FeedItem>();
foreach (XElement value in _xml.Elements("channel").Elements("item"))
{
FeedItem _item = new FeedItem();
_item.Title = value.Element("title").Value;
_item.enclosure = value.Element("enclosure").Attribute("url").Value;
_item.Description = Regex.Replace(value.Element("description").Value,
#"<(.|\n)*?>", String.Empty);
_item.Link = value.Element("link").Value;
_item.Guid = value.Element("guid").Value;
_item.Published = DateTime.Parse(value.Element("pubDate").Value);
l.Add(_item);
HttpWebRequest reqest1 = (HttpWebRequest)WebRequest.Create(_item.enclosure);
reqest1.BeginGetResponse(DownloadImageCallback, reqest1);
Thread.Sleep(1000);
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(_item.enclosure), client);
}
listBox.ItemsSource = l;
}
}
catch
{
}
}
IsolatedStorageFile MyStore = IsolatedStorageFile.GetUserStoreForApplication();
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var resInfo = new StreamResourceInfo(e.Result, null);
var reader = new StreamReader(resInfo.Stream);
byte[] contents;
using (BinaryReader bReader = new BinaryReader(reader.BaseStream))
{
contents = bReader.ReadBytes((int)reader.BaseStream.Length);
}
IsolatedStorageFileStream stream = MyStore.CreateFile("10.jpg");
stream.Write(contents, 0, contents.Length);
stream.Close();
}
void DownloadImageCallback(IAsyncResult result)
{
HttpWebRequest req1 = (HttpWebRequest)result.AsyncState;
HttpWebResponse responce = (HttpWebResponse)req1.EndGetResponse(result);
Stream s = responce.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
string directory = "Imagestest";
if (!MyStore.DirectoryExists(directory))
{
MyStore.CreateDirectory(directory);
IsolatedStorageFileStream stream = MyStore.CreateFile("10.jpg");
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isoFileStream = myIsolatedStorage.CreateFile(directory + "//ANALYSE_10052013095620.jpg"))
{
var bitimage = new BitmapImage();
var wb = new WriteableBitmap(bitimage);
var width = wb.PixelWidth;
var height = wb.PixelHeight;
// bitimage.SetSource = isoFileStream;
image1.Source = bitimage;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
else
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(directory + "//ANALYSE_10052013095620.jpg"))
{
myIsolatedStorage.DeleteFile(directory + "//ANALYSE_10052013095620.jpg");
}
using (var isoFileStream = myIsolatedStorage.CreateFile(directory + "//ANALYSE_10052013095620.jpg"))
{
var bitimage = new BitmapImage();
var wb = new WriteableBitmap(bitimage);
var width = wb.PixelWidth;
var height = wb.PixelHeight;
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, isoFileStream, width, height, 0, 100);
}
}
}
});
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
FeedItem currentFeedItem = (FeedItem)listBox.SelectedItem;
PhoneApplicationService.Current.State["FeedItem"] = currentFeedItem;
}
When i run this project , nothing's happend , it does'nt create any folder ,when i stop the internet , images doesnt display anymore.
If you need image caching in your app, I can suggest JetImageLoader library for you
Features:
Caching in memory (so it will work very fast with lists, grids, etc)
Caching is IsolatedStorageFile (to prevent reloading each time)
Fully asynchronous (no lags)
Usage via XAML Binding Converter, you do not have to change your code, just declare converter for Image
But it supports only Windows Phone 8+
I am authour of that library, so if you got any questions, please write to me here or create an issue on github
If you want to save image locally and the display image from locally, then try this sample
http://code.msdn.microsoft.com/wpapps/CSWP8ImageFromIsolatedStora-8dcf8411, on WP 8 it's works fine.

Exeception " Operation not permitted on IsolatedStorageFileStream."

I am trying to save a Image from IsolatedStorage.I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public HomePage()
{
InitializeComponent();
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "/Images/homescreenmap.png";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
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();
}
}
IsolatedStorageException means that it cannot find the path to location which you set, in your case this is folder Images. Just add before you create a file this code:
if (!myIsolatedStorage.DirectoryExists("Images"))
{
myIsolatedStorage.CreateDirectory("Images");
}

Resources