Search code examples
compressionpnglibpng

Writing a 1 bit depth grayscale PNG with libpng results in incorrect image


So I am trying to use libpng to write png's from an array of unsigned char that are a bit depth of 1. Meaning for all bits, there is only black and white, as a gray scale image. I have managed to do this successfully for 8-bit depth gray scale png, but not 1 bit depth. Here is the code i have :

extern int write_png_bwsq(const char* filename,
                    int dimen,
                    const unsigned char *buffer,
                    char* title)
{
        
    int yrow;
        int dim_bytes;
    int code = 1;
    FILE *fp = NULL;
    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;
    png_bytep row = NULL;
        dim_bytes = (dimen * dimen) / 8;

    
    // Open file for writing (binary mode)
    fp = fopen(filename, "wb");
    if (fp == NULL) {
        fprintf(stderr, "PNG ERROR: Could not open file %s for writing\n", filename);
        code = 0;
        goto finalise;
    }

    // Initialize write structure
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (png_ptr == NULL) {
        fprintf(stderr, "PNG ERROR: Could not allocate PNG write struct\n");
        code = 0;
        goto finalise;
    }

    // Initialize info structure
    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL) {
        fprintf(stderr, "PNG ERROR: Could not allocate PNG info struct\n");
        code = 0;
        goto finalise;
    }

    // Setup Exception handling
    if (setjmp(png_jmpbuf(png_ptr))) {
        fprintf(stderr, "PNG Error: Creating the PNG output failed.\n");
        code = 0;
        goto finalise;
    }

    png_init_io(png_ptr, fp);

    png_set_IHDR(png_ptr, info_ptr, dimen, dimen,
            1, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE,
            PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

    // Sets the title
    if (title != NULL) {
        png_text title_text;
        title_text.compression = PNG_TEXT_COMPRESSION_NONE;
        title_text.key = "Title";
        title_text.text = title;
        png_set_text(png_ptr, info_ptr, &title_text, 1);
    }

    png_write_info(png_ptr, info_ptr);

    row = (png_bytep) buffer;

    // Write image data
    for (yrow=0 ; yrow<dim_bytes ; yrow++) {
        png_write_row(png_ptr, row);
        ++row;
    }

    // End write operation
    png_write_end(png_ptr, NULL);

    finalise:
    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);

    return code;
}

Then, i have a separate file where i prepare my image

#include "write_pngs.h"
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#if CHAR_BIT != 8
#  error "CHAR_BIT is not usable on this platform"
#endif

#define PIC_SIZE_DIM 1080
#define PIC_SIZE_BW ((PIC_SIZE_DIM * PIC_SIZE_DIM) / CHAR_BIT) 
static unsigned char PIC_BITS[PIC_SIZE_BW] = {0};

static void __write_bits_pic(void)
{
     size_t i = 1000;
     for(;i < 140000;++i) {
        PIC_BITS[i] = ((i + 76) >> 5) & 0xff;
     }
}


int main(void) {
   __write_bits_pic();
   printf("Writing picture of %d bytes and %d bits\n", PIC_SIZE_BW, PIC_SIZE_BW * CHAR_BIT);
   return !write_png_bwsq("bwpixs.png",
                    PIC_SIZE_DIM,
                    PIC_BITS,
                    "bwpixs");
}

This results in an incorrect image where its not only quite large for a png (about 5mb for only 1080 x 1080), but only the bottom right corner of the image is changed from black.

What am i doing wrong here ? Does libpng require any special steps for writing pngs that are only 1 in bit depth for gray scale i am not doing ?


Solution

  • You are calling png_write_row() way too many times. Your

    for (yrow=0 ; yrow<dim_bytes ; yrow++) {
        png_write_row(png_ptr, row);
        ++row;
    }
    

    should be something like:

    for (yrow=0 ; yrow<dim_bytes ; yrow += dimen / 8) {
        png_write_row(png_ptr, row);
        row += dimen / 8;
    }
    

    in order to write a row of 1080 pixels (135 bytes). You were calling png_write_row() for every byte, as if the image is eight pixels wide. Which it isn't.