如何在 OpenLayers 3 中禁用平滑图像

Howto Disable smooth image on OpenLayers 3

我正在尝试使用 OpenLayer 在地图上查看图像,我的图像是遵循 SRID:4326 的 PNG。我设置了一个 OpenLayers 地图并设置了投影信息,以便在 OpenLayer SRID (3857) 中重新投影我的图像。

现在..我的问题是 OpenLayer 以平滑的颜色显示我的分类 PNG。我需要查看没有平滑颜色渲染的 PNG。

实际上我的 OpenLayers 地图显示了这张图片

但我需要查看没有平滑颜色的图像。

有什么想法吗?

更新:如果我禁用平滑选项,按照下面的答案,输出图像将在没有平滑的情况下呈现......但是有些像素呈现的颜色错误(使用更亮的着色器或更少的不透明度)

这是输出图像:

但输出应该是:

问题不在 ol 上,而是在 HTML5 Canvas 渲染上。您必须关闭地图上的图像平滑 canvas。看看 imageSmoothingEnabled option.

使用 Openlayers,您可以使用 precompose/postcompose 事件仅为您的层禁用它:

// Remove image smoothing on precompose
layer.on('precompose', function(event) {
  var ctx = event.context;
  ctx.mozImageSmoothingEnabled = 
  ctx.webkitImageSmoothingEnabled = 
  ctx.msImageSmoothingEnabled = 
  ctx.imageSmoothingEnabled = false;
}
// Restore image smoothing on postcompose
layer.on('postcompose', function(event) {
  var ctx = event.context;
  ctx.mozImageSmoothingEnabled = 
  ctx.webkitImageSmoothingEnabled = 
  ctx.msImageSmoothingEnabled = 
  ctx.imageSmoothingEnabled = true;
}

注意:它取决于导航器...

上面的回答解决了我的问题。但我也找到了这个解决方案

  map.on('precompose', function(evt) {
    evt.context.imageSmoothingEnabled = false;
    evt.context.webkitImageSmoothingEnabled = false;
    evt.context.mozImageSmoothingEnabled = false;
    evt.context.msImageSmoothingEnabled = false;
});

使用这段代码,我可以为我的 OL 地图上的每一层禁用平滑。

我知道这是一个老问题了,但我已经研究了几个小时并最终解决了这个问题,所以我认为其他人可能会觉得这有帮助。

自 OpenLayers 网站上的 OpenLayers 6.4.0, you can disable image smoothing for a source (code sample below is from this example 以来:

var disabledLayer = new TileLayer({
  // specify className so forEachLayerAtPixel can distinguish layers
  className: 'ol-layer-dem',
  source: new XYZ({
    attributions: attributions,
    url:
      'https://api.maptiler.com/tiles/terrain-rgb/{z}/{x}/{y}.png?key=' + key,
    maxZoom: 10,
    crossOrigin: '',
    imageSmoothing: false,
  }),
});

注意:确保在 source 上设置 imageSmoothing: false,而不是图层!如果你在层上设置它不会导致任何错误,但它不会实现任何东西;)

我发现如果我希望像素化按照我期望的方式工作,我需要在源上设置 imageSmoothing: false,然后在源上设置 maxZoom 以减少比我在层和视图上设置为 maxZoom 的值(例如,在源上设置 maxZoom: 14,在层和视图上设置 maxZoom: 19)。然后我得到了我想要的漂亮的实心块状像素,没有任何失真或阴影或任何像素内的不正确值。

最后,确保图层上的 maxZoom 设置与视图上的 maxZoom 设置相同,否则您的用户将能够放大太多,您的图层将消失。