WSL/SLF GitLab Repository

PNGIO.cc 13.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/***********************************************************************************/
/*  Copyright 2009 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of MeteoIO.
    MeteoIO is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MeteoIO is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "PNGIO.h"
#include <meteoio/ResamplingAlgorithms2D.h>
20
#include <meteoio/Graphics.h>
21
22
23
24
25
26
27

#include <algorithm>

using namespace std;

namespace mio {
/**
28
 * @page pngio PNGIO
29
30
 * @section template_format Format
 * *Put here the informations about the standard format that is implemented*
31
 * No data read, only write (because of gradients)
32
 * Finally, the naming scheme for meteo grids should be: YYYYMMDDHHmm_{MeteoGrids::Parameters}.png
33
34
35
36
37
38
 *
 * @section template_units Units
 *
 *
 * @section template_keywords Keywords
 * This plugin uses the following keywords:
39
40
41
 * - png_legend: plot legend on the side of the graph? (default: true)
 * - png_min_size: guarantee that a 2D plot will have at least the given size
 * - png_max_size: guarantee that a 2D plot will have at most the given size
42
43
 * - png_scaling: scaling algorithm, either nearest or bilinear (default=bilinear)
 * - png_autoscale: autoscale for the color gradient? (default= true)
44
 * - etc
45
46
47
48
49
50
51
52
53
 *
 * The size are specified as width followed by height, with the separator being either a space, 'x' or '*'. If a minimum and a maximum size are given, the average of the smallest and largest permissible sizes will be used.
 *
 * @code
 * GRID2D = PNG
 * png_legend = false
 * png_min_size = 400x400
 * png_max_size = 1366*768
 * @endcode
54
55
56
57
58
59
 */

const double PNGIO::plugin_nodata = -999.; //plugin specific nodata value. It can also be read by the plugin (depending on what is appropriate)

PNGIO::PNGIO(void (*delObj)(void*), const Config& i_cfg) : IOInterface(delObj), cfg(i_cfg)
{
60
	setOptions();
61
62
63
64
}

PNGIO::PNGIO(const std::string& configfile) : IOInterface(NULL), cfg(configfile)
{
65
	setOptions();
66
67
68
69
}

PNGIO::PNGIO(const Config& cfgreader) : IOInterface(NULL), cfg(cfgreader)
{
70
71
72
73
74
75
76
77
78
79
80
81
	setOptions();
}

void PNGIO::setOptions()
{
	//get size specifications
	std::string min_size, max_size;
	min_w = min_h = max_w = max_h = IOUtils::unodata;
	cfg.getValue("png_min_size", "Output", min_size, Config::nothrow);
	if(min_size!="") parse_size(min_size, min_w, min_h);
	cfg.getValue("png_max_size", "Output", max_size, Config::nothrow);
	if(max_size!="") parse_size(max_size, max_w, max_h);
82

83
84
85
86
	autoscale = true;
	cfg.getValue("png_autoscale", "Output", autoscale, Config::nothrow);
	has_legend = true;
	cfg.getValue("png_legend", "Output", has_legend, Config::nothrow);
87
88
	scaling = "bilinear";
	cfg.getValue("png_scaling", "Output", scaling, Config::nothrow);
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126

	if(has_legend) { //we need to save room for the legend
		if(min_w!=IOUtils::unodata) min_w -= legend::getLegendWidth();
		if(max_w!=IOUtils::unodata) max_w -= legend::getLegendWidth();
	}
}

void PNGIO::parse_size(const std::string& size_spec, unsigned int& width, unsigned int& height)
{
	char rest[32] = "";
	if(sscanf(size_spec.c_str(), "%u %u%31s", &width, &height, rest) < 2)
	if(sscanf(size_spec.c_str(), "%u*%u%31s", &width, &height, rest) < 2)
	if(sscanf(size_spec.c_str(), "%ux%u%31s", &width, &height, rest) < 2) {
		std::stringstream ss;
		ss << "Can not parse PNGIO size specification \"" << size_spec << "\"";
		throw InvalidFormatException(ss.str(), AT);
	}
	std::string tmp(rest);
	IOUtils::trim(tmp);
	if ((tmp.length() > 0) && tmp[0] != '#' && tmp[0] != ';') {//if line holds more than one value it's invalid
		std::stringstream ss;
		ss << "Invalid PNGIO size specification \"" << size_spec << "\"";
		throw InvalidFormatException(ss.str(), AT);
	}
}

double PNGIO::getScaleFactor(const double& grid_w, const double& grid_h)
{
	if(grid_w==0 || grid_h==0) {
		return 1.;
	}

	double min_factor = IOUtils::nodata;
	if(min_w!=IOUtils::unodata) { //min_w & min_w are read together
		const double min_w_factor = (double)min_w / (double)grid_w;
		const double min_h_factor = (double)min_h / (double)grid_h;
		min_factor = std::max(min_w_factor, min_h_factor);
	}
127

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
	double max_factor = IOUtils::nodata;
	if(max_w!=IOUtils::unodata) { //max_w & max_h are read together
		const double max_w_factor = (double)max_w / (double)grid_w;
		const double max_h_factor = (double)max_h / (double)grid_h;
		max_factor = std::min(max_w_factor, max_h_factor);
	}

	if(min_factor==IOUtils::nodata && max_factor==IOUtils::nodata)
		return 1.; //no user given specification
	if(min_factor!=IOUtils::nodata && max_factor!=IOUtils::nodata)
		return (min_factor+max_factor)/2.; //both min & max -> average

	//only one size specification provided -> return its matching factor
	if(min_factor!=IOUtils::nodata)
		return min_factor;
	else
		return max_factor;
145
146
147
148
149
150
151
}

