Set the modification time of a PNG

This program demonstrates how to set the modification date of a PNG graphic, which is the tIME chunk. The PNG created is the same as in Create a PNG with text segments.

#include <png.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
    
/* Write "bitmap" to a PNG file specified by "path"; returns 0 on
   success, non-zero on error. */

void save_png_to_file (const char *path)
{
    FILE * fp;
    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;
    size_t x, y;
    png_byte ** row_pointers = NULL;
    int pixel_size = 1;
    int depth = 8;
    int height = 100;
    int width = 100;
    png_time mod_time;

    fp = fopen (path, "wb");
    png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    info_ptr = png_create_info_struct (png_ptr);


    mod_time.year = 2010;
    mod_time.month = 12;
    mod_time.day = 29;
    mod_time.hour = 16;
    mod_time.minute = 20;
    mod_time.second = 20;

    png_set_tIME (png_ptr, info_ptr, & mod_time);
    
    png_set_IHDR (png_ptr,
                  info_ptr,
                  width,
                  height,
                  depth,
                  PNG_COLOR_TYPE_GRAY,
                  PNG_INTERLACE_NONE,
                  PNG_COMPRESSION_TYPE_DEFAULT,
                  PNG_FILTER_TYPE_DEFAULT);
    
    /* Initialize rows of PNG. */

    row_pointers = png_malloc (png_ptr, height * sizeof (png_byte *));
    for (y = 0; y < height; y++) {
        png_byte *row = 
            png_malloc (png_ptr, sizeof (uint8_t) * width * pixel_size);
        row_pointers[y] = row;

        /* Fill the image with random data. */

        for (x = 0; x < width; x++) {
            *row++ = random () % 256;
        }
    }
    
    /* Write the image data to "fp". */

    png_init_io (png_ptr, fp);
    png_set_rows (png_ptr, info_ptr, row_pointers);
    png_write_png (png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);

    for (y = 0; y < height; y++) {
        png_free (png_ptr, row_pointers[y]);
    }
    png_free (png_ptr, row_pointers);
    
    png_destroy_write_struct (&png_ptr, &info_ptr);
    fclose (fp);
}

int main ()
{
    save_png_to_file ("time.png");
    return 0;
}

Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer