+opj_cio_t* OPJ_CALLCONV opj_cio_open(opj_common_ptr cinfo, unsigned char *buffer, int length) {
+ opj_cp_t *cp = NULL;
+ opj_cio_t *cio = (opj_cio_t*)opj_malloc(sizeof(opj_cio_t));
+ if(!cio) return NULL;
+ cio->cinfo = cinfo;
+ if(buffer && length) {
+ /* wrap a user buffer containing the encoded image */
+ cio->openmode = OPJ_STREAM_READ;
+ cio->buffer = buffer;
+ cio->length = length;
+ }
+ else if(!buffer && !length && cinfo) {
+ /* allocate a buffer for the encoded image */
+ cio->openmode = OPJ_STREAM_WRITE;
+ switch(cinfo->codec_format) {
+ case CODEC_J2K:
+ cp = ((opj_j2k_t*)cinfo->j2k_handle)->cp;
+ break;
+ case CODEC_JP2:
+ cp = ((opj_jp2_t*)cinfo->jp2_handle)->j2k->cp;
+ break;
+ default:
+ opj_free(cio);
+ return NULL;
+ }
+ cio->length = cp->tdx * cp->tdy * cp->tw * cp->th * 4;
+ cio->buffer = (unsigned char *)opj_malloc(cio->length);
+ if(!cio->buffer) {
+ opj_free(cio);
+ return NULL;
+ }
+ }
+ else {
+ opj_free(cio);
+ return NULL;
+ }