Saving an image - c#

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.

Related

Why does writing an image to a stream give me a different result than directly saving to a file?

I am trying to add some rectangles to an existing image. When using the following code, everything works fine:
var bytes = File.ReadAllBytes("myPath\\input.jpg");
var stream = new MemoryStream(bytes);
using (var i = new Bitmap(stream))
{
using (var graphics = Graphics.FromImage(i))
{
var selPen = new Pen(Color.Blue);
graphics.DrawRectangle(selPen, 10, 10, 50, 50);
i.Save("myPath\\output.jpg", ImageFormat.Jpeg);
}
}
But saving the image to the same MemoryStream and then later writing all bytes to a file gives me an almost grey-only image.
This does not work:
var bytes = File.ReadAllBytes("myPath\\input.jpg");
var stream = new MemoryStream(bytes);
using (var i = new Bitmap(stream))
{
using (var graphics = Graphics.FromImage(i))
{
var selPen = new Pen(Color.Blue);
graphics.DrawRectangle(selPen, 10, 10, 50, 50);
i.Save(stream, ImageFormat.Jpeg);
}
}
File.WriteAllBytes("myPath\\output.jpg", stream.ToArray());
The (wrong) image looks like this:
As you can see, only part of the image is grey. There still is some part visible (the white one) of the actual image.
Why is this happening and what is the correct solution?
Thanks!
You've double-written to the Stream in the second example; it still contains the original data, and then you've appended more data with the Save. Stream works like a video tape (sort of). If you want to overwrite the stream, you need to do that very carefully (and: not all streams even support that concept - think "network stream", "encryption stream", etc). Note that ToArray (and the GetBuffer / TryGetBuffer methods) see all the data, not just what you're thinking of as the "new" data (a concept that doesn't even exist, really - like a video tape, you only have the "current" position and the length - if you need to know where the first show ends and the second show starts, you need to note that yourself, manually). In this case, adding:
stream.Position = 0; // rewind
stream.SetLength(0); // truncate (important in case the new data is *shorter* than the old)
after reading it and before Save, should fix it.
You are saving the image to an already initialized stream from a byte array.
Create a new stream and save to it.
var stream2 = new MemoryStream();
i.Save(stream2, ImageFormat.Jpeg);
Or simply reset the previous one
memoryStream = new MemoryStream(stream.Capacity());

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.

How to take a screenshot in WP8

So I have a DrawingSurfaceBackgroundGrid inside of a PhoneApplicationPage, in my WP8 app; and I would like to take a screenshot. As far as I can tell (from google), there isn't a call to simply "take a screenshot". What people are doing is using a WriteableBitmap, like this:
WriteableBitmap wbmp = new WriteableBitmap(test, null);
wbmp.SaveJpeg(isoStream2, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
I have tried test as both the DrawingSurfaceBackgroundGrid, and the PhoneApplicationPage. Neither of these are working for me. Could it have something to do with the fact that I am rendering everything using RenderTargets and pixel shaders (in SharpDX)? I just get a black image. Here is the code to save the image:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream isoStream2 = new IsolatedStorageFileStream("new.jpg", FileMode.OpenOrCreate, isoStore))
{
WriteableBitmap wbmp = new WriteableBitmap(test, null);
wbmp.SaveJpeg(isoStream2, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
}
But like I said, it just creates a black image.
Any ideas?
Tried your code as is with the exception of changing "test" to the name of the root grid, in my app x:Name="LayoutRoot", and works fine! Just replace test with the element you want to capture, the root-grid name for whole page or sub element name for just that element.
BTW thanks for the code, one more to squirrel away.
I am using the code below. Though it is saving to the Media Gallery.
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmpCurrentScreenImage.Render(LayoutRoot, new MatrixTransform());
bmpCurrentScreenImage.Invalidate();
using (var stream = new MemoryStream())
{
// Save the picture to the Windows Phone media library.
bmpCurrentScreenImage.SaveJpeg(stream, bmpCurrentScreenImage.PixelWidth, bmpCurrentScreenImage.PixelHeight, 0, quality);
stream.Seek(0, SeekOrigin.Begin);
var picture = new MediaLibrary().SavePicture(name, stream);
return picture.GetPath();
}

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

Windows Phone - SavePicture - InvalidOperationException

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

Categories