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();
}
Related
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());
I need to convert a JPG image to PNG and change its white background to transparent instead. I am using ImageMagick.NET and I have found the following ImageMagick command that is supposed to do what I am trying to achieve:
convert image.jpg -fuzz XX% -transparent white result.png
I have tried converting this to c# but all I am getting is a png image with a white background. My code snippet:
using (var img = new MagickImage("image.jpg"))
{
img.Format = MagickFormat.Png;
img.BackgroundColor = MagickColors.White;
img.ColorFuzz = new Percentage(10);
img.BackgroundColor = MagickColors.None;
img.Write("image.png");
}
Any kind of help will be greatly appreciated. Thank you!!
This is a late response as it took me a while to find an answer myself, but this seems to work for me quite well. Look at where the Background property is assigned the Transparent value.
using (var magicImage = new MagickImage())
{
var magicReadSettings = new MagickReadSettings
{
Format = MagickFormat.Svg,
ColorSpace = ColorSpace.Transparent,
BackgroundColor = MagickColors.Transparent,
// increasing the Density here makes a larger and sharper output to PNG
Density = new Density(950, DensityUnit.PixelsPerInch)
};
magicImage.Read("someimage.svg", magicReadSettings);
magicImage.Format = MagickFormat.Png;
magicImage.Write("someimage.png");
}
In my case, I wanted to send this to UWP Image element, so instead of Write(), I did the following after the steps above:
// Create byte array that contains a png file
byte[] imageData = magicImage.ToByteArray();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
{
writer.WriteBytes(imageData);
await writer.StoreAsync();
}
await bitmapImage.SetSourceAsync(stream);
}
return bitMapImage; // new BitMapImage() was scoped before all of this
Then on the UWP Image element, simply use:
imageElement.Source = bitMapImage;
Most of the arguments on the command line are either properties or method on the MagickImage class. Your command would translate to this:
using (var img = new MagickImage("image.jpg"))
{
// -fuzz XX%
img.ColorFuzz = new Percentage(10);
// -transparent white
img.Transparent(MagickColors.White);
img.Write("image.png");
}
It's possible to set a TiF (or TIFF) file in a Metro Application as an Image source very easily...
Image imm = new Image();
imm.Source = new BitmapImage(new Uri(filetiff_path));
The problem is that the content showed in the image is always the first page of the Tif and i am not able to set the content to another pages of the source file.
In WPF app I can do that with the System.Windows.Media.Imaging.TiffBitmapDecoder class that it does not seem to exist in a Metro Win 8 app
Stream imageStreamSource = new FileStream(filetiff_path, FileMode.Open, FileAccess.Read, FileShare.Read);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[indexPage];
Where indexPage is the number of the page that i want to be viewed.
Does anybody know a similar solution?
I don't have any experience with neither TiffBitmapDecoder nor Metro WPF, but I have used a similar thing before in WPF like this:
using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile("temp.tif"))
{
System.Drawing.Imaging.FrameDimension frameDimensions = new System.Drawing.Imaging.FrameDimension(imageFile.FrameDimensionsList[0]);
imageFile.SelectActiveFrame(frameDimensions, indexPage);
using (System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(imageFile.Size.Width, imageFile.Size.Height))
{
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newImage))
{
gr.Clear(System.Drawing.Color.White);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.DrawImage(imageFile, new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), imageFile.Size));
}
//do whatever with the newImage bitmap
}
}
SelectActiveFrame is the point you need there, so you can try that if it also works for you...
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
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.