GDAL创建JPG或PNG格式图像

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图像:
imglink1

原文地址:https://www.cnblogs.com/charlee44/p/15506399.html