Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow user to copy image from picturebox and save it everywhere

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);
like image 744
Hajitsu Avatar asked May 14 '13 14:05

Hajitsu


2 Answers

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

like image 191
Arash Milani Avatar answered Oct 16 '22 13:10

Arash Milani


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
    }
}
like image 5
John Alexiou Avatar answered Oct 16 '22 11:10

John Alexiou