shithub: jp2

ref: 0d62e74e14ccf4e123d5c2d7af76cb02e695c0ee
dir: /jp2.c/

View raw version
#include <jasper/jasper.h>
#include <draw.h>
#include <memdraw.h>

static void
usage(void)
{
	fprint(2, "usage: %s < FILE.jp2 > FILE.pic\n", argv0);
	exits("usage");
}

void
main(int argc, char **argv)
{
	jas_stream_t *s;
	jas_image_t *im;
	jas_cmprof_t *cp;
	int c, i, w, h, x, y;
	jas_image_cmpttype_t comps[] = {
		JAS_IMAGE_CT_RGB_R,
		JAS_IMAGE_CT_RGB_G,
		JAS_IMAGE_CT_RGB_B,
	};
	u8int *rgb;
	long *b;
	Memimage *m;

	ARGBEGIN{
	default:
		usage();
	}ARGEND

	if(argc != 0)
		usage();

	memimageinit();
	jas_init();

	if((cp = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)) == nil){
		werrstr("failed to create color space");
		goto error;
	}
	if((s = jas_stream_fdopen(0, "rb")) == nil){
		werrstr("failed to open");
		goto error;
	}
	if((im = jas_image_decode(s, -1, "")) == nil){
		werrstr("failed to decode: %r");
		goto error;
	}
	jas_stream_close(s);
	if((im = jas_image_chclrspc(im, cp, JAS_CMXFORM_INTENT_PER)) == nil){
		werrstr("failed to change color space");
		goto error;
	}
	w = jas_image_width(im);
	h = jas_image_height(im);
	if((b = malloc(w*h*sizeof(*b))) == nil){
		werrstr("memory");
		goto error;
	}
	if((rgb = malloc(w*h*3)) == nil){
		werrstr("memory");
		goto error;
	}

	for(i = 0; i < 3; i++){
		if((c = jas_image_getcmptbytype(im, comps[i])) < 0){
			werrstr("failed to get component R");
			goto error;
		}
		if(jas_image_readcmpt2(im, c, 0, 0, w, h, b) < 0){
			werrstr("read component failed");
			goto error;
		}
		for(y = 0; y < h; y++){
			for(x = 0; x < w; x++){
				rgb[3*(y*w + x) + 2-i] = b[y*w + x];
			}
		}
	}
	jas_image_destroy(im);
	free(b);

	if((m = allocmemimage(Rect(0,0,w,h), RGB24)) == nil){
		werrstr("memory");
		goto error;
	}
	loadmemimage(m, m->r, rgb, w*h*3);
	writememimage(1, m);
	freememimage(m);

	exits(nil);
error:
	fprint(2, "%r\n");
	exits("error");
}