WSL/SLF GitLab Repository

PNGIO.cc 24.2 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

#include <algorithm>
23
#include <errno.h>
24
#include <zlib.h>
25
26
27
28
29

using namespace std;

namespace mio {
/**
30
 * @page pngio PNGIO
31
 * @section template_format Format
32
33
34
35
 * This plugin write data to the Portable Network Graphics format (see https://secure.wikimedia.org/wikipedia/en/wiki/Portable_Network_Graphics).
 * No data read has been implemented, because reading an existing file would require the exact knowlege of the color gradient that has been used
 * to create it. When writing grids, various color gradients will be used depending on the parameter that the data represents. Nodata values
 * are represented by transparent pixels (transparency is acheived through a transparent color instead of a true alpha channel for size and performance).
36
 * Finally, the naming scheme for meteo grids should be: YYYY-MM-DDTHH.mm_{MeteoGrids::Parameters}.png
37
38
 *
 * @section template_units Units
39
 * All units are MKSA except temperatures that are expressed in celcius.
40
41
42
 *
 * @section template_keywords Keywords
 * This plugin uses the following keywords:
43
44
 * - COORDSYS: input coordinate system (see Coords) specified in the [Output] section
 * - COORDPARAM: extra input coordinates parameters (see Coords) specified in the [Output] section
45
46
47
48
49
50
51
 * - GRID2DPATH: meteo grids directory where to read the grids; [Output] section
 * - 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
 * - PNG_SCALING: scaling algorithm, either nearest or bilinear (default=bilinear)
 * - PNG_AUTOSCALE: autoscale for the color gradient? (default=true)
 * - PNG_WORLD_FILE: create world file with each file? (default=false)
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.
54
55
56
57
58
59
60
61
62
63
64
 * The world file is used for geolocalization and goes alongside the graphics output. By convention,
 * the file has the same name as the image file, with the third letter of the extension jammed with a w: tif->tfw, jpg->jqw.
 * The format is the following:
 * @code
 *    5.000000000000 (size of pixel in x direction)
 *    0.000000000000 (rotation term for row)
 *    0.000000000000 (rotation term for column)
 *    -5.000000000000 (size of pixel in y direction)
 *    492169.690845528910 (x coordinate of centre of upper left pixel in map units)
 *    5426523.318065105000 (y coordinate of centre of upper left pixel in map units)
 * @endcode
65
 *
66
 * @section example Example use
67
68
69
70
71
72
 * @code
 * GRID2D = PNG
 * png_legend = false
 * png_min_size = 400x400
 * png_max_size = 1366*768
 * @endcode
73
74
75
 */

const double PNGIO::plugin_nodata = -999.; //plugin specific nodata value. It can also be read by the plugin (depending on what is appropriate)
76
77
78
const unsigned char PNGIO::channel_depth = 8;
const unsigned char PNGIO::channel_max_color = 255;
const unsigned char PNGIO::transparent_grey = channel_max_color;
79
80
81
const bool PNGIO::indexed_png = true;
const bool PNGIO::optimize_for_speed = true;
const unsigned int PNGIO::nr_levels = 30;
82
83
84

PNGIO::PNGIO(void (*delObj)(void*), const Config& i_cfg) : IOInterface(delObj), cfg(i_cfg)
{
85
	setOptions();
86
87
88
89
}

PNGIO::PNGIO(const std::string& configfile) : IOInterface(NULL), cfg(configfile)
{
90
	setOptions();
91
92
93
94
}

PNGIO::PNGIO(const Config& cfgreader) : IOInterface(NULL), cfg(cfgreader)
{
95
96
97
98
99
	setOptions();
}

void PNGIO::setOptions()
{
100
101
	cfg.getValue("COORDSYS", "Output", coordout);
	cfg.getValue("COORDPARAM", "Output", coordoutparam, Config::nothrow);
102
	cfg.getValue("GRID2DPATH", "Output", grid2dpath);
103
104
	//cfg.getValue("TIME_ZONE", "Output", tz_out, Config::nothrow);

105
106
107
	//get size specifications
	std::string min_size, max_size;
	min_w = min_h = max_w = max_h = IOUtils::unodata;
108
	cfg.getValue("PNG_MIN_SIZE", "Output", min_size, Config::nothrow);
109
	if(min_size!="") parse_size(min_size, min_w, min_h);
110
	cfg.getValue("PNG_MAX_SIZE", "Output", max_size, Config::nothrow);
111
	if(max_size!="") parse_size(max_size, max_w, max_h);
112

113
	autoscale = true;
114
	cfg.getValue("PNG_AUTOSCALE", "Output", autoscale, Config::nothrow);
115
	has_legend = true;
116
	cfg.getValue("PNG_LEGEND", "Output", has_legend, Config::nothrow);
117
	scaling = "bilinear";
118
	cfg.getValue("PNG_SCALING", "Output", scaling, Config::nothrow);
119
	has_world_file=false;
120
	cfg.getValue("PNG_WORLD_FILE", "Output", has_world_file, Config::nothrow);
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

	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);
	}
159

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
	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;
177
178
}

179
PNGIO::~PNGIO() throw() {
180
181
182

}

183
184
185
186
187
188
189
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&)
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
{
	//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);
}

240
241
Grid2DObject PNGIO::scaleGrid(const Grid2DObject& grid_in)
{ //scale input image
242
	const double factor = getScaleFactor(grid_in.ncols, grid_in.nrows);
243
	if(scaling=="nearest")
244
		return ResamplingAlgorithms2D::NearestNeighbour(grid_in, factor);
245
	else if(scaling=="bilinear")
246
		return ResamplingAlgorithms2D::BilinearResampling(grid_in, factor);
247
248
249
250
251
	else {
		stringstream ss;
		ss << "Grid scaling algorithm \"" << scaling << "\" unknown";
		throw UnknownValueException(ss.str(), AT);
	}
252
}
253

254
void PNGIO::setFile(const std::string& filename, png_structp& png_ptr, png_infop& info_ptr, const unsigned int &width, const unsigned int &height)
255
{
256
257
258
259
	// Open file for writing (binary mode)
	if (!IOUtils::validFileName(filename)) {
		throw InvalidFileNameException(filename, AT);
	}
260
	errno=0;
261
262
	fp = fopen(filename.c_str(), "wb");
	if (fp == NULL) {
263
264
265
		stringstream ss;
		ss << "Error openning file \"" << filename << "\", possible reason: " << strerror(errno);
		throw FileAccessException(ss.str(), AT);
266
267
268
269
270
271
272
273
274
275
276
277
278
279
	}

	// 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);
280
		free(png_ptr);
281
282
283
284
285
		throw IOException("Could not allocate info structure", AT);
	}

	// Setup Exception handling
	if (setjmp(png_jmpbuf(png_ptr))) {
286
		closePNG(png_ptr, info_ptr, NULL);
287
		throw IOException("Error during png creation. Can not set jump pointer (I have no clue what it means too!)", AT);
288
289
290
291
	}

	png_init_io(png_ptr, fp);

292
293
	//png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
	if(optimize_for_speed) png_set_compression_level(png_ptr, Z_BEST_SPEED);
