summaryrefslogtreecommitdiff
path: root/examples/jpeg/test_rgb.c
blob: 39f2fd0126a367c8c594e057dc7c0f658389ec24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <glib.h>

#include "jpeg_rgb_decoder.h"

/* getfile */

void *getfile (char *path, int *n_bytes);
static void dump_pnm (unsigned char *ptr, int rowstride, int width, int height);

int
main (int argc, char *argv[])
{
  unsigned char *data;
  int len;
  JpegRGBDecoder *dec;
  char *fn;
  unsigned char *ptr;
  int rowstride;
  int width;
  int height;

  dec = jpeg_rgb_decoder_new ();

  if (argc < 2) {
    g_print("jpeg_rgb_test <file.jpg>\n");
    exit(1);
  }
  fn = argv[1];
  data = getfile (fn, &len);

  if (data == NULL) {
    g_print("cannot read file %s\n", fn);
    exit(1);
  }

  jpeg_rgb_decoder_addbits (dec, data, len);
  jpeg_rgb_decoder_parse (dec);

  jpeg_rgb_decoder_get_image (dec, &ptr, &rowstride, &width, &height);

  dump_pnm (ptr, rowstride, width, height);

  g_free (ptr);

  jpeg_rgb_decoder_free (dec);
  g_free (data);

  return 0;
}



/* getfile */

void *
getfile (char *path, int *n_bytes)
{
  int fd;
  struct stat st;
  void *ptr = NULL;
  int ret;

  fd = open (path, O_RDONLY);
  if (!fd)
    return NULL;

  ret = fstat (fd, &st);
  if (ret < 0) {
    close (fd);
    return NULL;
  }

  ptr = g_malloc (st.st_size);
  if (!ptr) {
    close (fd);
    return NULL;
  }

  ret = read (fd, ptr, st.st_size);
  if (ret != st.st_size) {
    g_free (ptr);
    close (fd);
    return NULL;
  }

  if (n_bytes)
    *n_bytes = st.st_size;

  close (fd);
  return ptr;
}

static void
dump_pnm (unsigned char *ptr, int rowstride, int width, int height)
{
  int x, y;

  printf ("P3\n");
  printf ("%d %d\n", width, height);
  printf ("255\n");

  for (y = 0; y < height; y++) {
    for (x = 0; x < width; x++) {
      printf ("%d ", ptr[x * 4 + 2]);
      printf ("%d ", ptr[x * 4 + 1]);
      printf ("%d ", ptr[x * 4 + 0]);
      if ((x & 15) == 15) {
        printf ("\n");
      }
    }
    printf ("\n");
    ptr += rowstride;
  }
}