openlayer4地图及图层导出图片问题小结
直接使用ol4中的地图导出功能在我们的项目中可能会存在跨域问题,导致地图不能正常的转为二进制。
解决方法:
1 //自定义图层中添加crossOrigin,具体如下:
var tdtTerLayer = new ol.layer.Tile({
visible: true,
source: new ol.source.XYZ({
crossOrigin: ‘anonymous’,
url: tdtter
})
});
var edge = new ol.layer.Image({
source: new ol.source.ImageArcGISRest({
crossOrigin: ‘anonymous’,
ratio: 1,
params: {},
url: jsmap
})
});
2//叠加显示
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({}),
new ol.control.ZoomSlider({}),
new ol.control.ZoomToExtent({})]),
target: ‘map’,
layers: [
tdtTerLayer, edge
// openstreemap,contries
],
view: new ol.View({
maxZoom: 19,
minZoom: 6,
projection: epsgWMproj,
center: ol.proj.transform([120.3351, 31.1918], epsg84proj, epsgWMproj),
zoom: 8
})
});
3//导出函数
function readBlobAsDataURL(blob, callback) {
var a = new FileReader();
a.onload = function (e) {
callback(e.target.result);
}
a.readAsDataURL(blob);
}
$(“#savemap”).click(function () {
map.once(‘postcompose’, function (event) {
var canvas = event.context.canvas;
var SLT_pic = new ArrayBuffer();
if (navigator.msSaveBlob) {
var ttt = canvas.msToBlob();//此处将图片转成二进制
readBlobAsDataURL(ttt, function (dataurl)
{
var name = “testpic.png”;
post_webservice_async_json({ “oper”: “SaveIMG”,”picname”:name,”oge”: dataurl });
})
} else {
canvas.toBlob(function (blob) {
var mmm = blob;
alert(“Binary pic”,mmm);
});
}
});
map.renderSync();
});
function post_webservice_async_json(paramObj) {
var returnStr = “”;
var defer = $.Deferred();
$.ajax({
type: ‘post’,
async: true,
dataType: ‘json’,
url: ‘Test.ashx’,
traditional: true,
data: { paramInfo: JSON.stringify(paramObj) },
success: function (data) {
//alert(“保存图层成功”);
defer.resolve(data);
}
})
return defer.promise();
}
4//图片保存
string res;
string paramInfo = null;
paramInfo = context.Request.Form[“paramInfo”];
//图片读取
if (paramInfo != null && paramInfo != “”)
{
JavaScriptSerializer aa = new JavaScriptSerializer();
Dictionary<string, string> dic = aa.Deserialize<Dictionary<string, string>>(paramInfo);
string obj = dic[“oge”].Replace(” “, “+”).Split(‘,’)[1];
byte[] array = Convert.FromBase64String(obj);
string oper = dic[“oper”];
string picname = dic[“picname”];
//图片保存到当前项目文件下
MemoryStream ms = new MemoryStream(array);
Image image = new Bitmap(ms);
image.Save(context.Server.MapPath(@”~2.png”));
}
转载自:https://blog.csdn.net/pdw521/article/details/78563217