允许用户从图片框中复制图像并将其保存在任何地方

时间:2013-05-14 14:46:35

标签: c# image clipboard copy-paste

在我的应用程序中,我有一个显示图像的pictureBox。当用户右键单击pictureBox并从上下文菜单中选择Copy时,我想将图像复制到剪贴板中,以便用户可以将其粘贴到文件夹和其他任何位置。我怎样才能做到这一点?

编辑:我使用此代码,但此用户只能将图片粘贴到文字中。

var img = Image.FromFile(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetImage(img);

2 个答案:

答案 0 :(得分:4)

Clipboard.SetImage将图像内容(二进制数据)复制到剪贴板而不是文件路径。要在Windows资源管理器中粘贴文件,您需要在剪贴板中收集文件路径而不是其内容。

您只需将该图片文件的路径添加到StringCollection,然后调用SetFileDropList Clipboard方法即可实现您想要的效果。

System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();
FileCollection.Add(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetFileDropList(FileCollection);

现在用户可以在任何地方通过文件,例如Windows资源管理器。

有关Clipboard.SetFileDropList Method http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard.setfiledroplist.aspx

的更多信息

答案 1 :(得分:3)

这是图片框不显示文件图像时的解决方案,但是使用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
    }
}