1. 概述
根據GDAL文檔,JPG/PNG格式支持讀取和批量寫入,但不支持實時更新。也就是不支持Create()方法,但是支持CreateCopy()方法。也可能是由於JPG/PNG格式是輕量化的壓縮格式決定的。
2. 實現
具體的實例如下:
#include <iostream>
#include <gdal_priv.h>
using namespace std;
int main()
{
GDALAllRegister(); //GDAL所有操作都需要先注冊格式
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); //支持中文路徑
//圖像參數
string tilePath = "D:/1.png";
//string tilePath = "D:/1.jpg";
int tileSizeX = 256;
int tileSizeY = 256;
int dstBand = 3;
int dstDepth = 1;
//分配緩沖區
size_t tileBufSize = (size_t)tileSizeX * tileSizeY * dstBand;
GByte *tileBuf = new GByte[tileBufSize];
memset(tileBuf, 0, tileBufSize * sizeof(GByte));
//繪制一個斜線
for (int yi = 0; yi < tileSizeY; yi++)
{
for (int xi = 0; xi < tileSizeX; xi++)
{
if (xi != yi)
{
continue;
}
size_t m = (size_t)tileSizeX * dstBand * yi + dstBand * xi;
for (int bi = 0; bi < dstBand; bi++)
{
tileBuf[m + bi] = 255;
}
}
}
//把數據保存到臨時文件MEM
GDALDriver *pDriverMEM = GetGDALDriverManager()->GetDriverByName("MEM");
GDALDataset *pOutMEMDataset = pDriverMEM->Create("", tileSizeX, tileSizeY, dstBand, GDT_Byte, NULL);
if (!pOutMEMDataset)
{
printf("Can't Write Image!");
return false;
}
pOutMEMDataset->RasterIO(GF_Write, 0, 0, tileSizeX, tileSizeY, tileBuf, tileSizeX, tileSizeY,
GDT_Byte, dstBand, nullptr, dstBand*dstDepth, tileSizeX*dstBand*dstDepth, dstDepth);
//以創建復制的方式,生成png文件
GDALDriver *pDriverPNG = GetGDALDriverManager()->GetDriverByName("PNG");
//GDALDriver *pDriverPNG = GetGDALDriverManager()->GetDriverByName("JPEG");
GDALDataset* tile = pDriverPNG->CreateCopy(tilePath.c_str(), pOutMEMDataset, TRUE, 0, 0, 0);
if (!tile)
{
printf("Can't Write Image!");
return false;
}
GDALClose(pOutMEMDataset);
pOutMEMDataset = nullptr;
GDALClose(tile);
tile = nullptr;
if (tileBuf)
{
delete[] tileBuf;
tileBuf = nullptr;
}
}
這里創建了一個畫着對角線的JPG/PNG圖像: