Allow user to copy image from picturebox and save it everywhere

余生颓废 提交于 2019-12-04 08:19:40
Arash Milani

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!