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

Haj*_*tsu 5 c# clipboard image copy-paste

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

编辑:我使用此代码但该用户只能将图像粘贴到word中.

var img = Image.FromFile(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetImage(img);
Run Code Online (Sandbox Code Playgroud)

Ara*_*ani 5

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

您可以简单地将该图像文件的路径添加到 a 中StringCollection,然后调用 的SetFileDropList方法Clipboard来实现您想要的。

System.Collections.Specialized.StringCollection FileCollection = new System.Collections.Specialized.StringCollection();
FileCollection.Add(pnlContent_Picture_PictureBox.ImageLocation);
Clipboard.SetFileDropList(FileCollection);
Run Code Online (Sandbox Code Playgroud)

现在用户可以将文件粘贴到任何地方,例如 Windows 资源管理器。

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

  • 完全有效,但是这个方法有什么问题:`Clipboard.SetImage(pictureBox1.Image);` (2认同)

ja7*_*a72 5

这是当图片框不显示文件图像,但使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)