想截取浏览器上内容,并做成图片保存到本地。
可以使用html2canvas.js进行操作。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="~/Jquery/jquery-1.10.2.js"></script> <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script> </head> <body> @*原始图片*@ <div class="my-div"> <img style="width: 400px; height: 300px" src="~/Img/longmao.jpg" /> </div> <br /> <input type="button" onclick="set()" value="截图" /> @*截取后存放图片的位置*@ <img id="img" /> <script> function set() { //要转换为图片的dom对象 var element = document.querySelector(‘.my-div‘); //要显示图片的img标签 var image = document.querySelector(‘#img‘); //调用html2image方法 html2image(element, image); function html2image(element, image) { html2canvas(element).then(function (canvas) { var imageData = canvas.toDataURL(1); //此时图片已经可以显示了 image.src = imageData; }); } } </script> </body> </html>
把数据传入后台,将图片保存到本地。传输后台的数据是Base64的数据,需要转换
public string Set(string imgdata) { try { var strbase64 = imgdata; string dummyData = strbase64.Trim().Replace("data:image/png;base64,", "").Replace("%", "").Replace(",", "").Replace(" ", "+"); if (dummyData.Length % 4 > 0) { dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, ‘=‘); } byte[] arr = Convert.FromBase64String(dummyData); MemoryStream ms = new MemoryStream(arr); Bitmap bmp = new Bitmap(ms); var imagePath = AppDomain.CurrentDomain.BaseDirectory + "123.png"; bmp.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png); ms.Close(); } catch (Exception ex) { Console.WriteLine(ex); return TAjaxCallBack.ERROR; } }
原文地址:https://www.cnblogs.com/xiaoyaodijun/p/9268929.html
时间: 2024-11-02 10:48:12