Windows Phone - SavePicture - InvalidOperationException - c#

Why this code throws InvalidOperationException no metter if I am conncted to PC or not?
MemoryStream ms = new MemoryStream();
picture.SaveAsJpeg(ms, 480, 800);
ms.Seek(0, SeekOrigin.Begin);
MediaLibrary l = new MediaLibrary();
l.SavePicture("test11", ms);
l.Dispose();
ms.Dispose();
I use WP7 RC Tools and XNA
picture is an Texture2D instance

Just solved the problem.
I forgot I've played with permissions (manifest file), and accidentaly deleted this permission
<Capability Name="ID_CAP_MEDIALIB" />

found this example here: How to: Encode a JPEG for Windows Phone and Save to the Pictures Library
hopefully it helps, it is saving the stream in the IsolatedStorage first then loading from there and saving in the MediaLibrary in the end...
private void btnSave_Click(object sender, RoutedEventArgs e)
{
// Create a file name for the JPEG file in isolated storage.
String tempJPEG = "TempJPEG";
// Create a virtual store and file stream. Check for duplicate tempJPEG files.
var myStore = IsolatedStorageFile.GetUserStoreForApplication();
if (myStore.FileExists(tempJPEG))
{
myStore.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);
// Create a stream out of the sample JPEG file.
// For [Application Name] in the URI, use the project name that you entered
// in the previous steps. Also, TestImage.jpg is an example;
// you must enter your JPEG file name if it is different.
StreamResourceInfo sri = null;
Uri uri = new Uri("[Application Name];component/TestImage.jpg", UriKind.Relative);
sri = Application.GetResourceStream(uri);
// Create a new WriteableBitmap object and set it to the JPEG stream.
BitmapImage bitmap = new BitmapImage();
bitmap.CreateOptions = BitmapCreateOptions.None;
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode the WriteableBitmap object to a JPEG stream.
wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
myFileStream.Close();
// Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);
// Save the image to the camera roll or saved pictures album.
MediaLibrary library = new MediaLibrary();
if (radioButtonCameraRoll.IsChecked == true)
{
// Save the image to the camera roll album.
Picture pic = library.SavePictureToCameraRoll("SavedPicture.jpg", myFileStream);
MessageBox.Show("Image saved to camera roll album");
}
else
{
// Save the image to the saved pictures album.
Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream);
MessageBox.Show("Image saved to saved pictures album");
}
myFileStream.Close();
}

If you're connected to the PC, you can't use the MediaLibrary. Instead connect with WPConnect.exe
See this answer for details on how: Unable to launch CameraCaptureTask or PhotoChooserTask while debugging with device

Related

C# Shell Thumbnail doesnt work properly on ppt files