PNGIO::~PNGIO() throw()
{

}

152
153
154
155
156
157
158
void PNGIO::read2DGrid(Grid2DObject&, const std::string&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::read2DGrid(Grid2DObject&, const MeteoGrids::Parameters& , const Date&)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::readDEM(DEMObject& /*dem_out*/)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::readLanduse(Grid2DObject& /*landuse_out*/)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::readAssimilationData(const Date& /*date_in*/, Grid2DObject& /*da_out*/)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::readStationData(const Date&, std::vector<StationData>& /*vecStation*/)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::readMeteoData(const Date& /*dateStart*/, const Date& /*dateEnd*/,
                             std::vector< std::vector<MeteoData> >& /*vecMeteo*/,
                             const size_t&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::writeMeteoData(const std::vector< std::vector<MeteoData> >& /*vecMeteo*/,
                              const std::string&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::readSpecialPoints(std::vector<Coords>&)
{
	//Nothing so far
	throw IOException("Nothing implemented here", AT);
}

void PNGIO::write2DGrid(const Grid2DObject& grid_in, const std::string& filename)
{
	FILE *fp;
	png_structp png_ptr=NULL;
	png_infop info_ptr=NULL;
	png_bytep row=NULL;

	//scale input image
217
	const double factor = getScaleFactor(grid_in.ncols, grid_in.nrows);
218
219
220
221
222
223
224
225
226
227
228
	Grid2DObject grid;
	if(scaling=="nearest")
		grid = ResamplingAlgorithms2D::NearestNeighbour(grid_in, factor);
	else if(scaling=="bilinear")
		grid = ResamplingAlgorithms2D::BilinearResampling(grid_in, factor);
	else {
		stringstream ss;
		ss << "Grid scaling algorithm \"" << scaling << "\" unknown";
		throw UnknownValueException(ss.str(), AT);
	}

229
	const double ncols = grid.ncols, nrows = grid.nrows;
230
231
	const double min = grid.grid2D.getMin();
	const double max = grid.grid2D.getMax();
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264

	// Open file for writing (binary mode)
	if (!IOUtils::validFileName(filename)) {
		throw InvalidFileNameException(filename, AT);
	}
	fp = fopen(filename.c_str(), "wb");
	if (fp == NULL) {
		throw FileAccessException(filename, AT);
	}

	// Initialize write structure
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (png_ptr == NULL) {
		fclose(fp);
		throw IOException("Could not allocate write structure", AT);
	}

	// Initialize info structure
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL) {
		fclose(fp);
		png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
		throw IOException("Could not allocate info structure", AT);
	}

	// Setup Exception handling
	if (setjmp(png_jmpbuf(png_ptr))) {
		cleanup(fp, png_ptr, info_ptr, row);
		throw IOException("Error during png creation", AT);
	}

	png_init_io(png_ptr, fp);

265
266
267
268
269
270
271
272
273
	unsigned int full_width=ncols;
	Array2D<double> legend_array;
	if(has_legend) {
		legend leg(nrows, min, max);
		legend_array = leg.getLegend();
		unsigned int nx, ny;
		legend_array.size(nx,ny);
		full_width += nx;
	}
274
	// Write header (8 bit colour depth)
275
	png_set_IHDR(png_ptr, info_ptr, full_width, nrows,
276
277
	             8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
	             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
278
279
	createMetadata(grid);
	writeMetadata(png_ptr, info_ptr);
280
281
282
	png_write_info(png_ptr, info_ptr);

	// Allocate memory for one row (4 bytes per pixel - RGBA)
283
	row = (png_bytep) malloc(4 * full_width * sizeof(png_byte));
284
285

	// Write image data
286
	Gradient gradient(Gradient::terrain, min, max, autoscale);
287
288
	for(int y=nrows-1 ; y>=0 ; y--) {
		for(unsigned int x=0 ; x<ncols ; x++) {
289
290
291
292
			const unsigned int i=x*4;
			unsigned char r,g,b,a;
			gradient.getColor(grid(x,y), r,g,b,a);
			row[i]=r; row[i+1]=g; row[i+2]=b; row[i+3]=a;
293
294
		}
		for(unsigned int x=ncols; x<full_width; x++) {
295
296
297
298
299
			//setRGB( legend_array(x-ncols,y), min, max, &(row[x*4]) );
			const unsigned int i=x*4;
			unsigned char r,g,b,a;
			gradient.getColor(legend_array(x-ncols,y), r,g,b,a);
			row[i]=r; row[i+1]=g; row[i+2]=b; row[i+3]=a;
300
301
302
303
304
305
306
307
		}
		png_write_row(png_ptr, row);
	}

	png_write_end(png_ptr, NULL);
	cleanup(fp, png_ptr, info_ptr, row);
}

308
309
310
311
312
313
314
void PNGIO::write2DGrid(const Grid2DObject& grid_in, const MeteoGrids::Parameters& parameter, const Date& date)
{
	std::stringstream ss;
	ss << date.toString(Date::NUM) << "_" << MeteoGrids::getParameterName(parameter) << ".png";
	write2DGrid(grid_in, ss.str());
}

315
316
317
318
319
void PNGIO::cleanup() throw()
{

}

320
void PNGIO::createMetadata(const Grid2DObject& grid)
321
{
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
	const double lat = grid.llcorner.getLat();
	const double lon = grid.llcorner.getLon();
	stringstream ss;

	metadata_key.push_back("Title");
	metadata_text.push_back("Gridded data"); //HACK: write meteogrid parameter, date
	metadata_key.push_back("Author");
	metadata_text.push_back(IOUtils::getLogName());
	metadata_key.push_back("Software");
	metadata_text.push_back("MeteoIO "+getLibVersion());
	metadata_key.push_back("Position");
	metadata_text.push_back("llcorner");
	metadata_key.push_back("Cellsize");
	ss.str(""); ss << fixed << setprecision(2) << grid.cellsize;
	metadata_text.push_back(ss.str());
	metadata_key.push_back("Latitude");
	ss.str(""); ss << fixed << setprecision(6) << lat;
	metadata_text.push_back(ss.str());
	metadata_key.push_back("Longitude");
	ss.str(""); ss << fixed << setprecision(6) << lon;
	metadata_text.push_back(ss.str());
343

344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
	if(lat<0.) {
		metadata_key.push_back("LatitudeRef");
		metadata_text.push_back("S");
		metadata_key.push_back("GPSLatitude");
		metadata_text.push_back(decimal_to_dms(-lat));
	} else {
		metadata_key.push_back("LatitudeRef");
		metadata_text.push_back("N");
		metadata_key.push_back("GPSLatitude");
		metadata_text.push_back(decimal_to_dms(lat));
	}
	if(lon<0.) {
		metadata_key.push_back("LongitudeRef");
		metadata_text.push_back("W");
		metadata_key.push_back("GPSLongitude");
		metadata_text.push_back(decimal_to_dms(-lon));
	} else {
		metadata_key.push_back("LongitudeRef");
		metadata_text.push_back("E");
		metadata_key.push_back("GPSLongitude");
		metadata_text.push_back(decimal_to_dms(lon));
	}
366

367
	//add data set timestamp
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
}

void PNGIO::writeMetadata(png_structp &png_ptr, png_infop &info_ptr)
{
	const size_t nr = metadata_key.size();
	png_text *info_text;
	info_text = (png_text *)calloc(sizeof(png_text), nr);
	char **key, **text;
	key = (char**)calloc(sizeof(char)*80, nr);
	text = (char**)calloc(sizeof(char)*80, nr);

	for(size_t ii=0; ii<nr; ii++) {
		key[ii] = (char *)calloc(sizeof(char), 80);
		text[ii] = (char *)calloc(sizeof(char), 80);
		strncpy(key[ii], metadata_key[ii].c_str(), 80);
		strncpy(text[ii], metadata_text[ii].c_str(), 80);
		info_text[ii].key = key[ii];
		info_text[ii].text = text[ii];
		info_text[ii].compression = PNG_TEXT_COMPRESSION_NONE;
	}
388

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
	png_set_text(png_ptr, info_ptr, info_text, nr);
	free(info_text);
	for(size_t ii=0; ii<nr; ii++) {
		free(key[ii]);
		free(text[ii]);
	}
	free(key);
	free(text);
}

std::string PNGIO::decimal_to_dms(const double& decimal) {
	std::stringstream dms;
	const int d = static_cast<int>( floor(decimal) );
	const double m = floor( ((decimal - (double)d)*60.)*100. ) / 100.;
	const double s = 3600.*(decimal - (double)d) - 60.*m;

	dms << d << "/1 " << static_cast<int>(m*100) << "/100 " << fixed << setprecision(6) << s << "/1";
	return dms.str();
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
}

void PNGIO::cleanup(FILE *fp, png_structp png_ptr, png_infop info_ptr, png_bytep row)
{
	if (fp != NULL) fclose(fp);
	if (info_ptr != NULL) png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
	if (png_ptr != NULL) png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
	if (row != NULL) free(row);
}

#ifndef _METEOIO_JNI
extern "C"
{
#define COMPILE_PLUGIN
#include "exports.h"

	METEOIO_EXPORT void deleteObject(void* obj) {
		delete reinterpret_cast<PluginObject*>(obj);
	}

	METEOIO_EXPORT void* loadObject(const string& classname, const Config& cfg) {
		if(classname == "PNGIO") {
			//cerr << "Creating dynamic handle for " << classname << endl;
			return new PNGIO(deleteObject, cfg);
		}
		//cerr << "Could not load " << classname << endl;
		return NULL;
	}
}
#endif

} //namespace