X
X
x2bool2012-09-26 09:56:37
Programming
x2bool, 2012-09-26 09:56:37

How to extract comment from PNG metadata?

If, after adding a comment with GIMP to a png file, if you open this file with a text editor, you can see the following line in the text " tEXtComment\00%Comment%", where %Comment% is my comment.
How to programmatically extract text from PNG without using third-party libraries relying on it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2012-09-26
@x2bool

something like this:

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
  if ( argc < 2 ) {
    return 0;
  }
  FILE *f = fopen( argv[1],"rb");
  char buffer[100];
  unsigned char lengthBuf[4];
  char type[5];
  fread(buffer, 1, 8, f);

  if ( strncmp("\x89PNG\r\n\x1a\n", buffer, 8 ) ) {
    printf("Not a PNG file!\r\n");
    fclose(f);
    return 0;
  };
  while(!feof(f)) {
    int len = 0;
    fread(lengthBuf, 1, 4, f);
    
    len=(lengthBuf[0]<<24)|(lengthBuf[1]<<16) | (lengthBuf[2]<<8) |lengthBuf[3];
    fread(type, 4,1, f);
    type[4] = 0;

    if (strcmp(type, "iTXt") == 0 ) {
      char *data = new char[len];
      fread(data, len, 1 , f);
      data[len] = 0;

      char keyword[100];
      char* comment = new char[len];
      strcpy(keyword, data);
      int keywordLen = strlen(keyword);
      int i = 0;
      while( data[keywordLen + i++ ] == 0);

      strcpy(keyword, data);
      strcpy(comment, &data[keywordLen+i-1]);
      printf("Keyword='%s', text='%s'\r\n", keyword, comment);
    
      delete comment;
      delete data;
      break;
    }
    if (strcmp(type, "IEND") == 0 ) {
      break;
    }
    fseek(f, len+4, SEEK_CUR);

  }
  fclose(f);
  return 0;
}

A
avalak, 2012-09-26
@avalak

Если совсем без библиотек, то RFC 2083 PNG (Portable Network Graphics) / Спека + раз язык роли не играет, то python и стандартный модуль struct.
Либо на bash будет примерно так, но тут уж на любителя.

#!/usr/bin/env bash

identify -verbose image.png | grep "Comment"
#    Comment: Created with GIMP

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question