I have the following function to get BitmapImage of file.
public static BitmapImage GetThumbnail(string filePath)
{
ShellFile shellFile = ShellFile.FromFilePath(filePath);
BitmapSource shellThumb = shellFile.Thumbnail.ExtraLargeBitmapSource;
BitmapImage bImg = new BitmapImage();
PngBitmapEncoder encoder = new PngBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(shellThumb));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
return bImg;
}
When I get Video's Thumbnail it always works.
When I get Presentation (pptx) Thumbnail it doesn't work properly (I have no idea when it does and when it doesn't).
For example, I have 2 files in directory:
And this is how it looks in my program - 1 is ok and 1 isn't (sometimes both are ok, and sometimes both aren't):
I would appreciate if you could tell me what's the problem or maybe give me another way of getting the Thumbnail that will not fail...
p.s.
I would like to remind that with video files it works 100% fine (.mp3, .mp4, .wmv - thats what I tested)
Since I wanted to get pptx thumbnail, I came up with the following solution:
1. I extracted the thumbnail using DotNetZip
2. I got the thumbnail which is located in docProps directory
3. I extracted the thumbnail to memoryStream
4. I converted the memoryStream to BitmapImage and returned it.
here's the code:
public static BitmapImage GetPPTXThumbnail(string filePath)
{
using (ZipFile zip = ZipFile.Read(filePath))
{
ZipEntry e = zip["docProps/thumbnail.jpeg"];
BitmapImage bImg = new BitmapImage();
MemoryStream memoryStream = new MemoryStream();
bImg.BeginInit();
e.Extract(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
bImg.StreamSource = memoryStream;
bImg.EndInit();
return bImg;
}
}
Cant fail with this solution, this solution is only to get PPTX Thumbnail, I assume it works with all office xml files such as docx, xlsx, etc...

Saving an captured image to the local folder

I am taking pictures and would like to save them according to the time they were exactly taken.
I would also like to create a folder named /pictures in the current directory and save the pictures in that folder. This is done in C# & WPF.
This is my code:
Image newimage = new Image();
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
newimage.Source = Capture(true) // Take picture
myBitmapImage.UriSource = new Uri(#"c:\" +
string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + ".jpg");
// Gives error: Could not find file 'c:\2013-05-26_04-40-25-AM.jpg'
myBitmapImage.EndInit();
newimage.Source = myBitmapImage;
newstackPanel.Children.Add(newimage);
Results in:
ERROR Could not find file 'c:\2013-05-26_04-44-59-AM.jpg'.
Why is it trying to find a file VS just saving the file on the c:\ drive?
If all you want to do is to save the image to disk, then you should use the BitmapEncoder class
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
var image = Capture(true); // Take picture
encoder.Frames.Add(BitmapFrame.Create(image));
// Save the file to disk
var filename = String.Format("...");
using (var stream = new FileStream(filename, FileMode.Create))
{
encoder.Save(stream);
}
The above example creates a JPEG image, but you any encoder you want - WFP comes with Png, Tiff, Gif, Bmp and Wmp encoders built in.

Image is not saving after updating, in c# using FileStream or Simple Bitmap

I am working for a utility in desktop application, related to some graphics work.
I have to load small thumbnails and full sized bitmap.I am doing this using this code.
FileStream fs = new FileStream("myphoto.jpg", FileMode.Open);
Image imgPhoto = Image.FromStream(fs);
fs.Close();
PictureBox p = new PictureBox();
p.Name = "p1";
p.Image = imgPhoto;
flowPanel.Controls.Add(p);
//----
FileStream fs = new FileStream("myphoto_thumb.jpg", FileMode.Open);
Image img = Image.FromStream(fs);
fs.Close();
Button b_thumb = new Button();
b_thumb.Name = "thumb1";
b_thumb.BackgroundImage = img;
flowBottom.Controls.Add(b_thumb);
After this, i need to add some effects on image of this picturebox.When i add some effect to main (big) image in picturebox, i also add the same effect in botton background image.When i save this thumbnail image to existing thumbnail image it is saving, but when i save the big image from picturebox on the existing file "myphoto.jpg", it gives me error like FILE IS BEING USED BY ANOTHER PROCESS
//---- Add some Effects to image of Picturebox ---- //
PictureBox tempPic = flowPanel.Controls["p1"];
tempPic.Image.Save("myphoto.jpg",ImageFormat.Jpeg);
I have found many solutions on google and on stackoverflow but could not find helpful.
If any good solution, plz help.
May be its very simple but i have tried more than 10 hours but failed.
You don't close the FileStream you open. I always wrap this kind of stuff in a using construction, so it automatically gets destructed, thus closes:
using (FileStream fs = new FileStream("myphoto.jpg", FileMode.Open)) {
// Do stuff
}
tempPic.Image.Save("myphoto.jpg",ImageFormat.Jpeg);
Try setting your filestream to read only:
fs = New System.IO.FileStream("myphoto.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
This is Microsoft's recommendation, targeted at users who try Image.FromFile and it locks the file: http://support.microsoft.com/kb/309482

Saving an image

I'm making a drawing program in C# for Windows Phone.
This is for Windows Phone, so a bunch of stuff doesn't work that would work in C#.
At the start of opening a .XAML page, I have a blank Canvas. The user draws on the Canvas, then clicks Save. When he/she clicks Save, I want the program to be able to save the image on the Canvas.
I have the following code so far:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader sr = null;
sr = new StreamReader(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Open, isf));
test = sr.ReadLine();
sr.Close();
int.TryParse(test, out test2);
test2 = test2 + 1;
IsolatedStorageFile isf2 = IsolatedStorageFile.GetUserStoreForApplication();
isf2.CreateDirectory("Data");
StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream("Data\\imagenum.txt", FileMode.Create, isf2));
sw.WriteLine(test2);
//This writes the content of textBox1 to the StreamWriter. The StreamWriter writes the text to the file.
sw.Close();
This code finds what an appropriate name for the image would be.
I've also found various other code snippets on the web:
// Construct a bitmap from the button image resource.
test = "Images/" + test + ".jpg";
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
WriteableBitmap bmImage = new WriteableBitmap(image);
if (!store.DirectoryExists("Images"))
{
store.CreateDirectory("Images");
}
using (IsolatedStorageFileStream isoStream =
store.OpenFile(#"Images\" + test + ".jpg", FileMode.OpenOrCreate))
{
Extensions.SaveJpeg(
bmImage,
isoStream,
bmImage.PixelWidth,
bmImage.PixelHeight,
0,
100);
}
}
The above is an ugly mess of code from tutorials on MSDN and my own badly scraped together code.
(It doesn't work, for semi-obvious reasons)
How would I save the canvas to IsolatedStorage, as an image?
Your first section where you appear to be writing the last used number to a text file in IsolatedStorage seems like a lot of work to do something relatively simple. You can replace that whole section with this:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
int imageNumber = 0;
settings.TryGetValue<int>("PreviousImageNumber", out imageNumber);
imageNumber++;
You can save the image to IsolatedStorage like this:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.DirectoryExists("Images"))
{
isf.CreateDirectory("Images");
}
IsolatedStorageFileStream fstream = isf.CreateFile(string.Format("Images\\{0}.jpg",imageNumber));
WriteableBitmap wbmp = new WriteableBitmap(image);
Extensions.SaveJpeg(wbmp, fstream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
fstream.Close();
}
But it would probably make more sense to save the image to their MediaLibrary like this:
MediaLibrary library = new MediaLibrary();
WriteableBitmap wbmp = new WriteableBitmap(image);
MemoryStream ms = new MemoryStream();
Extensions.SaveJpeg(wbmp, ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
ms.Seek(0, SeekOrigin.Begin);
library.SavePicture(string.Format("Images\\{0}.jpg",imageNumber), ms);
Either way, you can then save the imageNumber back to the IsolatedStorageSettings like this:
settings["PreviousImageNumber"] = imageNumber;
settings.Save();
I had assumed the image used above was set somewhere else in your code. I haven't saved a Canvas to an image before, but some quick searching turned up this blog where an example is given using the WriteableBitmap which indicates you can just replace the image variable with your canvas element:
WriteableBitmap wbmp = new WriteableBitmap(yourCanvas, null);
The article also indicates that the Canvas' background will be ignored and replaced with a black image but that you can overcome this by first adding a rectangle to the Canvas with whatever background you want. Again, I haven't tried this. If this doesn't work you should consider posting another question specifically related to transforming a Canvas to an Image since this is really a separate issue from your original question about saving images.
If you can save the writeable image using CE and want to know how to save the canvas,
then you need to either render canvas to image or if you want to save drawing, then have user draw directly to image, not canvas, by putting blank image (with alpha channel) on canvas, then using mouse move event to add brush marks to image. Thus modifying both display and future input to save method.

What is to FromFile and ToFile equivalent for BitmapImage?

The System.Drawing.Image has the easy to use methods for FromFile and ToFile. What is the equivalent for the Silverlight BitmapImage? I am trying to load and save a jpeg image as part of a unit test. The bytes must match exactly for it to pass. Here is my current guess:
//I am not sure this is right
private BitmapImage GetImage(string fileName)
{
BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
bitmapImage.BeginInit();
bitmapImage.StreamSource = imageStreamSource;
bitmapImage.EndInit();
}
return bitmapImage;
}
private void SaveImage(BitmapImage bitmapImage, string file)
{
//How to do this?
}
An in-browser Silverlight application cannot open a file using a filename. You would need it run out-of-browser with elevated trust to do that.
Silverlight has no built-in image encoding so you can't take the contents of a bitmap (BTW you would need to be using WriteableBitmap to be able to access the raw image).
You find something you need in Image Tools.
From MSDN link, use the ctor overload which takes in a URI or
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(#"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg");
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();
//set image source
myImage.Source = myBitmapImage;
To save the image to disk, you'd need the specific encoder e.g. JpegBitmapEncoder

Categories