294
295
	png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB|PNG_FILTER_UP); //any other filter is costly and brings close to nothing...
	if(indexed_png) png_set_compression_strategy(png_ptr, Z_RLE); //Z_DEFAULT_STRATEGY, Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313

	// Write header (8 bit colour depth). Full alpha channel with PNG_COLOR_TYPE_RGB_ALPHA
	if(indexed_png) {
		png_set_IHDR(png_ptr, info_ptr, width, height,
			channel_depth, PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
			PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
		//set transparent color (ie: cheap transparency: leads to smaller files and shorter run times)
		png_byte trans = 0; //by convention, the gradient define it as color 0
		png_set_tRNS(png_ptr, info_ptr, &trans, 1, 0);
	} else {
		png_set_IHDR(png_ptr, info_ptr, width, height,
			channel_depth, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
			PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
		//set transparent color (ie: cheap transparency: leads to smaller files and shorter run times)
		png_color_16 trans_rgb_value = {transparent_grey, transparent_grey, transparent_grey, transparent_grey, transparent_grey};
		png_set_tRNS(png_ptr, info_ptr, 0, 0, &trans_rgb_value);
	}

314
315
316
	//set background color to help applications show the picture when no background is present
	png_color_16 background = {channel_max_color, channel_max_color, channel_max_color, channel_max_color, channel_max_color};
	png_set_background(png_ptr, &background, PNG_BACKGROUND_GAMMA_SCREEN, true, 1.0);
317
318
319
320
}

unsigned int PNGIO::setLegend(const unsigned int &ncols, const unsigned int &nrows, const double &min, const double &max, Array2D<double> &legend_array)
{
321
322
323
324
325
	if(has_legend) {
		legend leg(nrows, min, max);
		legend_array = leg.getLegend();
		unsigned int nx, ny;
		legend_array.size(nx,ny);
326
327
328
		return (ncols+nx);
	} else {
		return ncols;
329
	}
330
331
}

332
void PNGIO::writeDataSection(const Grid2DObject &grid, const Array2D<double> &legend_array, const Gradient &gradient, const unsigned int &full_width, const png_structp &png_ptr)
333
{
334
335
	const double ncols = grid.ncols;
	const double nrows = grid.nrows;
336

337
	// Allocate memory for one row (3 bytes per pixel - RGB)
338
339
340
341
342
343
	unsigned char channels;
	if(indexed_png)
		channels = 1;
	else
		channels = 3;

344
345
346
347
	png_bytep row = (png_bytep)calloc(channels*sizeof(png_byte), full_width);
	if(row==NULL) {
		throw IOException("Can not allocate row memory in PNGIO!", AT);
	}
348
349

	// Write image data
350
351
352
353
354
355
356
357
358
359
360
361
362
363
	if(indexed_png) {
		for(int y=nrows-1 ; y>=0 ; y--) {
			unsigned int x=0;
			for(; x<ncols ; x++) {
				const unsigned int i=x*channels;
				unsigned int index;
				gradient.getColor(grid(x,y), index);
				row[i]=index;
			}
			for(; x<full_width; x++) {
				const unsigned int i=x*channels;
				unsigned int index;
				gradient.getColor(legend_array(x-ncols,y), index);
				row[i]=index;
364
			}
365
			png_write_row(png_ptr, row);
366
		}
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
	} else {
		for(int y=nrows-1 ; y>=0 ; y--) {
			unsigned int x=0;
			for(; x<ncols ; x++) {
				const unsigned int i=x*channels;
				unsigned char r,g,b;
				bool a;
				gradient.getColor(grid(x,y), r,g,b,a);
				if(a==true) {
					row[i]=transparent_grey; row[i+1]=transparent_grey; row[i+2]=transparent_grey;
				} else {
					row[i]=r; row[i+1]=g; row[i+2]=b;
				}
			}
			for(; x<full_width; x++) {
				const unsigned int i=x*channels;
				unsigned char r,g,b;
				bool a;
				gradient.getColor(legend_array(x-ncols,y), r,g,b,a);
				if(a==true) {
					row[i]=transparent_grey; row[i+1]=transparent_grey; row[i+2]=transparent_grey;
				} else {
					row[i]=r; row[i+1]=g; row[i+2]=b;
				}
391
			}
392
			png_write_row(png_ptr, row);
393
394
		}
	}
395

396
397
	png_write_flush(png_ptr);
	png_free(png_ptr, row);
398
399
}

400
void PNGIO::setPalette(const Gradient &gradient, png_structp& png_ptr, png_infop& info_ptr, png_color *palette)
401
402
403
404
{
	std::vector<unsigned char> r, g, b;
	gradient.getPalette(r,g,b);
	const size_t nr_colors = r.size();
405
	palette = (png_color*)calloc(sizeof (png_color), nr_colors);
406
407
408
409
410
411
412
413
	for(size_t ii=0; ii<nr_colors; ii++) {
		palette[ii].red = r[ii];
		palette[ii].green = g[ii];
		palette[ii].blue = b[ii];
	}
	png_set_PLTE(png_ptr, info_ptr, palette, nr_colors);
}

414
void PNGIO::closePNG(png_structp& png_ptr, png_infop& info_ptr, png_color *palette)
415
{
416
	png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
417
	if(indexed_png && palette!=NULL) free(palette);
418
	png_destroy_write_struct(&png_ptr, &info_ptr);
419
	fclose(fp);
420
421
	free(info_ptr);
	free(png_ptr);
422
423
}

424
void PNGIO::write2DGrid(const Grid2DObject& grid_in, const std::string& filename)
425
{
426
	string full_name = grid2dpath+"/"+filename;
427
	fp=NULL;
428
	png_color *palette=NULL;
429
430
431
432
433
434
435
436
437
438
	png_structp png_ptr=NULL;
	png_infop info_ptr=NULL;

	//scale input image
	const Grid2DObject grid = scaleGrid(grid_in);
	const double ncols = grid.ncols, nrows = grid.nrows;
	const double min = grid.grid2D.getMin();
	const double max = grid.grid2D.getMax();

	Gradient gradient(Gradient::heat, min, max, autoscale);
439
	gradient.setNrOfLevels(nr_levels);
440
441
442
443

	Array2D<double> legend_array; //it will remain empty if there is no legend
	const unsigned int full_width = setLegend(ncols, nrows, min, max, legend_array);

444
	setFile(full_name, png_ptr, info_ptr, full_width, nrows);
445
	if(indexed_png) setPalette(gradient, png_ptr, info_ptr, palette);
446
	if(has_world_file) writeWorldFile(grid, full_name);
447
448
449
450
451
452
453
454

	createMetadata(grid);
	metadata_key.push_back("Title"); //adding generic title
	metadata_text.push_back("Unknown Gridded data");
	writeMetadata(png_ptr, info_ptr);

	writeDataSection(grid, legend_array, gradient, full_width, png_ptr);
	png_write_end(png_ptr, NULL);
455

456
	closePNG(png_ptr, info_ptr, palette);
457
458
}

459
void PNGIO::write2DGrid(const Grid2DObject& grid_in, const MeteoGrids::Parameters& parameter, const Date& date)
460
{
461
462
	std::string filename;
	if(parameter==MeteoGrids::DEM || parameter==MeteoGrids::SLOPE || parameter==MeteoGrids::AZI)
463
		filename = grid2dpath + "/" + MeteoGrids::getParameterName(parameter) + ".png";
464
465
466
467
468
	else {
		std::string date_str = date.toString(Date::ISO);
		std::replace( date_str.begin(), date_str.end(), ':', '.');
		filename = grid2dpath + "/" + date_str + "_" + MeteoGrids::getParameterName(parameter) + ".png";
	}
469

470
	fp=NULL;
471
	png_color *palette=NULL;
472
473
474
475
476
477
478
479
480
481
482
	png_structp png_ptr=NULL;
	png_infop info_ptr=NULL;

	//scale input image
	Grid2DObject grid = scaleGrid(grid_in);
	const double ncols = grid.ncols, nrows = grid.nrows;
	double min = grid.grid2D.getMin();
	double max = grid.grid2D.getMax();

	Gradient gradient;
	if(parameter==MeteoGrids::DEM) {
483
484
		if(!autoscale) {
			min = 0.; //we want a 3000 snow line with a full scale legend
485
486
			max = 3500.;
			gradient.set(Gradient::terrain, min, max, autoscale); //max used as snow line reference
487
488
		} else
			gradient.set(Gradient::terrain, min, max, autoscale);
489
490
491
	} else if(parameter==MeteoGrids::SLOPE) {
		gradient.set(Gradient::slope, min, max, autoscale);
	} else if(parameter==MeteoGrids::AZI) {
492
493
494
495
		if(!autoscale) {
			min = 0.;
			max = 360.;
		}
496
497
		gradient.set(Gradient::azi, min, max, autoscale);
	} else if(parameter==MeteoGrids::HS) {
498
499
500
501
		if(!autoscale) {
			min = 0.; max = 3.5;
		}
		gradient.set(Gradient::blue, min, max, autoscale);
502
503
	} else if(parameter==MeteoGrids::TA) {
		grid.grid2D -= Cst::t_water_freezing_pt; //convert to celsius
504
505
506
507
508
509
		if(!autoscale) {
			min = -10.; max = 10.;
		} else {
			min -= Cst::t_water_freezing_pt;
			max -= Cst::t_water_freezing_pt;
		}
510
		gradient.set(Gradient::heat, min, max, autoscale);
511
512
513
514
515
516
517
518
519
	} else if(parameter==MeteoGrids::TSS) {
		grid.grid2D -= Cst::t_water_freezing_pt; //convert to celsius
		if(!autoscale) {
			min = -10.; max = 10.;
		} else {
			min -= Cst::t_water_freezing_pt;
			max -= Cst::t_water_freezing_pt;
		}
		gradient.set(Gradient::freeze, min, max, autoscale);
520
	} else if(parameter==MeteoGrids::RH) {
521
522
523
		if(!autoscale) {
			min = 0.; max = 1.;
		}
524
525
526
527
528
529
		gradient.set(Gradient::bg_isomorphic, min, max, autoscale);
	} else if(parameter==MeteoGrids::ALB) {
		if(!autoscale) {
			min = 0.; max = 1.;
		}
		gradient.set(Gradient::bg_isomorphic, min, max, autoscale);
530
531
532
533
534
535
536
537
538
539
	} else if(parameter==MeteoGrids::ISWR) {
		if(!autoscale) {
			min = 0.; max = 1000.;
		}
		gradient.set(Gradient::heat, min, max, autoscale);
	} else if(parameter==MeteoGrids::ILWR) {
		if(!autoscale) {
			min = 200.; max = 500.;
		}
		gradient.set(Gradient::heat, min, max, autoscale);
540
	} else if(parameter==MeteoGrids::SWE) {
541
542
543
544
		if(!autoscale) {
			min = 0.; max = 2000.;
		}
		gradient.set(Gradient::blue, min, max, autoscale);
545
546
547
	} else {
		gradient.set(Gradient::heat, min, max, autoscale);
	}
548
	gradient.setNrOfLevels(nr_levels);
549
550

	Array2D<double> legend_array; //it will remain empty if there is no legend
551
	const unsigned int full_width = setLegend(ncols, nrows, min, max, legend_array);
552

553
	setFile(filename, png_ptr, info_ptr, full_width, nrows);
554
	if(indexed_png) setPalette(gradient, png_ptr, info_ptr, palette);
555
	if(has_world_file) writeWorldFile(grid, filename);
556
557
558
559

	createMetadata(grid);
	metadata_key.push_back("Title"); //adding title
	metadata_text.push_back( MeteoGrids::getParameterName(parameter)+" on "+date.toString(Date::ISO) );
560
561
	metadata_key.push_back("Simulation Date");
	metadata_text.push_back( date.toString(Date::ISO) );
562
563
	metadata_key.push_back("Simulation Parameter");
	metadata_text.push_back( MeteoGrids::getParameterName(parameter) );
564
565
566
567
	writeMetadata(png_ptr, info_ptr);

	writeDataSection(grid, legend_array, gradient, full_width, png_ptr);
	png_write_end(png_ptr, NULL);
568

569
	closePNG(png_ptr, info_ptr, palette);
570
571
572
573
574
575
576
577
}

void PNGIO::writeWorldFile(const Grid2DObject& grid_in, const std::string& filename)
{
	const string world_file = IOUtils::removeExtension(filename)+".pnw";
	const double cellsize = grid_in.cellsize;
	Coords world_ref=grid_in.llcorner;
	world_ref.setProj(coordout, coordoutparam);
578
	world_ref.moveByXY(.5*cellsize, (grid_in.nrows+.5)*cellsize); //moving to center of upper left cell
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

	std::ofstream fout;
	fout.open(world_file.c_str());
	if (fout.fail()) {
		throw FileAccessException(world_file, AT);
	}

	try {
		fout << std::setprecision(12) << cellsize << "\n";
		fout << "0.000000000000\n";
		fout << "0.000000000000\n";
		fout << std::setprecision(12) << -cellsize << "\n";
		fout << std::setprecision(12) << world_ref.getEasting() << "\n";
		fout << std::setprecision(12) << world_ref.getNorthing() << "\n";
	} catch(...) {
		fout.close();
		throw FileAccessException("Failed when writing to PNG world file \""+world_file+"\"", AT);
	}

	fout.close();
599
600
}

601
void PNGIO::createMetadata(const Grid2DObject& grid)
602
{
603
604
605
606
	const double lat = grid.llcorner.getLat();
	const double lon = grid.llcorner.getLon();
	stringstream ss;

607
608
609
	metadata_key.clear();
	metadata_text.clear();

610
611
612
613
	metadata_key.push_back("Creation Time");
	Date cr_date;
	cr_date.setFromSys();
	metadata_text.push_back( cr_date.toString(Date::ISO) );
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
	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());
629

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
	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));
	}
}

void PNGIO::writeMetadata(png_structp &png_ptr, png_infop &info_ptr)
{
656
	const size_t max_len = 79; //according to the official specs' recommendation
657
658
659
660
	const size_t nr = metadata_key.size();
	png_text *info_text;
	info_text = (png_text *)calloc(sizeof(png_text), nr);
	char **key, **text;
661
662
	key = (char**)calloc(sizeof(char)*max_len, nr);
	text = (char**)calloc(sizeof(char)*max_len, nr);
663
664

	for(size_t ii=0; ii<nr; ii++) {
665
666
667
668
		key[ii] = (char *)calloc(sizeof(char), max_len);
		text[ii] = (char *)calloc(sizeof(char), max_len);
		strncpy(key[ii], metadata_key[ii].c_str(), max_len);
		strncpy(text[ii], metadata_text[ii].c_str(), max_len);
669
670
671
672
		info_text[ii].key = key[ii];
		info_text[ii].text = text[ii];
		info_text[ii].compression = PNG_TEXT_COMPRESSION_NONE;
	}
673

674
	png_set_text(png_ptr, info_ptr, info_text, nr);
675
676
	png_write_info(png_ptr, info_ptr);

677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
	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();
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
}

#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