static void unloadimage() { if (gs.image) { jas_image_destroy(gs.image); gs.image = 0; } if (gs.altimage) { jas_image_destroy(gs.altimage); gs.altimage = 0; } }
void imFileFormatJP2::Close() { if (this->image) jas_image_destroy(this->image); jas_stream_close(this->stream); }
static void jp2_dec_destroy(jp2_dec_t *dec) { if (dec->ihdr) { jp2_box_destroy(dec->ihdr); } if (dec->bpcc) { jp2_box_destroy(dec->bpcc); } if (dec->cdef) { jp2_box_destroy(dec->cdef); } if (dec->pclr) { jp2_box_destroy(dec->pclr); } #ifdef ENABLE_JASPER_IMAGE if (dec->image) { jas_image_destroy(dec->image); } #endif /* ENABLE_JASPER_IMAGE */ if (dec->cmap) { jp2_box_destroy(dec->cmap); } if (dec->colr) { jp2_box_destroy(dec->colr); } if (dec->chantocmptlut) { jas_free(dec->chantocmptlut); } jas_free(dec); }
void fz_dropjpxd(fz_filter *filter) { fz_jpxd *d = (fz_jpxd*)filter; if (d->stream) jas_stream_close(d->stream); if (d->image) jas_image_destroy(d->image); }
static void jp2_dec_destroy(jp2_dec_t *dec) { if (dec->ihdr) { jp2_box_destroy(dec->ihdr); } if (dec->bpcc) { jp2_box_destroy(dec->bpcc); } if (dec->cdef) { jp2_box_destroy(dec->cdef); } if (dec->pclr) { jp2_box_destroy(dec->pclr); } if (dec->image) { jas_image_destroy(dec->image); } if (dec->cmap) { jp2_box_destroy(dec->cmap); } if (dec->colr) { jp2_box_destroy(dec->colr); } if (dec->chantocmptlut) { jas_free(dec->chantocmptlut); } jas_free(dec); }
int jpeg2k_decode_mem(IMG_DAT **oimg_dat, int *lossyflag, unsigned char *idata, const int ilen) { IMG_DAT *img_dat; jas_image_t *image; jas_stream_t *in; if (jas_init() != 0){ fprintf(stderr, "ERROR : jpeg2k_decode_mem: init : jas\n"); return(-1); } /* The input image is to be read from buffer stream. */ if ((in = jas_stream_memopen((char *)idata, ilen)) == NULL){ fprintf(stderr, "ERROR : jpeg2k_decode_mem: failed to open jas stream\n"); return(-2); } /* Get the input image data. */ if ((image = jas_image_decode(in, -1, (char *)NULL)) == NULL){ fprintf(stderr, "error: cannot load image data\n"); return(-3); } /* Early cleanup--input stream no longer needed. */ (void) jas_stream_close(in); /* Gerenate Image data sturcture. */ if ((img_dat_generate(&img_dat, image)) != 0){ jas_image_destroy(image); fprintf(stderr, "ERROR : jpeg2k_decode_mem: failed to generate img_dat\n"); return(-5); } /* General clean up. */ jas_image_destroy(image); *oimg_dat = img_dat; *lossyflag = 0; return(0); }
jas_image_t *pnm_decode(jas_stream_t *in, char *opts) { pnm_hdr_t hdr; jas_image_t *image; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; int i; if (opts) { jas_eprintf("warning: ignoring options\n"); } /* Read the file header. */ if (pnm_gethdr(in, &hdr)) { return 0; } /* Create an image of the correct size. */ for (i = 0, cmptparm = cmptparms; i < hdr.numcmpts; ++i, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = hdr.width; cmptparm->height = hdr.height; cmptparm->prec = pnm_maxvaltodepth(hdr.maxval); cmptparm->sgnd = hdr.sgnd; } if (!(image = jas_image_create(hdr.numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { return 0; } if (hdr.numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read image data from stream into image. */ if (pnm_getdata(in, &hdr, image)) { jas_image_destroy(image); return 0; } return image; }
bool jasperConvert(jas_image_t* &image, jas_stream_t* &out, const char* data, unsigned size, int outfmt, const char* outopts) { jas_stream_t *in; // kDebug(YAHOO_RAW_DEBUG) << "Got data - size=" << size; if(!(in = jas_stream_memopen(const_cast<char*>(data), size))) { kDebug(YAHOO_RAW_DEBUG) << "Could not open jasper input stream"; return false; } int infmt; infmt = jas_image_getfmt(in); if (infmt < 0) { jas_stream_close(in); kDebug(YAHOO_RAW_DEBUG) << "Failed to recognize input webcam image format"; return false; } if (!(image = jas_image_decode(in, infmt, 0))) { kDebug(YAHOO_RAW_DEBUG) << "Unable to decode image"; jas_stream_close(in); return false; } /* kDebug(YAHOO_RAW_DEBUG) << "jasper: decoded image: " << jas_image_width(image) << "x" << jas_image_height(image) << " bytes: " << jas_image_rawsize(image) << " components:" << jas_image_numcmpts(image); */ char* out_img = NULL; if(!(out = jas_stream_memopen(out_img, 0))) { kDebug(YAHOO_RAW_DEBUG) << "Could not open output stream"; jas_stream_close(in); return false; } if (jas_image_encode(image, out, outfmt, const_cast<char*>(outopts))) { kDebug(YAHOO_RAW_DEBUG) << "Unable to convert image"; jas_stream_close(in); jas_stream_close(out); jas_image_destroy(image); return false; } jas_stream_flush(out); jas_stream_close(in); return true; }
static void IDirectFBImageProvider_JPEG2000_Destruct( IDirectFBImageProvider *thiz ) { IDirectFBImageProvider_JPEG2000_data *data = thiz->priv; if (data->buf) D_FREE( data->buf ); if (data->image) jas_image_destroy( data->image ); release_jasper(); }
static void gst_jasper_enc_reset (GstJasperEnc * enc) { if (enc->buf) g_free (enc->buf); enc->buf = NULL; if (enc->image) jas_image_destroy (enc->image); enc->image = NULL; enc->fmt = -1; enc->mode = GST_JP2ENC_MODE_J2C; enc->clrspc = JAS_CLRSPC_UNKNOWN; enc->format = GST_VIDEO_FORMAT_UNKNOWN; }
void GrFmtJpeg2000Reader::Close() { if( m_stream ) { jas_stream_close( m_stream ); m_stream = 0; } if( m_image ) { jas_image_destroy( m_image ); m_image = 0; } GrFmtReader::Close(); }
static jas_image_t *jpg_mkimage(j_decompress_ptr cinfo) { jas_image_t *image; int cmptno; jas_image_cmptparm_t cmptparm; int numcmpts; image = 0; numcmpts = cinfo->output_components; if (!(image = jas_image_create0())) { goto error; } for (cmptno = 0; cmptno < numcmpts; ++cmptno) { cmptparm.tlx = 0; cmptparm.tly = 0; cmptparm.hstep = 1; cmptparm.vstep = 1; cmptparm.width = cinfo->image_width; cmptparm.height = cinfo->image_height; cmptparm.prec = 8; cmptparm.sgnd = false; if (jas_image_addcmpt(image, cmptno, &cmptparm)) { goto error; } } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } return image; error: if (image) { jas_image_destroy(image); } return 0; }
static gboolean gst_jasper_enc_init_encoder (GstJasperEnc * enc) { jas_image_cmptparm_t param[GST_JASPER_ENC_MAX_COMPONENT]; gint i; switch (enc->mode) { case GST_JP2ENC_MODE_J2C: case GST_JP2ENC_MODE_JPC: enc->fmt = jas_image_strtofmt ((char *) "jpc"); break; case GST_JP2ENC_MODE_JP2: enc->fmt = jas_image_strtofmt ((char *) "jp2"); break; } if (gst_video_format_is_rgb (enc->format)) enc->clrspc = JAS_CLRSPC_SRGB; else enc->clrspc = JAS_CLRSPC_SYCBCR; if (enc->buf) { g_free (enc->buf); enc->buf = NULL; } enc->buf = g_new0 (glong, enc->width); if (enc->image) { jas_image_destroy (enc->image); enc->image = NULL; } for (i = 0; i < enc->channels; ++i) { param[i].tlx = 0; param[i].tly = 0; param[i].prec = 8; param[i].sgnd = 0; param[i].height = enc->cheight[i]; param[i].width = enc->cwidth[i]; param[i].hstep = enc->height / param[i].height; param[i].vstep = enc->width / param[i].width; } if (!(enc->image = jas_image_create (enc->channels, param, enc->clrspc))) return FALSE; return TRUE; }
int main(int argc, char **argv) { struct cmdlineInfo cmdline; struct pam outpam; int * jasperCmpt; /* malloc'ed */ /* jaspercmpt[P] is the component number for use with the Jasper library that corresponds to Plane P of the PAM. */ jas_image_t * jasperP; pnm_init(&argc, argv); parseCommandLine(argc, argv, &cmdline); { int rc; rc = jas_init(); if ( rc != 0 ) pm_error("Failed to initialize Jasper library. " "jas_init() returns rc %d", rc ); } jas_setdbglevel(cmdline.debuglevel); readJpc(cmdline.inputFilename, &jasperP); outpam.file = stdout; outpam.size = sizeof(outpam); outpam.len = PAM_STRUCT_SIZE(tuple_type); computeOutputParm(jasperP, &outpam, &jasperCmpt); pnm_writepaminit(&outpam); convertToPamPnm(&outpam, jasperP, jasperCmpt); free(jasperCmpt); jas_image_destroy(jasperP); pm_close(stdout); return 0; }
JPEG2000Dataset::~JPEG2000Dataset() { FlushCache(); if ( psStream ) jas_stream_close( psStream ); if ( psImage ) jas_image_destroy( psImage ); if ( pszProjection ) CPLFree( pszProjection ); if( nGCPCount > 0 ) { GDALDeinitGCPs( nGCPCount, pasGCPList ); CPLFree( pasGCPList ); } }
bool WebcamImgFormat::forYahoo(QByteArray& result, const QImage* src) { if (!initOk) return false; QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); if (!src) return false; if (!src->save(&buffer, forYahooFmtQt, 100)) { kDebug(YAHOO_RAW_DEBUG) << "Failed to write intermediary " << forYahooFmtQt << " image"; return false; } jas_image_t* image = NULL; jas_stream_t* out = NULL; /* Note: need to pass the floating number in the current locale so that it can be parsed back. And since somehow I got my dev env with a non-english locale, it took some time to figure that this was the problem :-( */ /* The 'rate' parameter: tested and worked also with rate = 0.0265. In the future - make that a property of this object and change it from some GUI. */ bool r = jasperConvert(image, out, ba.constData(), ba.size(), jpcFmtID, QString("cblkwidth=64 cblkheight=64 numrlvls=4 rate=%L1 prcheight=128 prcwidth=2048 mode=real").arg(0.0165).toAscii().constData()); if (!r) return false; unsigned size = ((jas_stream_memobj_t *)out->obj_)->bufsize_; const char *buf = (const char*)(((jas_stream_memobj_t *)out->obj_)->buf_); result = QByteArray(buf, size); if (out) jas_stream_close(out); if (image) jas_image_destroy(image); return r; }
int main(int argc, char **argv) { int fmtid = 0; jas_image_fmtops_t fmtops; fmtops.decode = jp2_decode; fmtops.encode = NULL; fmtops.validate = jp2_validate; jas_image_addfmt(fmtid, "jp2", "jp2", "JPEG-2000 JP2 File Format Syntax (ISO/IEC 15444-1)", &fmtops); ++fmtid; fmtops.decode = NULL; fmtops.encode = bmp_encode; fmtops.validate = NULL; jas_image_addfmt(fmtid, "bmp", "bmp", "Microsoft Bitmap (BMP)", &fmtops); ++fmtid; jas_stream_t *in = jas_stream_fdopen(STDIN_FILENO, "rb"); assert(in != NULL); jas_stream_t *out = jas_stream_fdopen(STDOUT_FILENO, "w+b"); assert(out != NULL); jas_image_t *image = jas_image_decode(in, 0, NULL); assert(image != NULL); int rc = jas_image_encode(image, out, 1, NULL); assert(rc == 0); jas_stream_flush(out); jas_stream_close(in); jas_stream_close(out); jas_image_destroy(image); return 0; }
bool WebcamImgFormat::fromYahoo(QPixmap& pixmap, const char* data, unsigned size) { if (!initOk) return false; jas_image_t* image = NULL; jas_stream_t* out = NULL; bool r = jasperConvert(image, out, data, size, fromYahooFmtID, 0); if (!r) return false; size = ((jas_stream_memobj_t *)out->obj_)->bufsize_; const unsigned char *buf = static_cast<const unsigned char*>(((jas_stream_memobj_t *)out->obj_)->buf_); r = pixmap.loadFromData(buf, size); if (out) jas_stream_close(out); if (image) jas_image_destroy(image); return r; }
int main(int argc, char **argv) { struct cmdlineInfo cmdline; FILE *ifP; struct pam inpam; jas_image_t * jasperP; pnm_init(&argc, argv); parseCommandLine(argc, argv, &cmdline); { int rc; rc = jas_init(); if ( rc != 0 ) pm_error("Failed to initialize Jasper library. " "jas_init() returns rc %d", rc ); } jas_setdbglevel(cmdline.debuglevel); ifP = pm_openr(cmdline.inputFilename); pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type)); convertToJasperImage(&inpam, &jasperP); writeJpc(jasperP, cmdline, stdout); jas_image_destroy(jasperP); pm_close(ifP); pm_close(stdout); return 0; }
void JPCInstance::Close() { if ( m_jp2Stream != nullptr ) jas_stream_close( m_jp2Stream ), m_jp2Stream = nullptr; if ( m_jp2Image != nullptr ) { jas_image_setcmprof( m_jp2Image, nullptr ); // don't destroy embedded profile now jas_image_destroy( m_jp2Image ), m_jp2Image = nullptr; } if ( m_jp2CMProfile != nullptr ) jas_cmprof_destroy( m_jp2CMProfile ), m_jp2CMProfile = nullptr; CleanupJasPer(); m_path.Clear(); m_options.Reset(); m_jp2Options = JPCFormat::DefaultOptions(); m_queriedOptions = false; }
// Internal function used to load the Jpeg2000 stream. ILboolean iLoadJp2Internal(jas_stream_t *Stream, ILimage *Image) { jas_image_t *Jp2Image = NULL; jas_matrix_t *origdata; ILuint x, y, c; ILimage *TempImage; // Decode image Jp2Image = jas_image_decode(Stream, -1, 0); if (!Jp2Image) { ilSetError(IL_ILLEGAL_FILE_VALUE); jas_stream_close(Stream); return IL_FALSE; } // We're not supporting anything other than 8 bits/component yet. if (jas_image_cmptprec(Jp2Image, 0) != 8) { jas_image_destroy(Jp2Image); ilSetError(IL_ILLEGAL_FILE_VALUE); return IL_FALSE; } switch (jas_image_numcmpts(Jp2Image)) { case 3: if (Image == NULL) { ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL); TempImage = iCurImage; } else { ifree(Image->Data); // @TODO: Not really the most efficient way to do this... ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL); TempImage = Image; } break; case 4: if (Image == NULL) { ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL); TempImage = iCurImage; } else { ifree(Image->Data); // @TODO: Not really the most efficient way to do this... ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL); TempImage = Image; } break; default: jas_image_destroy(Jp2Image); ilSetError(IL_ILLEGAL_FILE_VALUE); return IL_FALSE; } TempImage->Origin = IL_ORIGIN_UPPER_LEFT; // JasPer stores the data channels separately. // I am assuming RGBA format. Is it possible for other formats to be included? for (c = 0; c < TempImage->Bpp; c++) { origdata = jas_matrix_create(TempImage->Height, TempImage->Width); if (!origdata) { ilSetError(IL_LIB_JP2_ERROR); return IL_FALSE; // @TODO: Error } // Have to convert data into an intermediate matrix format. if (jas_image_readcmpt(Jp2Image, c, 0, 0, TempImage->Width, TempImage->Height, origdata)) { return IL_FALSE; } for (y = 0; y < TempImage->Height; y++) { for (x = 0; x < TempImage->Width; x++) { TempImage->Data[y * TempImage->Width * TempImage->Bpp + x * TempImage->Bpp + c] = origdata->data_[y * origdata->numcols_ + x]; } } jas_matrix_destroy(origdata); } jas_image_destroy(Jp2Image); ilFixImage(); return IL_TRUE; }
int main(int argc, char **argv) { jas_image_t *image; cmdopts_t *cmdopts; jas_stream_t *in; jas_stream_t *out; clock_t startclk; clock_t endclk; long dectime; long enctime; int_fast16_t numcmpts; int i; /* Determine the base name of this command. */ if ((cmdname = strrchr(argv[0], '/'))) { ++cmdname; } else { cmdname = argv[0]; } if (jas_init()) { errprint(0, "error: cannot initialize jasper library\n"); abort(); } /* set our error callback */ jas_set_error_cb(errprint); /* Parse the command line options. */ if (!(cmdopts = cmdopts_parse(argc, argv))) { jas_eprintf("error: cannot parse command line\n"); exit(EXIT_FAILURE); } if (cmdopts->version) { jas_eprintf("%s\n", JAS_VERSION); jas_eprintf("libjasper %s\n", jas_getversion()); exit(EXIT_SUCCESS); } jas_setdbglevel(cmdopts->debug); if (cmdopts->verbose) { cmdinfo(); } /* Open the input image file. */ if (cmdopts->infile) { /* The input image is to be read from a file. */ if (!(in = jas_stream_fopen(cmdopts->infile, "rb"))) { jas_eprintf("error: cannot open input image file %s\n", cmdopts->infile); exit(EXIT_FAILURE); } } else { /* The input image is to be read from standard input. */ if (!(in = jas_stream_fdopen(0, "rb"))) { jas_eprintf("error: cannot open standard input\n"); exit(EXIT_FAILURE); } } /* Open the output image file. */ if (cmdopts->outfile) { /* The output image is to be written to a file. */ if (!(out = jas_stream_fopen(cmdopts->outfile, "w+b"))) { jas_eprintf("error: cannot open output image file %s\n", cmdopts->outfile); exit(EXIT_FAILURE); } } else { /* The output image is to be written to standard output. */ if (!(out = jas_stream_fdopen(1, "w+b"))) { jas_eprintf("error: cannot open standard output\n"); exit(EXIT_FAILURE); } } if (cmdopts->infmt < 0) { if ((cmdopts->infmt = jas_image_getfmt(in)) < 0) { jas_eprintf("error: input image has unknown format\n"); exit(EXIT_FAILURE); } } /* Get the input image data. */ startclk = clock(); if (!(image = jas_image_decode(in, cmdopts->infmt, cmdopts->inopts))) { jas_eprintf("error: cannot load image data\n"); exit(EXIT_FAILURE); } endclk = clock(); dectime = endclk - startclk; /* If requested, throw away all of the components except one. Why might this be desirable? It is a hack, really. None of the image formats other than the JPEG-2000 ones support images with two, four, five, or more components. This hack allows such images to be decoded with the non-JPEG-2000 decoders, one component at a time. */ numcmpts = jas_image_numcmpts(image); if (cmdopts->cmptno >= 0 && cmdopts->cmptno < numcmpts) { for (i = numcmpts - 1; i >= 0; --i) { if (i != cmdopts->cmptno) { jas_image_delcmpt(image, i); } } } if (cmdopts->srgb) { jas_image_t *newimage; jas_cmprof_t *outprof; jas_eprintf("forcing conversion to sRGB\n"); if (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) { jas_eprintf("cannot create sRGB profile\n"); exit(EXIT_FAILURE); } if (!(newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER))) { jas_eprintf("cannot convert to sRGB\n"); exit(EXIT_FAILURE); } jas_image_destroy(image); jas_cmprof_destroy(outprof); image = newimage; } /* Generate the output image data. */ startclk = clock(); if (jas_image_encode(image, out, cmdopts->outfmt, cmdopts->outopts)) { jas_eprintf("error: cannot encode image\n"); exit(EXIT_FAILURE); } jas_stream_flush(out); endclk = clock(); enctime = endclk - startclk; if (cmdopts->verbose) { jas_eprintf("decoding time = %f\n", dectime / (double) CLOCKS_PER_SEC); jas_eprintf("encoding time = %f\n", enctime / (double) CLOCKS_PER_SEC); } /* If this fails, we don't care. */ (void) jas_stream_close(in); /* Close the output image stream. */ if (jas_stream_close(out)) { jas_eprintf("error: cannot close output image file\n"); exit(EXIT_FAILURE); } cmdopts_destroy(cmdopts); jas_image_destroy(image); jas_image_clearfmts(); /* Success at last! :-) */ return EXIT_SUCCESS; }
DEFINE_LOADER_PLUGIN_LOAD(p, st, vw #if !defined(IDENTIFY_BEFORE_LOAD) __attribute__((unused)) #endif , c #if !defined(IDENTIFY_BEFORE_LOAD) __attribute__((unused)) #endif , priv #if !defined(IDENTIFY_BEFORE_LOAD) __attribute__((unused)) #endif ) { jas_image_t *ji; jas_stream_t *js; unsigned char *d; char *buf = NULL; int k, cmp[3]; unsigned int i, j; int tlx, tly; int vs, hs; //debug_message("JasPer: load() called\n"); #ifdef IDENTIFY_BEFORE_LOAD { LoaderStatus status; if ((status = identify(p, st, vw, c, priv)) != LOAD_OK) return status; stream_rewind(st); } #endif /* Read whole stream into buffer... */ { char *tmp; int size = 0, len; int bufsize = 65536; for (;;) { if ((tmp = realloc(buf, bufsize)) == NULL) { free(buf); return LOAD_ERROR; } buf = tmp; len = stream_read(st, (unsigned char *)(buf + size), bufsize - size); size += len; if (len < bufsize - size) break; bufsize += 65536; } if ((js = jas_stream_memopen(buf, size)) == NULL) { free(buf); return LOAD_ERROR; } } /* loading... */ if ((ji = jas_image_decode(js, -1, 0)) == NULL) { err_message_fnc("jas_image_decode() failed.\n"); goto error_clear; } /* colorspace conversion */ { jas_cmprof_t *jc; jas_image_t *new_ji; if ((jc = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)) == NULL) goto error_destroy_free; if ((new_ji = jas_image_chclrspc(ji, jc, JAS_CMXFORM_INTENT_PER)) == NULL) goto error_destroy_free; jas_image_destroy(ji); ji = new_ji; } jas_stream_close(js); free(buf); debug_message("JasPer: jas_image_decode() OK: (%ld,%ld)\n", jas_image_cmptwidth(ji, 0), jas_image_cmptheight(ji, 0)); /* convert to enfle format */ p->bits_per_pixel = 24; p->type = _RGB24; p->depth = 24; cmp[0] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); cmp[1] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); cmp[2] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); /* dimension */ image_width(p) = jas_image_cmptwidth(ji, cmp[0]); image_height(p) = jas_image_cmptheight(ji, cmp[0]); image_left(p) = 0; image_top(p) = 0; image_bpl(p) = image_width(p) * 3; tlx = jas_image_cmpttlx(ji, cmp[0]); tly = jas_image_cmpttly(ji, cmp[0]); vs = jas_image_cmptvstep(ji, cmp[0]); hs = jas_image_cmpthstep(ji, cmp[0]); debug_message("JasPer: tlx %d tly %d vs %d hs %d ncomponents %d\n", tlx, tly, vs, hs, jas_image_numcmpts(ji)); /* memory allocation */ if ((d = memory_alloc(image_image(p), image_bpl(p) * image_height(p))) == NULL) { err_message("No enough memory (%d bytes)\n", image_bpl(p) * image_height(p)); goto error_destroy_free; } for (i = 0; i < image_height(p); i++) { for (j = 0; j < image_width(p); j++) { for (k = 0; k < 3; k++) *d++ = jas_image_readcmptsample(ji, cmp[k], j, i); } } jas_image_destroy(ji); return LOAD_OK; error_destroy_free: jas_image_destroy(ji); error_clear: return LOAD_ERROR; }
static GstFlowReturn gst_jasper_dec_get_picture (GstJasperDec * dec, guint8 * data, guint size, GstBuffer ** outbuf) { GstFlowReturn ret = GST_FLOW_OK; jas_stream_t *stream = NULL; jas_image_t *image = NULL; gint i; g_return_val_if_fail (outbuf != NULL, GST_FLOW_ERROR); *outbuf = NULL; if (!(stream = jas_stream_memopen ((gpointer) data, size))) goto fail_stream; if (!(image = jas_image_decode (stream, dec->fmt, (char *) ""))) goto fail_decode; ret = gst_jasper_dec_negotiate (dec, image); if (ret != GST_FLOW_OK) goto fail_negotiate; ret = gst_pad_alloc_buffer_and_set_caps (dec->srcpad, GST_BUFFER_OFFSET_NONE, dec->image_size, GST_PAD_CAPS (dec->srcpad), outbuf); if (ret != GST_FLOW_OK) goto no_buffer; if (dec->alpha) memset (GST_BUFFER_DATA (*outbuf), 0xff, dec->image_size); for (i = 0; i < dec->channels; ++i) { gint x, y, cwidth, cheight, inc, stride, cmpt; guint8 *row_pix, *out_pix; glong *tb; inc = dec->inc[i]; stride = dec->stride[i]; cmpt = dec->cmpt[i]; cheight = dec->cheight[cmpt]; cwidth = dec->cwidth[cmpt]; GST_LOG_OBJECT (dec, "retrieve component %d<=%d, size %dx%d, offset %d, inc %d, stride %d", i, cmpt, cwidth, cheight, dec->offset[i], inc, stride); out_pix = GST_BUFFER_DATA (*outbuf) + dec->offset[i]; for (y = 0; y < cheight; y++) { row_pix = out_pix; tb = dec->buf; if (jas_image_readcmpt2 (image, i, 0, y, cwidth, 1, dec->buf)) goto fail_image; for (x = 0; x < cwidth; x++) { *out_pix = *tb; tb++; out_pix += inc; } out_pix = row_pix + stride; } } GST_LOG_OBJECT (dec, "all components retrieved"); done: if (image) jas_image_destroy (image); if (stream) jas_stream_close (stream); return ret; /* ERRORS */ fail_stream: { GST_DEBUG_OBJECT (dec, "Failed to create inputstream."); goto fail; } fail_decode: { GST_DEBUG_OBJECT (dec, "Failed to decode image."); goto fail; } fail_image: { GST_DEBUG_OBJECT (dec, "Failed to process decoded image."); goto fail; } fail: { if (*outbuf) gst_buffer_unref (*outbuf); *outbuf = NULL; GST_ELEMENT_WARNING (dec, STREAM, DECODE, (NULL), (NULL)); ret = GST_FLOW_OK; goto done; } no_buffer: { GST_DEBUG_OBJECT (dec, "Failed to create outbuffer - %s", gst_flow_get_name (ret)); goto done; } fail_negotiate: { GST_DEBUG_OBJECT (dec, "Failed to determine output caps."); goto done; } }
int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; if (jas_init()) { errprint(0, "error: cannot initialize jasper library\n"); abort(); } /* set our error callback */ jas_set_error_cb(errprint); cmdname = argv[0]; infile = 0; verbose = 0; /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_HELP: default: usage(); break; } } /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, "rb"))) { jas_eprintf("cannot open input image file %s\n", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, "rb"))) { jas_eprintf("cannot open standard input\n"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { jas_eprintf("unknown image format\n"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { jas_eprintf("cannot load image\n"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); numcmpts = jas_image_numcmpts(image); width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } jas_eprintf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }
CPL_C_END int dec_jpeg2000(char *injpc,g2int bufsize,g2int *outfld) /*$$$ SUBPROGRAM DOCUMENTATION BLOCK * . . . . * SUBPROGRAM: dec_jpeg2000 Decodes JPEG2000 code stream * PRGMMR: Gilbert ORG: W/NP11 DATE: 2002-12-02 * * ABSTRACT: This Function decodes a JPEG2000 code stream specified in the * JPEG2000 Part-1 standard (i.e., ISO/IEC 15444-1) using JasPer * Software version 1.500.4 (or 1.700.2) written by the University of British * Columbia and Image Power Inc, and others. * JasPer is available at http://www.ece.uvic.ca/~mdadams/jasper/. * * PROGRAM HISTORY LOG: * 2002-12-02 Gilbert * * USAGE: int dec_jpeg2000(char *injpc,g2int bufsize,g2int *outfld) * * INPUT ARGUMENTS: * injpc - Input JPEG2000 code stream. * bufsize - Length (in bytes) of the input JPEG2000 code stream. * * OUTPUT ARGUMENTS: * outfld - Output matrix of grayscale image values. * * RETURN VALUES : * 0 = Successful decode * -3 = Error decode jpeg2000 code stream. * -5 = decoded image had multiple color components. * Only grayscale is expected. * * REMARKS: * * Requires JasPer Software version 1.500.4 or 1.700.2 * * ATTRIBUTES: * LANGUAGE: C * MACHINE: IBM SP * *$$$*/ { #ifndef HAVE_JASPER // J2K_SUBFILE method // create "memory file" from buffer int fileNumber = 0; VSIStatBufL sStatBuf; CPLString osFileName = "/vsimem/work.jpc"; // ensure we don't overwrite an existing file accidentally while ( VSIStatL( osFileName, &sStatBuf ) == 0 ) { osFileName.Printf( "/vsimem/work%d.jpc", ++fileNumber ); } VSIFCloseL( VSIFileFromMemBuffer( osFileName, (unsigned char*)injpc, bufsize, FALSE ) ); // TRUE to let vsi delete the buffer when done // Open memory buffer for reading GDALDataset* poJ2KDataset = (GDALDataset *) GDALOpen( osFileName, GA_ReadOnly ); if( poJ2KDataset == NULL ) { printf("dec_jpeg2000: Unable to open JPEG2000 image within GRIB file.\n" "Is the JPEG2000 driver available?" ); return -3; } if( poJ2KDataset->GetRasterCount() != 1 ) { printf("dec_jpeg2000: Found color image. Grayscale expected.\n"); return (-5); } // Fulfill administration: initialize parameters required for RasterIO int nXSize = poJ2KDataset->GetRasterXSize(); int nYSize = poJ2KDataset->GetRasterYSize(); int nXOff = 0; int nYOff = 0; int nBufXSize = nXSize; int nBufYSize = nYSize; GDALDataType eBufType = GDT_Int32; // map to type of "outfld" buffer: g2int* int nBandCount = 1; int* panBandMap = NULL; int nPixelSpace = 0; int nLineSpace = 0; int nBandSpace = 0; // Decompress the JPEG2000 into the output integer array. poJ2KDataset->RasterIO( GF_Read, nXOff, nYOff, nXSize, nYSize, outfld, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace, NULL ); // close source file, and "unlink" it. GDALClose( poJ2KDataset ); VSIUnlink( osFileName ); return 0; #else // JasPer method int ier; g2int i,j,k; jas_image_t *image=0; jas_stream_t *jpcstream; jas_image_cmpt_t *pcmpt; char *opts=0; jas_matrix_t *data; // jas_init(); ier=0; // // Create jas_stream_t containing input JPEG200 codestream in memory. // jpcstream=jas_stream_memopen(injpc,bufsize); // // Decode JPEG200 codestream into jas_image_t structure. // image=jpc_decode(jpcstream,opts); if ( image == 0 ) { printf(" jpc_decode return = %d \n",ier); return -3; } pcmpt=image->cmpts_[0]; // Expecting jpeg2000 image to be grayscale only. // No color components. // if (image->numcmpts_ != 1 ) { printf("dec_jpeg2000: Found color image. Grayscale expected.\n"); return (-5); } // // Create a data matrix of grayscale image values decoded from // the jpeg2000 codestream. // data=jas_matrix_create(jas_image_height(image), jas_image_width(image)); jas_image_readcmpt(image,0,0,0,jas_image_width(image), jas_image_height(image),data); // // Copy data matrix to output integer array. // k=0; for (i=0; i<pcmpt->height_; i++) for (j=0; j<pcmpt->width_; j++) outfld[k++]=data->rows_[i][j]; // // Clean up JasPer work structures. // jas_matrix_destroy(data); ier=jas_stream_close(jpcstream); jas_image_destroy(image); return 0; #endif }
int main(int argc, char **argv) { char *origpath; char *reconpath; int verbose; char *metricname; int metric; int id; jas_image_t *origimage; jas_image_t *reconimage; jas_matrix_t *origdata; jas_matrix_t *recondata; jas_image_t *diffimage; jas_stream_t *diffstream; int width; int height; int depth; int numcomps; double d; double maxdist; double mindist; int compno; jas_stream_t *origstream; jas_stream_t *reconstream; char *diffpath; int maxonly; int minonly; int fmtid; verbose = 0; origpath = 0; reconpath = 0; metricname = 0; metric = metricid_none; diffpath = 0; maxonly = 0; minonly = 0; if (jas_init()) { errprint(0, "error: cannot initialize jasper library\n"); abort(); } /* set our error callback */ jas_set_error_cb(errprint); cmdname = argv[0]; /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_MAXONLY: maxonly = 1; break; case OPT_MINONLY: minonly = 1; break; case OPT_METRIC: metricname = jas_optarg; break; case OPT_ORIG: origpath = jas_optarg; break; case OPT_RECON: reconpath = jas_optarg; break; case OPT_VERBOSE: verbose = 1; break; case OPT_DIFFIMAGE: diffpath = jas_optarg; break; case OPT_VERSION: printf("%s\n", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_HELP: default: usage(); break; } } if (verbose) { cmdinfo(); } /* Ensure that files are given for both the original and reconstructed images. */ if (!origpath || !reconpath) { usage(); } /* If a metric was specified, process it. */ if (metricname) { if ((metric = (jas_taginfo_nonull(jas_taginfos_lookup(metrictab, metricname))->id)) < 0) { usage(); } } /* Open the original image file. */ if (!(origstream = jas_stream_fopen(origpath, "rb"))) { jas_eprintf("cannot open %s\n", origpath); return EXIT_FAILURE; } /* Open the reconstructed image file. */ if (!(reconstream = jas_stream_fopen(reconpath, "rb"))) { jas_eprintf("cannot open %s\n", reconpath); return EXIT_FAILURE; } /* Decode the original image. */ if (!(origimage = jas_image_decode(origstream, -1, 0))) { jas_eprintf("cannot load original image\n"); return EXIT_FAILURE; } /* Decoder the reconstructed image. */ if (!(reconimage = jas_image_decode(reconstream, -1, 0))) { jas_eprintf("cannot load reconstructed image\n"); return EXIT_FAILURE; } /* Close the original image file. */ jas_stream_close(origstream); /* Close the reconstructed image file. */ jas_stream_close(reconstream); /* Ensure that both images have the same number of components. */ numcomps = jas_image_numcmpts(origimage); if (jas_image_numcmpts(reconimage) != numcomps) { jas_eprintf("number of components differ\n"); return EXIT_FAILURE; } /* Compute the difference for each component. */ maxdist = 0; mindist = FLT_MAX; for (compno = 0; compno < numcomps; ++compno) { width = jas_image_cmptwidth(origimage, compno); height = jas_image_cmptheight(origimage, compno); depth = jas_image_cmptprec(origimage, compno); if (jas_image_cmptwidth(reconimage, compno) != width || jas_image_cmptheight(reconimage, compno) != height) { jas_eprintf("image dimensions differ\n"); return EXIT_FAILURE; } if (jas_image_cmptprec(reconimage, compno) != depth) { jas_eprintf("precisions differ\n"); return EXIT_FAILURE; } if (!(origdata = jas_matrix_create(height, width))) { jas_eprintf("internal error\n"); return EXIT_FAILURE; } if (!(recondata = jas_matrix_create(height, width))) { jas_eprintf("internal error\n"); return EXIT_FAILURE; } if (jas_image_readcmpt(origimage, compno, 0, 0, width, height, origdata)) { jas_eprintf("cannot read component data\n"); return EXIT_FAILURE; } if (jas_image_readcmpt(reconimage, compno, 0, 0, width, height, recondata)) { jas_eprintf("cannot read component data\n"); return EXIT_FAILURE; } if (diffpath) { if (!(diffstream = jas_stream_fopen(diffpath, "rwb"))) { jas_eprintf("cannot open diff stream\n"); return EXIT_FAILURE; } if (!(diffimage = makediffimage(origdata, recondata))) { jas_eprintf("cannot make diff image\n"); return EXIT_FAILURE; } fmtid = jas_image_strtofmt("pnm"); if (jas_image_encode(diffimage, diffstream, fmtid, 0)) { jas_eprintf("cannot save\n"); return EXIT_FAILURE; } jas_stream_close(diffstream); jas_image_destroy(diffimage); } if (metric != metricid_none) { d = getdistortion(origdata, recondata, depth, metric); if (d > maxdist) { maxdist = d; } if (d < mindist) { mindist = d; } if (!maxonly && !minonly) { if (metric == metricid_pae || metric == metricid_equal) { printf("%ld\n", (long) ceil(d)); } else { printf("%f\n", d); } } } jas_matrix_destroy(origdata); jas_matrix_destroy(recondata); } if (metric != metricid_none && (maxonly || minonly)) { if (maxonly) { d = maxdist; } else if (minonly) { d = mindist; } else { abort(); } if (metric == metricid_pae || metric == metricid_equal) { jas_eprintf("%ld\n", (long) ceil(d)); } else { jas_eprintf("%f\n", d); } } jas_image_destroy(origimage); jas_image_destroy(reconimage); jas_image_clearfmts(); return EXIT_SUCCESS; }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method WriteJP2Image writes an image in the JPEG 2000 image format. % % JP2 support originally written by Nathan Brown, [email protected] % % The format of the WriteJP2Image method is: % % MagickPassFail WriteJP2Image(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o status: Method WriteJP2Image return MagickTrue if the image is written. % MagickFalse is returned is there is a memory shortage or if the image file % fails to write. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % % */ static MagickPassFail WriteJP2Image(const ImageInfo *image_info,Image *image) { char magick[MaxTextExtent], option_keyval[MaxTextExtent], *options = NULL; int format; long y; jas_image_cmptparm_t component_info; jas_image_t *jp2_image; jas_matrix_t *jp2_pixels; jas_stream_t *jp2_stream; register const PixelPacket *p; register int x; unsigned int rate_specified=False, status; int component, number_components; unsigned short *lut; ImageCharacteristics characteristics; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == False) ThrowWriterException(FileOpenError,UnableToOpenFile,image); /* Ensure that image is in RGB space. */ (void) TransformColorspace(image,RGBColorspace); /* Analyze image to be written. */ if (!GetImageCharacteristics(image,&characteristics, (OptimizeType == image_info->type), &image->exception)) { CloseBlob(image); return MagickFail; } /* Obtain a JP2 stream. */ jp2_stream=JP2StreamManager(image); if (jp2_stream == (jas_stream_t *) NULL) ThrowWriterException(DelegateError,UnableToManageJP2Stream,image); number_components=image->matte ? 4 : 3; if ((image_info->type != TrueColorType) && (characteristics.grayscale)) number_components=1; jp2_image=jas_image_create0(); if (jp2_image == (jas_image_t *) NULL) ThrowWriterException(DelegateError,UnableToCreateImage,image); for (component=0; component < number_components; component++) { (void) memset((void *)&component_info,0,sizeof(jas_image_cmptparm_t)); component_info.tlx=0; /* top left x ordinate */ component_info.tly=0; /* top left y ordinate */ component_info.hstep=1; /* horizontal pixels per step */ component_info.vstep=1; /* vertical pixels per step */ component_info.width=(unsigned int) image->columns; component_info.height=(unsigned int) image->rows; component_info.prec=(unsigned int) Max(2,Min(image->depth,16)); /* bits in range */ component_info.sgnd = false; /* range is signed value? */ if (jas_image_addcmpt(jp2_image, component,&component_info)) { jas_image_destroy(jp2_image); ThrowWriterException(DelegateError,UnableToCreateImageComponent,image); } } /* Allocate and compute LUT. */ { unsigned long i, max_value; double scale_to_component; lut=MagickAllocateArray(unsigned short *,MaxMap+1,sizeof(*lut)); if (lut == (unsigned short *) NULL) { jas_image_destroy(jp2_image); ThrowWriterException(ResourceLimitError,MemoryAllocationFailed,image); } max_value=MaxValueGivenBits(component_info.prec); scale_to_component=max_value/MaxRGBDouble; for(i=0; i <= MaxMap; i++) lut[i]=scale_to_component*i+0.5; } if (number_components == 1) { /* FIXME: If image has an attached ICC profile, then the profile should be transferred and the image colorspace set to JAS_CLRSPC_GENGRAY */ /* sRGB Grayscale */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting SGRAY colorspace"); jas_image_setclrspc(jp2_image, JAS_CLRSPC_SGRAY); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting GRAY channel to channel 0"); jas_image_setcmpttype(jp2_image,0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } else { /* FIXME: If image has an attached ICC profile, then the profile should be transferred and the image colorspace set to JAS_CLRSPC_GENRGB */ /* sRGB */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting SRGB colorspace"); jas_image_setclrspc(jp2_image, JAS_CLRSPC_SRGB); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting RED channel to channel 0"); jas_image_setcmpttype(jp2_image,0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting GREEN channel to channel 1"); jas_image_setcmpttype(jp2_image,1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting BLUE channel to channel 2"); jas_image_setcmpttype(jp2_image,2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); if (number_components == 4 ) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Setting OPACITY channel to channel 3"); jas_image_setcmpttype(jp2_image,3, JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_OPACITY)); } } /* Convert to JPEG 2000 pixels. */ jp2_pixels=jas_matrix_create(1,(unsigned int) image->columns); if (jp2_pixels == (jas_matrix_t *) NULL) { MagickFreeMemory(lut); jas_image_destroy(jp2_image); ThrowWriterException(ResourceLimitError,MemoryAllocationFailed,image); } for (y=0; y < (long) image->rows; y++) { p=AcquireImagePixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (number_components == 1) { for (x=0; x < (long) image->columns; x++) jas_matrix_setv(jp2_pixels,x,lut[ScaleQuantumToMap(PixelIntensityToQuantum(&p[x]))]); (void) jas_image_writecmpt(jp2_image,0,0,(unsigned int) y, (unsigned int) image->columns,1,jp2_pixels); } else { for (x=0; x < (long) image->columns; x++) jas_matrix_setv(jp2_pixels,x,lut[ScaleQuantumToMap(p[x].red)]); (void) jas_image_writecmpt(jp2_image,0,0,(unsigned int) y, (unsigned int) image->columns,1,jp2_pixels); for (x=0; x < (long) image->columns; x++) jas_matrix_setv(jp2_pixels,x,lut[ScaleQuantumToMap(p[x].green)]); (void) jas_image_writecmpt(jp2_image,1,0,(unsigned int) y, (unsigned int) image->columns,1,jp2_pixels); for (x=0; x < (long) image->columns; x++) jas_matrix_setv(jp2_pixels,x,lut[ScaleQuantumToMap(p[x].blue)]); (void) jas_image_writecmpt(jp2_image,2,0,(unsigned int) y, (unsigned int) image->columns,1,jp2_pixels); if (number_components > 3) for (x=0; x < (long) image->columns; x++) jas_matrix_setv(jp2_pixels,x,lut[ScaleQuantumToMap(MaxRGB-p[x].opacity)]); (void) jas_image_writecmpt(jp2_image,3,0,(unsigned int) y, (unsigned int) image->columns,1,jp2_pixels); } if (image->previous == (Image *) NULL) if (QuantumTick(y,image->rows)) if (!MagickMonitorFormatted(y,image->rows,&image->exception, SaveImageText,image->filename, image->columns,image->rows)) break; } (void) strlcpy(magick,image_info->magick,MaxTextExtent); /* J2C is an alias for JPC but Jasper only supports "JPC". */ if (LocaleCompare(magick,"j2c") == 0) (void) strlcpy(magick,"jpc",sizeof(magick)); LocaleLower(magick); format=jas_image_strtofmt(magick); /* Support passing Jasper options. */ { const char **option_name; static const char *jasper_options[] = { "imgareatlx", "imgareatly", "tilegrdtlx", "tilegrdtly", "tilewidth", "tileheight", "prcwidth", "prcheight", "cblkwidth", "cblkheight", "mode", "ilyrrates", "prg", "nomct", "numrlvls", "sop", "eph", "lazy", "rate", "termall", "segsym", "vcausal", "pterm", "resetprob", "numgbits", NULL }; for (option_name = jasper_options; *option_name != NULL; option_name++) { const char *value; if ((value=AccessDefinition(image_info,"jp2",*option_name)) != NULL) { if(LocaleCompare(*option_name,"rate") == 0) rate_specified=True; FormatString(option_keyval,"%s=%.1024s ",*option_name,value); ConcatenateString(&options,option_keyval); } } } /* Provide an emulation of IJG JPEG "quality" by default. */ if (rate_specified == False) { double rate=1.0; /* A rough approximation to JPEG v1 quality using JPEG-2000. Default "quality" 75 results in a request for 16:1 compression, which results in image sizes approximating that of JPEG v1. */ if ((image_info->quality < 99.5) && (image->rows*image->columns > 2500)) { double header_size, current_size, target_size, d; d=115-image_info->quality; /* Best number is 110-115 */ rate=100.0/(d*d); header_size=550.0; /* Base file size. */ header_size+=(number_components-1)*142; /* Additional components */ /* FIXME: Need to account for any ICC profiles here */ current_size=(double)((image->rows*image->columns*image->depth)/8)* number_components; target_size=(current_size*rate)+header_size; rate=target_size/current_size; } FormatString(option_keyval,"%s=%g ","rate",rate); ConcatenateString(&options,option_keyval); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Compression rate: %g (%3.2f:1)",rate,1.0/rate); } if (options) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Jasper options: \"%s\"", options); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Encoding image"); status=jas_image_encode(jp2_image,jp2_stream,format,options); (void) jas_stream_close(jp2_stream); MagickFreeMemory(options); MagickFreeMemory(lut); jas_matrix_destroy(jp2_pixels); jas_image_destroy(jp2_image); if (status) ThrowWriterException(DelegateError,UnableToEncodeImageFile,image); return(True); }
static Image *ReadJP2Image(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; long y; jas_image_t *jp2_image; jas_matrix_t *pixels; jas_stream_t *jp2_stream; register long x; register PixelPacket *q; int component, components[4], number_components; Quantum *channel_lut[4]; unsigned int status; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AllocateImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == False) ThrowReaderException(FileOpenError,UnableToOpenFile,image); /* Obtain a JP2 Stream. */ jp2_stream=JP2StreamManager(image); if (jp2_stream == (jas_stream_t *) NULL) ThrowReaderException(DelegateError,UnableToManageJP2Stream,image); jp2_image=jas_image_decode(jp2_stream,-1,0); if (jp2_image == (jas_image_t *) NULL) { (void) jas_stream_close(jp2_stream); ThrowReaderException(DelegateError,UnableToDecodeImageFile,image); } /* Validate that we can handle the image and obtain component indexes. */ switch (jas_clrspc_fam(jas_image_clrspc(jp2_image))) { case JAS_CLRSPC_FAM_RGB: { if (((components[0]= jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0) || ((components[1]= jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0) || ((components[2]= jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,MissingImageChannel,image); } number_components=3; (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image is in RGB colorspace family"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "RED is in channel %d, GREEN is in channel %d, BLUE is in channel %d", components[0],components[1],components[2]); if((components[3]=jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_OPACITY))) > 0) { image->matte=MagickTrue; (void) LogMagickEvent(CoderEvent,GetMagickModule(), "OPACITY is in channel %d",components[3]); number_components++; } break; } case JAS_CLRSPC_FAM_GRAY: { if ((components[0]= jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,MissingImageChannel,image); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image is in GRAY colorspace family"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "GRAY is in channel %d",components[0]); number_components=1; break; } case JAS_CLRSPC_FAM_YCBCR: { components[0]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_YCBCR_Y); components[1]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_YCBCR_CB); components[2]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_YCBCR_CR); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,MissingImageChannel,image); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_OPACITY); if (components[3] > 0) { image->matte=True; number_components++; } image->colorspace=YCbCrColorspace; (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image is in YCBCR colorspace family"); break; } default: { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CoderError,ColorspaceModelIsNotSupported,image); } } image->columns=jas_image_width(jp2_image); image->rows=jas_image_height(jp2_image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "columns=%lu rows=%lu components=%d",image->columns,image->rows, number_components); for (component=0; component < number_components; component++) { if(((unsigned long) jas_image_cmptwidth(jp2_image,components[component]) != image->columns) || ((unsigned long) jas_image_cmptheight(jp2_image,components[component]) != image->rows) || (jas_image_cmpttlx(jp2_image, components[component]) != 0) || (jas_image_cmpttly(jp2_image, components[component]) != 0) || (jas_image_cmpthstep(jp2_image, components[component]) != 1) || (jas_image_cmptvstep(jp2_image, components[component]) != 1) || (jas_image_cmptsgnd(jp2_image, components[component]) != false)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CoderError,IrregularChannelGeometryNotSupported,image); } } image->matte=number_components > 3; for (component=0; component < number_components; component++) { unsigned int component_depth; component_depth=jas_image_cmptprec(jp2_image,components[component]); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Component[%d] depth is %u",component,component_depth); if (0 == component) image->depth=component_depth; else image->depth=Max(image->depth,component_depth); } (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image depth is %u",image->depth); if (image_info->ping) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); return(image); } /* Allocate Jasper pixels. */ pixels=jas_matrix_create(1,(unsigned int) image->columns); if (pixels == (jas_matrix_t *) NULL) { jas_image_destroy(jp2_image); ThrowReaderException(ResourceLimitError,MemoryAllocationFailed,image); } /* Allocate and populate channel LUTs */ for (component=0; component < (long) number_components; component++) { unsigned long component_depth, i, max_value; double scale_to_quantum; component_depth=jas_image_cmptprec(jp2_image,components[component]); max_value=MaxValueGivenBits(component_depth); scale_to_quantum=MaxRGBDouble/max_value; (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Channel %d scale is %g", component, scale_to_quantum); channel_lut[component]=MagickAllocateArray(Quantum *,max_value+1,sizeof(Quantum)); if (channel_lut[component] == (Quantum *) NULL) { for ( --component; component >= 0; --component) MagickFreeMemory(channel_lut[component]); jas_matrix_destroy(pixels); jas_image_destroy(jp2_image); ThrowReaderException(ResourceLimitError,MemoryAllocationFailed,image); } for(i=0; i <= max_value; i++) (channel_lut[component])[i]=scale_to_quantum*i+0.5; } /* Convert JPEG 2000 pixels. */ for (y=0; y < (long) image->rows; y++) { q=GetImagePixels(image,0,y,image->columns,1); if (q == (PixelPacket *) NULL) break; if (1 == number_components) { /* Grayscale */ (void) jas_image_readcmpt(jp2_image,(short) components[0],0, (unsigned int) y, (unsigned int) image->columns,1,pixels); for (x=0; x < (long) image->columns; x++) { q->red=q->green=q->blue=(channel_lut[0])[jas_matrix_getv(pixels,x)]; q->opacity=OpaqueOpacity; q++; } } else { /* Red */ (void) jas_image_readcmpt(jp2_image,(short) components[0],0, (unsigned int) y, (unsigned int) image->columns,1,pixels); for (x=0; x < (long) image->columns; x++) q[x].red=(channel_lut[0])[jas_matrix_getv(pixels,x)]; /* Green */ (void) jas_image_readcmpt(jp2_image,(short) components[1],0, (unsigned int) y, (unsigned int) image->columns,1,pixels); for (x=0; x < (long) image->columns; x++) q[x].green=(channel_lut[1])[jas_matrix_getv(pixels,x)]; /* Blue */ (void) jas_image_readcmpt(jp2_image,(short) components[2],0, (unsigned int) y, (unsigned int) image->columns,1,pixels); for (x=0; x < (long) image->columns; x++) q[x].blue=(channel_lut[2])[jas_matrix_getv(pixels,x)]; /* Opacity */ if (number_components > 3) { (void) jas_image_readcmpt(jp2_image,(short) components[3],0, (unsigned int) y, (unsigned int) image->columns,1,pixels); for (x=0; x < (long) image->columns; x++) q[x].opacity=MaxRGB-(channel_lut[3])[jas_matrix_getv(pixels,x)]; } else { for (x=0; x < (long) image->columns; x++) q[x].opacity=OpaqueOpacity; } } if (!SyncImagePixels(image)) break; if (image->previous == (Image *) NULL) if (QuantumTick(y,image->rows)) if (!MagickMonitorFormatted(y,image->rows,exception,LoadImageText, image->filename, image->columns,image->rows)) break; } if (number_components == 1) image->is_grayscale=MagickTrue; { /* Obtain ICC ICM color profile */ jas_cmprof_t *cm_profile; /* Obtain a pointer to the existing jas_cmprof_t profile handle. */ cm_profile=jas_image_cmprof(jp2_image); if (cm_profile != (jas_cmprof_t *) NULL) { jas_iccprof_t *icc_profile; /* Obtain a copy of the jas_iccprof_t ICC profile handle */ icc_profile=jas_iccprof_createfromcmprof(cm_profile); /* or maybe just icc_profile=cm_profile->iccprof */ if (icc_profile != (jas_iccprof_t *) NULL) { jas_stream_t *icc_stream; icc_stream=jas_stream_memopen(NULL,0); if ((icc_stream != (jas_stream_t *) NULL) && (jas_iccprof_save(icc_profile,icc_stream) == 0) && (jas_stream_flush(icc_stream) == 0)) { jas_stream_memobj_t *blob; blob=(jas_stream_memobj_t *) icc_stream->obj_; if (image->logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "ICC profile: %lu bytes",(unsigned long) blob->len_); SetImageProfile(image,"ICM",blob->buf_,blob->len_); (void) jas_stream_close(icc_stream); jas_iccprof_destroy(icc_profile); } } } } for (component=0; component < (long) number_components; component++) MagickFreeMemory(channel_lut[component]); jas_matrix_destroy(pixels); (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); return(image); }
bool Jpeg2KDecoder::readData(Mat& img) { bool result = false; int color = img.channels() > 1; uchar* data = img.data; int step = img.step; jas_stream_t* stream = (jas_stream_t*)m_stream; jas_image_t* image = (jas_image_t*)m_image; if (stream && image) { bool convert; int colorspace; if (color) { convert = (jas_image_clrspc(image) != JAS_CLRSPC_SRGB); colorspace = JAS_CLRSPC_SRGB; } else { convert = (jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_GRAY); colorspace = JAS_CLRSPC_SGRAY; // TODO GENGRAY or SGRAY? } // convert to the desired colorspace if (convert) { jas_cmprof_t* clrprof = jas_cmprof_createfromclrspc(colorspace); if (clrprof) { jas_image_t* _img = jas_image_chclrspc(image, clrprof, JAS_CMXFORM_INTENT_RELCLR); if (_img) { jas_image_destroy(image); m_image = image = _img; result = true; } else { fprintf(stderr, "JPEG 2000 LOADER ERROR: cannot convert colorspace\n"); } jas_cmprof_destroy(clrprof); } else { fprintf(stderr, "JPEG 2000 LOADER ERROR: unable to create colorspace\n"); } } else { result = true; } if (result) { int ncmpts; int cmptlut[3]; if (color) { cmptlut[0] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_RGB_B); cmptlut[1] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_RGB_G); cmptlut[2] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_RGB_R); if (cmptlut[0] < 0 || cmptlut[1] < 0 || cmptlut[0] < 0) { result = false; } ncmpts = 3; } else { cmptlut[0] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_GRAY_Y); if (cmptlut[0] < 0) { result = false; } ncmpts = 1; } if (result) { for (int i = 0; i < ncmpts; i++) { int maxval = 1 << jas_image_cmptprec(image, cmptlut[i]); int offset = jas_image_cmptsgnd(image, cmptlut[i]) ? maxval / 2 : 0; int yend = jas_image_cmptbry(image, cmptlut[i]); int ystep = jas_image_cmptvstep(image, cmptlut[i]); int xend = jas_image_cmptbrx(image, cmptlut[i]); int xstep = jas_image_cmpthstep(image, cmptlut[i]); jas_matrix_t* buffer = jas_matrix_create(yend / ystep, xend / xstep); if (buffer) { if (!jas_image_readcmpt(image, cmptlut[i], 0, 0, xend / xstep, yend / ystep, buffer)) { if (img.depth() == CV_8U) { result = readComponent8u(data + i, buffer, step, cmptlut[i], maxval, offset, ncmpts); } else { result = readComponent16u(((unsigned short*)data) + i, buffer, step / 2, cmptlut[i], maxval, offset, ncmpts); } if (!result) { i = ncmpts; result = false; } } jas_matrix_destroy(buffer); } } } } else { fprintf(stderr, "JPEG2000 LOADER ERROR: colorspace conversion failed\n"); } } close(); return result; }