我试过这样的
protected void Page_Load(object sender, EventArgs e)
{
//saveURLToImage("http://localhost:2564/Pagetoimage.aspx?OrderId=7");
saveURLToImage("http://www.w3schools.com/");
}
private void saveURLToImage(string url)
{
if (!string.IsNullOrEmpty(url))
{
string content = "";
System.Net.WebRequest webRequest = WebRequest.Create(url);
System.Net.WebResponse webResponse = webRequest.GetResponse();
System.IO.StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
content = sr.ReadToEnd();
//save to file
byte[] b = Convert.FromBase64String(content);
System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
string folderPath = Server.MapPath("~/ImagesFolder/"); //Create a Folder in your Root directory on your solution.
string fileName = "IMageName" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".jpg";
string imagePath = folderPath + fileName;
img.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();
ms.Close();
}
}
但是这个错误即将到来
输入不是有效的Base-64字符串,因为它包含非基数64 字符,两个以上的填充字符或非法字符 在填充字符中。
请帮帮我。
答案 0 :(得分:0)
你可以在这里使用画布。将此脚本添加到.aspx页面
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("selector")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
并将你的功能改为像这样
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
string folderPath = Server.MapPath("~/Images/"); //Create a Folder in your Root directory on your solution.
string fileName = "IMageName" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".jpg";
string imagePath = folderPath + fileName;
img.Save(imagePath, System.Drawing.Imaging.ImageFormat.Png);
在页面上添加一个按钮,您必须单击该按钮调用此函数,并在客户端单击时调用ConvertToImage()函数。并且还添加一个隐藏字段,如下所示: -
<asp:HiddenField ID="hfImageData" runat="server" />
<asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false"
OnClick="saveURLToImage" OnClientClick="return ConvertToImage(this)" />
现在,当您单击按钮时,它将在指定的路径上保存服务器上的网页图像。并且您可以更改要捕获其图像的jquery选择器。此解决方案使用jquery和canvas来确保导入库。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>