- int pos = findjpegboundary(&tag->data[6], tag->len-6);
- if(pos<0) {
- fi = save_fopen(filename, "wb");
- fwrite(&tag->data[6], end-6, 1, fi);
- fclose(fi);
- } else {
- pos+=6;
- fi = save_fopen(filename, "wb");
- fwrite(&tag->data[6], pos-6, 1, fi);
- fwrite(&tag->data[pos+4], end-(pos+4), 1, fi);
- fclose(fi);
- }
+ int pos = findjpegboundary(&tag->data[6], end);
+ if(end >= tag->len) {
+ msg("<error> zlib data out of bounds in definebitsjpeg3");
+ return 0;
+ }
+ if(pos) {
+ /* TODO: do we actually need this? */
+ memmove(&tag->data[pos], &tag->data[pos+4], end-(pos+4));
+ }
+ unsigned char*image;
+ unsigned width=0, height=0;
+ jpeg_load_from_mem(&tag->data[6], end-6, &image, &width, &height);
+
+ uLongf datalen = width*height;
+ Bytef *data = malloc(datalen);
+
+ int error = uncompress(data, &datalen, &tag->data[end], (uLong)(tag->len - end));
+ if(error != Z_OK) {
+ fprintf(stderr, "Zlib error %d\n", error);
+ return 0;
+ }
+ int t, size = width*height;
+ for(t=0;t<size;t++) {
+ image[t*4+0] = data[t];
+ }
+ free(data);
+ png_write(filename, image, width, height);
+ free(image);