博主喝口茶,一毛也是爱

收缩

C# 复制图片到剪切板

1157 人阅读
分类:

我们经常会使用QQ截图工具,截图完成之后就可以直接复制图片到QQ或微信上,非常方便

如果我们网页上有张图片,图片下面有个复制按钮,点击按钮之后,就复制图片到剪切板怎么操作?


后端代码

实现复制图片逻辑

public class ValuesController : ApiController
{
    [HttpGet]
    public ResMsgModel CopyImgToClipboard(string imgFileUrl)
    {
        string imgFilePath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("/Images"), 
                Path.GetFileName(imgFileUrl));

        string result = startCopyImg(imgFilePath);

        ResMsgModel resMsgModel = new ResMsgModel();
        if (result == "1")
        {
            resMsgModel.Success = true;
        }
        else
        {
            resMsgModel.Msg = result;
        }
        return resMsgModel;
    }

    //开始复制图片
    private string startCopyImg(string imgFilePath)
    {
    	//Exe: CopyImgToClipboard.exe 所在文件夹
        string currentWorkDir = System.Web.Hosting.HostingEnvironment.MapPath("/Exe");
        string exeFilePath = Path.Combine(currentWorkDir, "CopyImgToClipboard.exe");

        System.Diagnostics.Process p = new System.Diagnostics.Process();
        //需要启动的程序名
        p.StartInfo.FileName = exeFilePath;
        //启动参数    
        p.StartInfo.Arguments = imgFilePath;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.CreateNoWindow = true;
        p.Start();//启动
        p.StandardInput.WriteLine("");
        p.StandardInput.WriteLine("exit");
        //返回1表示成功
        string Re = p.StandardOutput.ReadToEnd();
        p.StandardOutput.Close();
        p.WaitForExit();
        p.Close();

        return Re;
    }
}

public class ResMsgModel
{
    public bool Success { set; get; }

    public string Msg { set; get; }
}

上面是使用图片绝对路径,执行CopyImgToClipboard.exe文件实现复制

那么CopyImgToClipboard.exe里面做了什么呢?其实很简单...


CopyImgToClipboard.exe内代码

[STAThread]
static void Main(string[] args)
{
    string result = "";
    try
    {
        if (args == null || args.Length <= 0)
        {
            result = "请传入参数";
        }
        else
        {
            string imgFilePath = args[0];
            Image img = Image.FromFile(imgFilePath);

            //需要添加引用 System.Windows.Forms
            Clipboard.SetImage(img);
            result = "1";
        }
    }
    catch (Exception ex)
    {
        result = ex.Message;
    }

    Console.Write(result);
}

其实CopyImgToClipboard.exe就是控制台程序,使用cmd命令调用exe文件实现复制图片到剪切板

源码下载: http://download.csdn.net/download/jx_521/10201195

如果是网页端复制图片到剪切板上面并不适用,请参考:JavaScript 网页端复制图片到剪切板


和博主交个朋友吧
    发布篇幅
    • 文章总数:0
    • 原创:0
    • 转载:0
    • 译文:0
    文章分类
      文章存档
      阅读排行