Allow user to copy image from picturebox and save it everywhere - c#

In my application I have a pictureBox that shows an image. When user right clicks on the pictureBox and selects Copy from the context menu, I want to copy the image into the clipboard so the user can paste it in folders and anywhere else. How can I do that?
EDIT: I use this code but by this user only can paste image into word.
var img = Image.FromFile(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetImage(img);

Clipboard.SetImage copies the image content (binary data) to the clipboard not the file path. To paste a file in Windows Explorer you need to have file paths collection in the clipboard not their content.
You can simply add the path of that image file to a StringCollection and then call the SetFileDropList method of Clipboard to achieve what you want.
System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();
FileCollection.Add(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetFileDropList(FileCollection);
Now user can past the file anywhere e.g. Windows Explorer.
More info on Clipboard.SetFileDropList Method http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.setfiledroplist.aspx

This is the solution when the picture box does not display a file image, but it is rendered upon with GDI+.
public partial class Form1 : Form
{
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// call render function
RenderGraphics(e.Graphics, pictureBox1.ClientRectangle);
}
private void pictureBox1_Resize(object sender, EventArgs e)
{
// refresh drawing on resize
pictureBox1.Refresh();
}
private void copyToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
{
// create a memory image with the size taken from the picturebox dimensions
RectangleF client=new RectangleF(
0, 0, pictureBox1.Width, pictureBox1.Height);
Image img=new Bitmap((int)client.Width, (int)client.Height);
// create a graphics target from image and draw on the image
Graphics g=Graphics.FromImage(img);
RenderGraphics(g, client);
// copy image to clipboard.
Clipboard.SetImage(img);
}
private void RenderGraphics(Graphics g, RectangleF client)
{
g.SmoothingMode=SmoothingMode.AntiAlias;
// draw code goes here
}
}

Related

Why undo Drawline() in my opinion is not work?

I try to remove newest drawline.
declaration
Bitmap DrawArea ; // global variable
Bitmap Previuos_DrawArea; // global variable
when I click button to draw a line
private void button2_Click_1(object sender, EventArgs e)
{
Graphics g = Graphics.FromImage(DrawArea);
Previuos_DrawArea_img = DrawArea;
g.(new Pen(Brushes.BlueViolet, 1.0F),0,10,10,20);
pictureBox1.Image = DrawArea;
}
when I click button to remove a line
private void button3_Click_1(object sender, EventArgs e)
{
pictureBox1.Image = Previuos_DrawArea_img;
}
Concept :
1st step - Declare variable.
2nd step - Backup current picture.
3rd step - Draw new picture.
4th step - if undo just draw the backup picture.
You aren’t creating a copy of the bitmap, you’re only storing it in two variables. They point to the same bitmap so editing one affects the other one. You’ll need to create a copy:
Previuos_DrawArea_img = new Bitmap(DrawArea);
Now it is a separate image and whatever you do to one of them doesn’t affect the other one.

How to permanently display the placed image

I created a windows form that displays and image as a Logo. I was able to browse and display an image to the PictureBox with this code:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
I want the placed image saved in that PictureBox to be displayed every time the Form is called. What code do I need to write in order to do that?
On the load event of the form you can set the image of the picture box. By going to project settings, Resources tab, you can add an image as a Resource and reference it using the ProjectNamespace.Resources.NameOfResource.
You need a special kind of pictureBox that shows the logo. Let's call this a LogoBox. If you make this a user control you can use Visual Studio Toolbox to add it to your controls.
In Visual Studio:
Open the project where the LogoBox is to be used, or put it in a DLL, so it can be used by several executables.
Menu: Project - Add User Control, Name it LogoBox
Use the Toolbox to add a PictureBox to the user control.
Change the Dock style of picture box to DockStyle.Fill
Use properties to add an event handler for the Load Event, let's call it OnLoad.
Your LogoBox class will need a property to change the image that will be used as a logo. I use the same function as PictureBox.Image, but call it Logo:
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
}
}
This code is not enough: the next time you load this LogoBox you want it to load its last set Logo. The esiest method is to save the last set image in a file, because then you know certain that if the user of your LogoBox deletes the original image after setting it you still have your own saved copy.
You'll need a filename for the file. User project properties - settings to create a filename.
Make it a string property with application scope (it will never change)
Name: LogoFileName
Value: think of something nice. Logo.Img?
.
[BindableAttribute(true)]
public Image Logo
{
get {return this.pictureBox1.Image;}
set
{
this.pictureBox1.Image = image;
image.Save(Properties.Settings.Default.LogoFileName)
}
}
Finally load the image when your LogoBox is loaded:
private void OnFormLoading(object sender, EventArgs e)
{
var img = Image.FromFile(Properties.Settings.Default.LogoFileName);
this.pictureBox1.Image = img;
}
Don't use this.Logo = img, because that will save the image again which is a waste of time.
The only thing to do is error handling if the logo file does not exist.
Then lets have a static thing.
Within your form, implement a static paths for your image..say
public string prg_form_image
{
get { return "myimage.jpg"; }
}
public string prg_image_path
{
get { return this.AppDomain.CurrentDomain.BaseDirectory + "image\\"; }
}
private string myImage
{
get
{
return File.Exists(prg_image_path + prg_form_image)
? prg_image_path + prg_form_image
: prg_image_path + "default.jpg";
}
}
public Image img
{
get { return Image.FromFile(prg_image_path + prg_form_image); }
}
private void SetImage()
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = img;
}
private void Form_Load(object sender, EventArgs e)
{
SetImage();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "jpg (*.jpg)|*.jpg|bmp (*.bmp)|*.bmp|png (*.png)|*.png";
if (ofd.ShowDialog() == DialogResult.OK && ofd.FileName.Length > 0)
{
if(File.Exists(prg_image_path + prg_form_image))
{
File.Delete(prg_image_path + prg_form_image);
}
if(!Directory.Exists(prg_image_path)) { Directory.Create(prg_image_path); }
Image imgIn = Image.FromFile(ofd.FileName);
imgIn.SaveAs(prg_image_path + prg_form_image);
SetImage();
}
}
Notes : Folder name image should exists along-side your executable program. a default.jpg should also exist inside the folder image.

