Skip to content

Instantly share code, notes, and snippets.

@andrewxhill
Created December 8, 2011 17:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewxhill/1447686 to your computer and use it in GitHub Desktop.
Save andrewxhill/1447686 to your computer and use it in GitHub Desktop.
ST_ClipEx a working variation of ST_Clip for raster
CREATE OR REPLACE FUNCTION ST_ClipEx(rast raster, x int, y int, width int, height int)
RETURNS raster AS
$$
DECLARE
newrast raster := ST_MakeEmptyRaster(width, height, ST_UpperLeftX(rast), ST_UpperLeftY(rast),
ST_ScaleX(rast), ST_ScaleY(rast), ST_SkewX(rast), ST_SkewY(rast), ST_SRID(rast));
numband int := ST_Numbands(rast);
band int;
cx int;
cy int;
newwidth int := CASE WHEN x + width > ST_Width(rast) THEN ST_Width(rast) - x ELSE width END;
newheight int := CASE WHEN y + height > ST_Height(rast) THEN ST_Height(rast) - y ELSE height END;
BEGIN
FOR band IN 1..numband LOOP
newrast := ST_AddBand(newrast, '8BUI'::text, 0, 0);
FOR cx IN 1..newwidth LOOP
FOR cy IN 1..newheight LOOP
newrast := ST_SetValue(newrast, band, cx, cy, ST_Value(rast, band, cx + x - 1, cy + y - 1));
END LOOP;
END LOOP;
END LOOP;
RETURN newrast;
END;
$$
LANGUAGE 'plpgsql';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment