以下是使用Python和GDAL库生成分块TIF文件的PNG缩略图的示例代码:

import os
from osgeo import gdal

# 定义输入和输出文件路径
input_tif = "input.tif"
output_png = "output.png"

# 打开输入TIF文件
dataset = gdal.Open(input_tif)

# 获取图像的宽度和高度
width = dataset.RasterXSize
height = dataset.RasterYSize

# 将图像分成16x16像素的块
tile_size = 16
x_blocks = width // tile_size
y_blocks = height // tile_size

# 创建输出PNG文件
driver = gdal.GetDriverByName("PNG")
out_dataset = driver.Create(output_png, tile_size * x_blocks, tile_size * y_blocks, 3)

# 遍历每个块并将其写入输出文件
for y in range(y_blocks):
    for x in range(x_blocks):
        # 从输入文件中读取块
        x_offset = x * tile_size
        y_offset = y * tile_size
        block = dataset.ReadAsArray(x_offset, y_offset, tile_size, tile_size)

        # 将块写入输出文件
        out_x_offset = x_offset
        out_y_offset = height - (y_offset + tile_size) # 翻转Y轴以匹配PNG文件的坐标系
        out_dataset.GetRasterBand(1).WriteArray(block[0], out_x_offset, out_y_offset)
        out_dataset.GetRasterBand(2).WriteArray(block[1], out_x_offset, out_y_offset)
        out_dataset.GetRasterBand(3).WriteArray(block[2], out_x_offset, out_y_offset)

# 关闭文件
dataset = None
out_dataset = None

该代码使用GDAL库打开输入TIF文件,将其分成16x16像素的块,然后遍历每个块并将其写入输出PNG文件。在写入块时,代码还需要翻转Y轴以匹配PNG文件的坐标系。最终,将生成一个PNG文件,其中包含分块TIF文件的缩略图

python 使用gdal分块方式生成tif文件的一张png缩略图

原文地址: https://www.cveoy.top/t/topic/eguD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录