Blob Blame Raw

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


int main() {
  int sizeX = 28;
  int sizeY = 28;
  int border = 2;
  int outSizeX = 22;
  int outSizeY = 22;
  const char *filename = "data/symbols-data.bin";
  const char *outFilename = "data/output/symbols22-data.bin";


  printf("read data from '%s'\n", filename);
  FILE *f = fopen(filename, "rb");
  if (!f)
    return printf("cannot open file\n"), 1;
  fseek(f, 0, SEEK_END);
  size_t fs = ftell(f);
  fseek(f, 0, SEEK_SET);

  size_t testSize = sizeX*sizeY + 1;
  int count = fs/testSize;
  if (!count)
    return printf("file is lesser minimal size\n"), fclose(f), 1;

  unsigned char *data = calloc(testSize, count);
  if (!fread(data, testSize*count, 1, f))
    return printf("cannot read"), free(data), fclose(f), 1;
  fclose(f);

  printf("write converted data to '%s'\n", outFilename);
  f = fopen(outFilename, "wb");
  if (!f)
    return printf("cannot open file\n"), 1;

  unsigned char *img = calloc(outSizeX*outSizeY+1, 1);
  int sx = sizeX - 2*border - 1, sy = sizeY - 2*border - 1;
  int osx = outSizeX - 2*border - 1, osy = outSizeY - 2*border - 1;
  for(int i = 0; i < count; ++i) {
    unsigned char *in = data + testSize*i;
    for(int y = 0; y <= osy; ++y) {
      int y0 = y*sy;
      int py = y0%osy;
      y0 /= osy;
      int y1 = y0 < sy ? y0 : sy;
      for(int x = 0; x <= osx; ++x) {
        int x0 = x*sx;
        int px = x0%osx;
        x0 /= osx;
        int x1 = x0 < sx ? x0 : sx-1;

        int p00 = in[(border+y0)*sizeX + x0];
        int p01 = in[(border+y0)*sizeX + x1];
        int p0 = p00*(osx-px) + p01*px;

        int p10 = in[(border+y1)*sizeX + x0];
        int p11 = in[(border+y1)*sizeX + x1];
        int p1 = p10*(osx-px) + p11*px;

        int p = p0*(osy-py) + p1*py;
        p = (p + osx*osy/2)/(osx*osy);

        img[(y+border)*outSizeX + x] = (unsigned int)p1;
      }
    }
    img[outSizeX*outSizeY] = in[sizeX*sizeY];
    if (!fwrite(img, outSizeX*outSizeY+1, 1, f))
      return printf("cannot write\n"), free(data), free(img), fclose(f), 1;
  }
  free(data);
  free(img);

  fclose(f);

  return printf("done\n");
  return 0;
}