How to save a Form using SaveFileDialog - c#

If i have a program which draws rectangles, circles and lines and i want to save the picture which the user has drawn on the form using SaveFileDialog, how would this be done?
I know how to save a text file using SaveFileDialog, just not sure how to save the form.

you can try this....
It will save form content as bitmap with SaveFileDialog
public class Form1
{
private Bitmap objDrawingSurface;
private Rectangle rectBounds1;
private void Button1_Click(object sender, System.EventArgs e)
{
objDrawingSurface = new Bitmap(this.Width, this.Height, Imaging.PixelFormat.Format24bppRgb);
rectBounds1 = new Rectangle(0, 0, this.Width, this.Height);
this.DrawToBitmap(objDrawingSurface, rectBounds1);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "JPG Files (*.JPG) |*.JPG";
if ((sfd.ShowDialog == Windows.Forms.DialogResult.OK))
{
objDrawingSurface.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}

public void SaveFormToFile(string fileName)
{
System.Drawing.Bitmap b = new Bitmap(this.Bounds.Width, this.Bounds.Height);
this.DrawToBitmap(b, this.Bounds);
b.Save(fileName );
}

Related

How to clear a pictureBox in C#? I have tried setting the property to null but it doesnt work

I would like to clear a pictureBox after clicking on an 'Encode' button to save it as a new image file in my project. I would like to clear the fields on the form after the user saves the image file.
The code I use to display image on pictureBox:
private void btnOpenfile_Click(object sender, EventArgs e)
{
// open file dialog
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files (*.png)|*.png";
if (open.ShowDialog() == DialogResult.OK)
{
// display image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
tbFilepath.Text = open.FileName;
//pictureBox1.ImageLocation = tbFilepath.Text;
}
}
The code I used to clear the pictureBox:
private void clearForm()
{
pictureBox1.Image = null; //doesn't work
pictureBox1.Invalidate(); //doesn't work
tbFilepath.Text = "";
tbMessage.Text = "";
}
I have also tried the following but it did not work either:
private void clearForm()
{
Bitmap bm = new Bitmap(img);
bm.Save(tbFilepath.Text,System.Drawing.Imaging.ImageFormat.Png);
}
I tried using the Refresh() method as one of the commentors suggested, but it did not work either:
private void clearForm()
{
Refresh(); //first attempt
pictureBox1.Refresh();// second attempt
}
I expect the pictureBox field to clear out the existing image I have selected but the image did not clear away.
Before clicking on encode button
After clicking on encode button, the textBox fields are cleared but not the pictureBox field. I used the codes I have added in this question.
Try creating a new Bitmap Variable and use it for the picturebox:
Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
pictureBox.Image = bitmap;
pictrueBox.Invalidate();
Also, try to declare a Global Variable for the Bitmap so it is the one to be set as the picture and also the one to be cleared before setting it as the image for the PictureBox.
On the other hand you could try using the OnPaint Method of the Picurebox:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bm = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}
Bitmap bm = null;
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pictureBox1.Image = bm;
}
private void btn_Open_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp); *.PNG|*.jpg; *.jpeg; *.gif; *.bmp; *.PNG";
if (ofd.ShowDialog() == DialogResult.OK)
{
bm = new Bitmap(Image.FromFile(ofd.FileName), new Size(pictureBox1.Width, pictureBox1.Height));
textBox1.Text = ofd.FileName;
pictureBox1.Invalidate();
}
}
private void btn_Clear_Click(object sender, EventArgs e)
{
bm = null;
pictureBox1.Invalidate();
}
These code I made worked perfectly. So please try it.

Printing out a dynamically created bitmap image

I've a code where i am making a bitmap image in runtime and i want to get the print of that image. My image is saved in a bitmap variable. and i want to get the print of that image. or in other words i want to access that variable in "Print code": which is in my case is the second section of code.
But i am not getting anything after the executing the "Print Code"
here is my code for Image.
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
var bmp = new Bitmap(this.picBoxCard.Width, this.picBoxCard.Height);
this.picBoxCard.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
e.Graphics.DrawImage(bmp,50,105);
bmp.Save(#"Image.png", ImageFormat.Png); //Just saving the Image for making sure
}
code to execute for printing.
private void picPrint_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
PrintDocument doc = new PrintDocument();
doc.PrintPage += printDocument1_PrintPage;
pd.Document = doc;
if (pd.ShowDialog() == DialogResult.OK)
{
doc.Print();
}
}
Please guide me where I am making any mistake.

Display an image into windows forms

I wanted to display an image to the windows forms, but i already did this and the image did not come out.
Where did I go wrong?
Here is the code:
private void Images(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.Image = Image.FromFile("../SamuderaJayaMotor.png");
pb1.Location = new Point(100, 100);
pb1.Size = new Size(500, 500);
this.Controls.Add(pb1);
}
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Like you are doing.
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
There could be many reasons for this. A few that come up quickly to my mind:
Did you call this routine AFTER InitializeComponent()?
Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.
I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Location = new Point(0, 0);
pb.Size = new Size(150, 150);
pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
pb.Visible = true;
this.Controls.Add(pb);
}

C# save bitmap output

I'm creating a C# program that's capturing the screen with bitmap.
And than I want to save it to an .Avi/ .mpeg file.
But I don't know how to save it to a video.
Here is the code I already have.
public Form1()
{
InitializeComponent();
}
static Bitmap bm;
private void btnFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
SaveCapture(textBox1.Text);
}
private void SaveCapture(string path)
{
// Here should be the code to save it to mpeg/avi
}
private void timer1_Tick(object sender, EventArgs e)
{
// Take screenshot
bm = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bm as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bm.Size);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
// Show it in picturebox
pictureBox1.Image = bm;
}
Thank you very much!
Create a Video Stream (AVI) from a Series of Images
I think this might be your best solution. Store all the .jpg's and create an avi from the command line at intervals. I don't see how creating video on the fly would produce a "lightweight" solution.
Hello click this to download the aviwrapper liblary. And the code that you should write is this:
var pngFileList = Directory.EnumerateFiles(folderImages, "*.png");
//load the first image
Bitmap bitmap = (Bitmap)Image.FromFile(pngFileList.First());
//create a new AVI file
AviManager aviManager = new AviManager(fileName, false); // location and the name of video file
//add a new video stream and one frame to the new file
//set IsCompressed = false
VideoStream aviStream = aviManager.AddVideoStream(false, 3, bitmap);
pngFileList.Skip(1).ToList().ForEach(file =>
{
bitmap = (Bitmap)Bitmap.FromFile(file);
aviStream.AddFrame(bitmap);
bitmap.Dispose();
});
aviManager.Close();

C# - Making a BackgroundImage update in real time while editing it in other programs

first i have made an desktop AIR app with drag and drop functions to view the tiles image, but because of some issues, i've tryed to make the same in C#. what do you think is the better choice ? ( i know for this little programm performance is not the question, but i mean the dufficulty and complexity of both )
I was building a simple TileViewer, so a picture is selected in openFileDialog and set as tiled BackgroundImage of the Form.
My problem is:
I've been using a timer ( interval = 500 ) to reload the image, so if i edit the image in photoshop, the TileViewer will automaticaly reload the updated image ( as i save it in photoshop ).
BUT the problem is that photoshop doesnt have premissions to do so, cuz the image is opened in an other programm ( my TileViewer )
I removed the Timer and made a refresh button instead. but its the same problem.
I thought of making a copy of the bitmap data, but then I get an error that I dont have enought memory for a 32px x 32px img.
My code :
private string FileName;
public Form1() {
InitializeComponent();
FileName = "";
}
// OPEN FILE btn
private void button1_Click( object sender, EventArgs e ) {
openFileDialog1.Filter = "PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg";
if(openFileDialog1.ShowDialog() == DialogResult.OK) {
button2.Enabled = true;
FileName = openFileDialog1.FileName;
setImage();
}
}
// REFRESH btn
private void button2_Click( object sender, EventArgs e ) {
if( FileName != "" ) {
setImage();
}
}
private void setImage() {
Bitmap tempImg = new Bitmap( FileName );
Rectangle rect = new Rectangle(0, 0, 100, 100);
PixelFormat format = tempImg.PixelFormat;
this.BackgroundImage = new Bitmap( FileName ).Clone( rect, format );
}
So guys, if you have any suggestions or solutions, let me know.
Update 2:
Another issue was is in line Rectangle rect = new Rectangle(0, 0, 100, 100);
where in the constructor you should pass the width and heigth of the new image not an arbitary value like 100.
thats why the runtime says that you're out of memory !! (It did for me and I have a 18 GB monster machine)
Update:
your're leaking objects hence the out of memory exception
(Haans Already warned you about disposing objects thats.)
Try the following code
private string FileName;
public Form1()
{
InitializeComponent();
FileName = "";
}
// OPEN FILE btn
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = openFileDialog1.FileName;
setImage();
}
}
// REFRESH btn
private void button2_Click(object sender, EventArgs e)
{
if (FileName != "")
{
setImage();
}
}
private void setImage()
{
Stream str=new FileStream(FileName,FileMode.Open, FileAccess.Read,FileShare.Read);
Bitmap tempImg= new Bitmap(Bitmap.FromStream(str));
str.Close();
using( tempImg)
{
Rectangle rect = new Rectangle(0, 0, tempImg.Width, tempImg.Height);
PixelFormat format = tempImg.PixelFormat;
this.BackgroundImage = new Bitmap(tempImg);
}
}
OLD Answer
Like Jason said
you might need to do somethinglike this in your setimage method
Stream str = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
this.BackgroundImage = Bitmap.FromStream(str);
str.Close();
Note that you're better off closing any stream that you open after you use it.
instead of
private void setImage() {
Bitmap tempImg = new Bitmap( FileName ); <---
Rectangle rect = new Rectangle(0, 0, 100, 100);
PixelFormat format = tempImg.PixelFormat;
this.BackgroundImage = new Bitmap( FileName ).Clone( rect, format );
}
The Bitmap.Clone() method doesn't do what you hope it does. It creates a "shallow" copy. You get a new Bitmap object but it still uses the underlying pixel buffer. Including the memory-mapped file that GDI+ uses to keep the pixel data out of the swap file. Which in turn puts a lock on the file.
You'll need to make a "deep" copy, do so with the Bitmap(Image) constructor. Like this:
private void setImage() {
using (var tempImg = new Bitmap(FileName)) {
this.BackgroundImage = new Bitmap(tempImg);
}
}
The using statement ensures the original image is disposed and the lock gets released.
You will need to open the file manually with ReadOnly flags, and then load the payload of the file into the bitmap by hand.
an alternitive would be to copy the file and then open the copy.
See if you cna run the following code while photoshop has the file open
FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);

Categories