def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
'''
create raster from 2D array
Args:
newRasterfn: the path of generated tiff file
rasterOrigin: the start longitude and latitude
pixelWidth: the grid distance of longitude
pixelHeight: the grid distance of latitude
array: the 2D array to create tiff
Returns:
none
'''
cols = array.shape[1]
rows = array.shape[0]
originX = rasterOrigin[0]
originY = rasterOrigin[1]
#Create Color Table
ct = gdal.ColorTable()
ctmap1 = {0:(255,255,255,255)}
ctmap = {0:(192,192,254,255),1:(122,114,238,255),2:(30,38,130,255),3:(166,252,168,255),4:(0,234,0,255)
,5:(16,146,26,255),6:(252,244,100,255),7:(200,200,2,255),8:(140,140,0,255),9:(254,172,172,255)
,10:(254,100,92,255),11:(238,2,48,255),12:(212,142,254,255),13:(170,36,250,255)}
for i in range(256):
index = i/5;
index = min(index,len(ctmap)-1)
if i == 0:
ct.SetColorEntry(i,ctmap1[0])
else:
ct.SetColorEntry(i,ctmap[index])
#open geotiff
driver = gdal.GetDriverByName('GTiff')
if os.path.exists(newRasterfn):
os.remove(newRasterfn)
outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Byte)
#Add Color Table
outRaster.GetRasterBand(1).SetRasterColorTable(ct)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
#Write Date to geotiff
outband = outRaster.GetRasterBand(1)
ndv = -3.4028230607371e+38
outband.SetNoDataValue(ndv)
outband.WriteArray(array)
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(4326)
outRaster.SetProjection(outRasterSRS.ExportToWkt())
#Close Geotiff
outband.FlushCache()
del outRaster
http://wenku.baidu.com/view/7293b71755270722192ef792.html?re=view