Printing a winform C# application

I created an application which is larger in size than an A4 paper . I placed a print button on my windows form and following the MSDN tried both printDocument and printForm . But both of them don't scale my image and print only half the screen .
I researched and found that somewhere it was advised to place all controls in a picturebox and print that , but I am looking for a better alternative before I go ahead changing the complete design of my application . Some places advised to go for a completely different route for crystal reports .
The task doesn't seem easy than I actually thought and now I am stuck .
Edit1 :Here is the code that I added to my Form . I did try using bitmaps but that did not resolve the problem too .
private void button1_Click(object sender, EventArgs e)
{
//Form3 dlg = new Form3();
//dlg.ShowDialog();
//CaptureScreen();
// printDocument2.Print();
printForm1.Print();
}
/* Bitmap memoryImage;
private void CaptureScreen()
{
Graphics myGraphics = this.CreateGraphics();
Size s = this.Size;
memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(memoryImage);
memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
}
private void printDocument2_PrintPage(System.Object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(memoryImage, 0, 0);
}
private void groupBox4_Enter(object sender, EventArgs e)
{
}*/
Is there a way if I can also possibly change the orientation to landscape ? I would like to try to see of that probably fits .
Edit2 : I found a way to print in the landscape mode and all the contents fit well . My application has a windows form and 3 tabs in it under a tab control . What I am trying to print is only the contents of the third tab which is the result window . Is there a way I can only print the contents of the tab control and not the entire form ?

How to create a video file out of bitmaps?

Is there any way for how to record the images into a video file (output.avi) by implementing some code inside the NewFrame event handler. Also how can we make the size of file not too much big?
I've got a pictureBox1 and a button1 and I'm using the code below to switch on the webcam and display the output on pictureBox1
The code works fine. However, I need to implement a way to Save the output to a video file rather than showing it on the pictureBox
I use the code below
private void button1_Click(object sender, EventArgs e)
{
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(video_NewFrame);
///
CloseVideoSource();
videoSource.Start();
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap img = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = img; // Something should go here to make the video file out of successive bitmaps ?
}
private void CloseVideoSource()
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
I think all you need is to use the VideoFileWriter class. There's a nice demo in the AForge.Net documentation.
Note that your code will need to include the FFMPEG dlls found in the Externals folder in your AForge installation directory.

Making a background image scale with button size

I'm trying to add some background images to a few buttons in my Win Forms application. The three images are different sizes (ie pixel dimensions don't match, one is 128x128 and another is 256x256). I need the buttons to be identical in size (otherwise the GUI is horribly asymmetrical). Without changing the actual image files, how can I get the images to scale with button size?
I've tried creating my own class, and adding an event handler for the button resize event, but that doesn't seem to work. My code:
class CustomButton : Button {
internal void CustomButton_Resize( object sender, EventArgs e ) {
if ( this.BackgroundImage == null ) {
return;
}
var pic = new Bitmap( this.BackgroundImage, this.Width, this.Height );
this.BackgroundImage = pic;
}
}
and in the form:
this.buttonOne.Resize += new System.EventHandler(this.buttonOne.CustomButton_Resize);
Forgot to mention, the above code does not resize the images at all. The buttons still need to have different sizes to display the images completely.
Easiest way to add a background image to a .NET Button object and scale it to fit
I used this method to avoid any additional coding of new classes and event handlers. This helped me also avoid converting all Button objects into Image objects.
Add image to your Resources.resx file.
Click on your chosen button.
Navigate to the BackgroundImage property and choose the image you imported into the project's resources.resx file.
Navigate to the BackgroundImageLayout property and choose Stretch.
Make sure you don't have anything entered for the Image and Text properties or else they will interfere with your new background image.
The easy programmatic way
Say I have a button btn1, Following code is working perfectly in visual-studio-2010.
private void btn1_Click(object sender, EventArgs e)
{
btn1.Width = 120;
btn1.Height = 100;
}
void btn1_Resize(object sender, EventArgs e)
{
if ( this.BackgroundImage == null )
return;
var bm = new Bitmap(btn1.BackgroundImage, new Size(btn1.Width, btn1.Height));
btn1.BackgroundImage = bm;
}
The better way
You can add eventHandler in the constructor of your custombutton (just to ensure that you are adding eventhandler correctly)
class CustomButton : Button
{
CustomButton()
{
this.Resize += new System.EventHandler(buttonOne.CustomButton_Resize);
}
void CustomButton_Resize( object sender, EventArgs e )
{
if ( this.BackgroundImage == null )
return;
var pic = new Bitmap( this.BackgroundImage, new Size(this.Width, this.Height) );
this.BackgroundImage = pic;
}
}
Now when you will resize the button anywhere your image will get fit(scaled) to its new size.
You could start with something like this...
public class ImageButton : Control
{
public Image backgroundImage;
public Image BackgroundImage
{
get
{
return backgroundImage;
}
set
{
backgroundImage = value;
Refresh();
}
}
public ImageButton()
{
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
if(BackgroundImage != null)
e.Graphics.DrawImage(BackgroundImage, 0, 0, Width, Height);
base.OnPaint(e);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
}
You can just handle paint and draw the image yourself. You may also try using a PictureBox or some other control which has more scaling options

Categories

Resources