static void ReadJP2KImage( GenericImage<P>& img, jas_stream_t* jp2Stream, jas_image_t* jp2Image ) { int width = jas_image_cmptwidth( jp2Image, 0 ); int height = jas_image_cmptheight( jp2Image, 0 ); int numberOfChannels = jas_image_numcmpts( jp2Image ); jas_matrix_t* pixels = nullptr; try { pixels = jas_matrix_create( 1, width ); if ( pixels == nullptr ) throw Error( "Memory allocation error reading JPEG2000 image" ); // Allocate pixel data img.AllocateData( width, height, numberOfChannels, (jas_clrspc_fam( jas_image_clrspc( jp2Image ) ) == JAS_CLRSPC_FAM_GRAY) ? ColorSpace::Gray : ColorSpace::RGB ); for ( int c = 0; c < numberOfChannels; ++c ) { int n = jas_image_cmptprec( jp2Image, c ); bool s = jas_image_cmptsgnd( jp2Image, c ) != 0; for ( int y = 0; y < height; ++y ) { jas_image_readcmpt( jp2Image, c, 0, y, width, 1, pixels ); typename P::sample* f = img.ScanLine( y, c ); if ( n == 8 ) { if ( s ) for ( int x = 0; x < width; ++x ) *f++ = P::ToSample( int8( jas_matrix_get( pixels, 0, x ) ) ); else for ( int x = 0; x < width; ++x ) *f++ = P::ToSample( uint8( jas_matrix_get( pixels, 0, x ) ) ); } else { if ( s ) for ( int x = 0; x < width; ++x ) *f++ = P::ToSample( int16( jas_matrix_get( pixels, 0, x ) ) ); else for ( int x = 0; x < width; ++x ) *f++ = P::ToSample( uint16( jas_matrix_get( pixels, 0, x ) ) ); } } } jas_matrix_destroy( pixels ), pixels = nullptr; } catch ( ... ) { if ( pixels != nullptr ) jas_matrix_destroy( pixels ); throw; } }
static void createMatrices(struct pam * const outpamP, jas_matrix_t *** matrixP) { jas_matrix_t ** matrix; unsigned int plane; MALLOCARRAY_NOFAIL(matrix, outpamP->depth); for (plane = 0; plane < outpamP->depth; ++plane) { matrix[plane] = jas_matrix_create(1, outpamP->width); if (matrix[plane] == NULL) pm_error("Unable to create matrix for plane %u. " "jas_matrix_create() failed.", plane); } *matrixP = matrix; }
JPEG2000RasterBand::JPEG2000RasterBand( JPEG2000Dataset *poDS, int nBand, int iDepth, int bSignedness ) { this->poDS = poDS; poGDS = poDS; this->nBand = nBand; this->iDepth = iDepth; this->bSignedness = bSignedness; // XXX: JasPer can't handle data with depth > 32 bits // Maximum possible depth for JPEG2000 is 38! switch ( bSignedness ) { case 1: // Signed component if (iDepth <= 8) this->eDataType = GDT_Byte; // FIXME: should be signed, // but we haven't signed byte // data type in GDAL else if (iDepth <= 16) this->eDataType = GDT_Int16; else if (iDepth <= 32) this->eDataType = GDT_Int32; break; case 0: // Unsigned component default: if (iDepth <= 8) this->eDataType = GDT_Byte; else if (iDepth <= 16) this->eDataType = GDT_UInt16; else if (iDepth <= 32) this->eDataType = GDT_UInt32; break; } // FIXME: Figure out optimal block size! // Should the block size be fixed or determined dynamically? nBlockXSize = MIN(256, poDS->nRasterXSize); nBlockYSize = MIN(256, poDS->nRasterYSize); psMatrix = jas_matrix_create(nBlockYSize, nBlockXSize); }
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; jas_cmprof_t *cm_profile; jas_iccprof_t *icc_profile; jas_image_t *jp2_image; jas_matrix_t *pixels[4]; jas_stream_t *jp2_stream; MagickBooleanType status; QuantumAny pixel, range[4]; register Quantum *q; register ssize_t i, x; size_t maximum_component_depth, number_components, x_step[4], y_step[4]; ssize_t components[4], y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JPEG 2000 API. */ jp2_stream=JP2StreamManager(image); if (jp2_stream == (jas_stream_t *) NULL) ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); 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->columns=jas_image_width(jp2_image); image->rows=jas_image_height(jp2_image); image->compression=JPEG2000Compression; switch (jas_clrspc_fam(jas_image_clrspc(jp2_image))) { case JAS_CLRSPC_FAM_RGB: { SetImageColorspace(image,RGBColorspace,exception); components[0]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_RGB_R); components[1]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_RGB_G); components[2]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_RGB_B); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,"MissingImageChannel"); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,3); if (components[3] > 0) { image->alpha_trait=BlendPixelTrait; number_components++; } break; } case JAS_CLRSPC_FAM_GRAY: { SetImageColorspace(image,GRAYColorspace,exception); components[0]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_GRAY_Y); if (components[0] < 0) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,"MissingImageChannel"); } number_components=1; break; } case JAS_CLRSPC_FAM_YCBCR: { SetImageColorspace(image,YCbCrColorspace,exception); 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"); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_UNKNOWN); if (components[3] > 0) { image->alpha_trait=BlendPixelTrait; number_components++; } break; } case JAS_CLRSPC_FAM_XYZ: { SetImageColorspace(image,XYZColorspace,exception); components[0]=jas_image_getcmptbytype(jp2_image,0); components[1]=jas_image_getcmptbytype(jp2_image,1); components[2]=jas_image_getcmptbytype(jp2_image,2); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,"MissingImageChannel"); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_UNKNOWN); if (components[3] > 0) { image->alpha_trait=BlendPixelTrait; number_components++; } break; } case JAS_CLRSPC_FAM_LAB: { SetImageColorspace(image,LabColorspace,exception); components[0]=jas_image_getcmptbytype(jp2_image,0); components[1]=jas_image_getcmptbytype(jp2_image,1); components[2]=jas_image_getcmptbytype(jp2_image,2); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,"MissingImageChannel"); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_UNKNOWN); if (components[3] > 0) { image->alpha_trait=BlendPixelTrait; number_components++; } break; } default: { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); } } for (i=0; i < (ssize_t) number_components; i++) { size_t height, width; width=(size_t) (jas_image_cmptwidth(jp2_image,components[i])* jas_image_cmpthstep(jp2_image,components[i])); height=(size_t) (jas_image_cmptheight(jp2_image,components[i])* jas_image_cmptvstep(jp2_image,components[i])); x_step[i]=(unsigned int) jas_image_cmpthstep(jp2_image,components[i]); y_step[i]=(unsigned int) jas_image_cmptvstep(jp2_image,components[i]); if ((width != image->columns) || (height != image->rows) || (jas_image_cmpttlx(jp2_image,components[i]) != 0) || (jas_image_cmpttly(jp2_image,components[i]) != 0) || (jas_image_cmptsgnd(jp2_image,components[i]) != MagickFalse)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported"); } } /* Convert JPEG 2000 pixels. */ image->alpha_trait=number_components > 3 ? BlendPixelTrait : UndefinedPixelTrait; maximum_component_depth=0; for (i=0; i < (ssize_t) number_components; i++) { maximum_component_depth=(unsigned int) MagickMax((size_t) jas_image_cmptprec(jp2_image,components[i]),(size_t) maximum_component_depth); pixels[i]=jas_matrix_create(1,(int) (image->columns/x_step[i])); if (pixels[i] == (jas_matrix_t *) NULL) { for (--i; i >= 0; i--) jas_matrix_destroy(pixels[i]); jas_image_destroy(jp2_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } image->depth=maximum_component_depth; if (image_info->ping != MagickFalse) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); return(GetFirstImageInList(image)); } for (i=0; i < (ssize_t) number_components; i++) range[i]=GetQuantumRange((size_t) jas_image_cmptprec(jp2_image, components[i])); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (i=0; i < (ssize_t) number_components; i++) (void) jas_image_readcmpt(jp2_image,(short) components[i],0, (jas_image_coord_t) (y/y_step[i]),(jas_image_coord_t) (image->columns/ x_step[i]),1,pixels[i]); switch (number_components) { case 1: { /* Grayscale. */ for (x=0; x < (ssize_t) image->columns; x++) { pixel=(QuantumAny) jas_matrix_getv(pixels[0],x/x_step[0]); SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) pixel,range[0]),q); q+=GetPixelChannels(image); } break; } case 3: { /* RGB. */ for (x=0; x < (ssize_t) image->columns; x++) { pixel=(QuantumAny) jas_matrix_getv(pixels[0],x/x_step[0]); SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) pixel,range[0]),q); pixel=(QuantumAny) jas_matrix_getv(pixels[1],x/x_step[1]); SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) pixel,range[1]),q); pixel=(QuantumAny) jas_matrix_getv(pixels[2],x/x_step[2]); SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) pixel,range[2]),q); q+=GetPixelChannels(image); } break; } case 4: { /* RGBA. */ for (x=0; x < (ssize_t) image->columns; x++) { pixel=(QuantumAny) jas_matrix_getv(pixels[0],x/x_step[0]); SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) pixel,range[0]),q); pixel=(QuantumAny) jas_matrix_getv(pixels[1],x/x_step[1]); SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) pixel,range[1]),q); pixel=(QuantumAny) jas_matrix_getv(pixels[2],x/x_step[2]); SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) pixel,range[2]),q); pixel=(QuantumAny) jas_matrix_getv(pixels[3],x/x_step[3]); SetPixelAlpha(image,ScaleAnyToQuantum((QuantumAny) pixel,range[3]),q); q+=GetPixelChannels(image); } break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } cm_profile=jas_image_cmprof(jp2_image); icc_profile=(jas_iccprof_t *) NULL; if (cm_profile != (jas_cmprof_t *) NULL) icc_profile=jas_iccprof_createfromcmprof(cm_profile); 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; StringInfo *icc_profile, *profile; /* Extract the icc profile, handle errors without much noise. */ blob=(jas_stream_memobj_t *) icc_stream->obj_; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %.20g bytes",(double) blob->len_); profile=BlobToStringInfo(blob->buf_,blob->len_); if (profile == (StringInfo *) NULL) ThrowReaderException(CorruptImageError,"MemoryAllocationFailed"); icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile == (StringInfo *) NULL) (void) SetImageProfile(image,"icc",profile,exception); else (void) ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); (void) jas_stream_close(icc_stream); } } (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); for (i=0; i < (ssize_t) number_components; i++) jas_matrix_destroy(pixels[i]); return(GetFirstImageInList(image)); }
static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band, jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs) { jpc_dec_seg_t *seg; int i; int bpno; int passtype; int ret; int compno; int filldata; int fillmask; jpc_dec_ccp_t *ccp; compno = tcomp - tile->tcomps; if (!cblk->flags) { /* Note: matrix is assumed to be zeroed */ if (!(cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2, jas_matrix_numcols(cblk->data) + 2))) { return -1; } } seg = cblk->segs.head; while (seg && (seg != cblk->curseg || dopartial) && (maxlyrs < 0 || seg->lyrno < maxlyrs)) { assert(seg->numpasses >= seg->maxpasses || dopartial); assert(seg->stream); jas_stream_rewind(seg->stream); jas_stream_setrwcount(seg->stream, 0); if (seg->type == JPC_SEG_MQ) { if (!cblk->mqdec) { if (!(cblk->mqdec = jpc_mqdec_create(JPC_NUMCTXS, 0))) { return -1; } jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs); } jpc_mqdec_setinput(cblk->mqdec, seg->stream); jpc_mqdec_init(cblk->mqdec); } else { assert(seg->type == JPC_SEG_RAW); if (!cblk->nulldec) { if (!(cblk->nulldec = jpc_bitstream_sopen(seg->stream, "r"))) { assert(0); } } } for (i = 0; i < seg->numpasses; ++i) { if (cblk->numimsbs > band->numbps) { ccp = &tile->cp->ccps[compno]; if (ccp->roishift <= 0) { jas_eprintf("warning: corrupt code stream\n"); } else { if (cblk->numimsbs < ccp->roishift - band->numbps) { jas_eprintf("warning: corrupt code stream\n"); } } } bpno = band->roishift + band->numbps - 1 - (cblk->numimsbs + (seg->passno + i - cblk->firstpassno + 2) / 3); if (bpno < 0) { goto premature_exit; } #if 1 passtype = (seg->passno + i + 2) % 3; #else passtype = JPC_PASSTYPE(seg->passno + i + 2); #endif assert(bpno >= 0 && bpno < 31); switch (passtype) { case JPC_SIGPASS: ret = (seg->type == JPC_SEG_MQ) ? dec_sigpass(dec, cblk->mqdec, bpno, band->orient, (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, cblk->flags, cblk->data) : dec_rawsigpass(dec, cblk->nulldec, bpno, (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, cblk->flags, cblk->data); break; case JPC_REFPASS: ret = (seg->type == JPC_SEG_MQ) ? dec_refpass(dec, cblk->mqdec, bpno, (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, cblk->flags, cblk->data) : dec_rawrefpass(dec, cblk->nulldec, bpno, (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, cblk->flags, cblk->data); break; case JPC_CLNPASS: assert(seg->type == JPC_SEG_MQ); ret = dec_clnpass(dec, cblk->mqdec, bpno, band->orient, (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0, (tile->cp->ccps[compno].cblkctx & JPC_COX_SEGSYM) != 0, cblk->flags, cblk->data); break; default: ret = -1; break; } /* Do we need to reset after each coding pass? */ if (tile->cp->ccps[compno].cblkctx & JPC_COX_RESET) { jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs); } if (ret) { jas_eprintf("coding pass failed passtype=%d segtype=%d\n", passtype, seg->type); return -1; } } if (seg->type == JPC_SEG_MQ) { /* Note: dont destroy mq decoder because context info will be lost */ } else { assert(seg->type == JPC_SEG_RAW); if (tile->cp->ccps[compno].cblkctx & JPC_COX_PTERM) { fillmask = 0x7f; filldata = 0x2a; } else { fillmask = 0; filldata = 0; } if ((ret = jpc_bitstream_inalign(cblk->nulldec, fillmask, filldata)) < 0) { return -1; } else if (ret > 0) { jas_eprintf("warning: bad termination pattern detected\n"); } jpc_bitstream_close(cblk->nulldec); cblk->nulldec = 0; } cblk->curseg = seg->next; jpc_seglist_remove(&cblk->segs, seg); jpc_seg_destroy(seg); seg = cblk->curseg; } assert(dopartial ? (!cblk->curseg) : 1); premature_exit: return 0; }
// 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, Error; 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; } // JasPer likes to buffer a lot, so it may try buffering past the end // of the file. iread naturally sets IL_FILE_READ_ERROR if it tries // reading past the end of the file, but this actually is not an error. Error = ilGetError(); // Put the error back if it is not IL_FILE_READ_ERROR. if (Error != IL_FILE_READ_ERROR) ilSetError(Error); // 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)) { //@TODO: Can we do alpha data? jas_image_cmpttype always returns 0 for this case. case 1: // Assuming this is luminance data. if (Image == NULL) { ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 1, IL_LUMINANCE, 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, 1, IL_LUMINANCE, IL_UNSIGNED_BYTE, NULL); TempImage = Image; } break; case 2: // Assuming this is luminance-alpha data. if (Image == NULL) { ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 2, IL_LUMINANCE_ALPHA, 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, 2, IL_LUMINANCE_ALPHA, IL_UNSIGNED_BYTE, NULL); TempImage = Image; } break; 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); return ilFixImage(); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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); }
jas_image_t *makediffimage(jas_matrix_t *origdata, jas_matrix_t *recondata) { jas_image_t *diffimage; jas_matrix_t *diffdata[3]; int width; int height; int i; int j; int k; jas_image_cmptparm_t compparms[3]; jas_seqent_t a; jas_seqent_t b; width = jas_matrix_numcols(origdata); height = jas_matrix_numrows(origdata); for (i = 0; i < 3; ++i) { compparms[i].tlx = 0; compparms[i].tly = 0; compparms[i].hstep = 1; compparms[i].vstep = 1; compparms[i].width = width; compparms[i].height = height; compparms[i].prec = 8; compparms[i].sgnd = jas_false; } if (!(diffimage = jas_image_create(3, compparms, JAS_CLRSPC_SRGB))) { abort(); } for (i = 0; i < 3; ++i) { if (!(diffdata[i] = jas_matrix_create(height, width))) { jas_eprintf("internal error\n"); return 0; } } for (j = 0; j < height; ++j) { for (k = 0; k < width; ++k) { a = jas_matrix_get(origdata, j, k); b = jas_matrix_get(recondata, j, k); if (a > b) { jas_matrix_set(diffdata[0], j, k, 255); jas_matrix_set(diffdata[1], j, k, 0); jas_matrix_set(diffdata[2], j, k, 0); } else if (a < b) { jas_matrix_set(diffdata[0], j, k, 0); jas_matrix_set(diffdata[1], j, k, 255); jas_matrix_set(diffdata[2], j, k, 0); } else { jas_matrix_set(diffdata[0], j, k, a); jas_matrix_set(diffdata[1], j, k, a); jas_matrix_set(diffdata[2], j, k, a); } } } for (i = 0; i < 3; ++i) { if (jas_image_writecmpt(diffimage, i, 0, 0, width, height, diffdata[i])) { return 0; } } return diffimage; }
int jpg_encode(jas_image_t *image, jas_stream_t *out, char *optstr) { JDIMENSION numscanlines; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; jas_image_coord_t width; jas_image_coord_t height; jpg_src_t src_mgr_buf; jpg_src_t *src_mgr = &src_mgr_buf; FILE *output_file; int cmptno; jpg_enc_t encbuf; jpg_enc_t *enc = &encbuf; jpg_encopts_t encopts; output_file = 0; if (jpg_parseencopts(optstr, &encopts)) goto error; switch (jas_clrspc_fam(jas_image_clrspc(image))) { case JAS_CLRSPC_FAM_RGB: if (jas_image_clrspc(image) != JAS_CLRSPC_SRGB) jas_eprintf("warning: inaccurate color\n"); enc->numcmpts = 3; if ((enc->cmpts[0] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R))) < 0 || (enc->cmpts[1] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G))) < 0 || (enc->cmpts[2] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))) < 0) { jas_eprintf("error: missing color component\n"); goto error; } break; case JAS_CLRSPC_FAM_YCBCR: if (jas_image_clrspc(image) != JAS_CLRSPC_SYCBCR) jas_eprintf("warning: inaccurate color\n"); enc->numcmpts = 3; if ((enc->cmpts[0] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y))) < 0 || (enc->cmpts[1] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB))) < 0 || (enc->cmpts[2] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))) < 0) { jas_eprintf("error: missing color component\n"); goto error; } break; case JAS_CLRSPC_FAM_GRAY: if (jas_image_clrspc(image) != JAS_CLRSPC_SGRAY) jas_eprintf("warning: inaccurate color\n"); enc->numcmpts = 1; if ((enc->cmpts[0] = jas_image_getcmptbytype(image, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) { jas_eprintf("error: missing color component\n"); goto error; } break; default: jas_eprintf("error: JPG format does not support color space\n"); goto error; break; } width = jas_image_width(image); height = jas_image_height(image); for (cmptno = 0; cmptno < enc->numcmpts; ++cmptno) { if (jas_image_cmptwidth(image, enc->cmpts[cmptno]) != width || jas_image_cmptheight(image, enc->cmpts[cmptno]) != height || jas_image_cmpttlx(image, enc->cmpts[cmptno]) != 0 || jas_image_cmpttly(image, enc->cmpts[cmptno]) != 0 || jas_image_cmpthstep(image, enc->cmpts[cmptno]) != 1 || jas_image_cmptvstep(image, enc->cmpts[cmptno]) != 1 || jas_image_cmptprec(image, enc->cmpts[cmptno]) != 8 || jas_image_cmptsgnd(image, enc->cmpts[cmptno]) != jas_false) { jas_eprintf("error: The JPG encoder cannot handle an image with this geometry.\n"); goto error; } } if (!(output_file = tmpfile())) { goto error; } /* Create a JPEG compression object. */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); /* Specify data destination for compression */ jpeg_stdio_dest(&cinfo, output_file); cinfo.in_color_space = tojpgcs(jas_image_clrspc(image)); cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = enc->numcmpts; jpeg_set_defaults(&cinfo); src_mgr->error = 0; src_mgr->image = image; src_mgr->data = jas_matrix_create(1, width); src_mgr->buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, (JDIMENSION) width * cinfo.input_components, (JDIMENSION) 1); src_mgr->buffer_height = 1; src_mgr->enc = enc; /* Read the input file header to obtain file size & colorspace. */ jpg_start_input(&cinfo, src_mgr); if (encopts.qual >= 0) { jpeg_set_quality(&cinfo, encopts.qual, jas_true); } /* Now that we know input colorspace, fix colorspace-dependent defaults */ jpeg_default_colorspace(&cinfo); /* Start compressor */ jpeg_start_compress(&cinfo, jas_true ); /* Process data */ while (cinfo.next_scanline < cinfo.image_height) { if ((numscanlines = jpg_get_pixel_rows(&cinfo, src_mgr)) <= 0) { break; } jpeg_write_scanlines(&cinfo, src_mgr->buffer, numscanlines); } /* Finish compression and release memory */ jpg_finish_input(&cinfo, src_mgr); jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); rewind(output_file); jpg_copyfiletostream(out, output_file); fclose(output_file); output_file = 0; return 0; error: if (output_file) { fclose(output_file); } return -1; }
bool JP2KLoader::save(const QString& filePath, DImgLoaderObserver* observer) { FILE* file = fopen(QFile::encodeName(filePath), "wb"); if (!file) { return false; } fclose(file); // ------------------------------------------------------------------- // Initialize JPEG 2000 API. register long i, x, y; unsigned long number_components; jas_image_t* jp2_image = 0; jas_stream_t* jp2_stream = 0; jas_matrix_t* pixels[4]; jas_image_cmptparm_t component_info[4]; int init = jas_init(); if (init != 0) { kDebug() << "Unable to init JPEG2000 decoder"; return false; } jp2_stream = jas_stream_fopen(QFile::encodeName(filePath), "wb"); if (jp2_stream == 0) { kDebug() << "Unable to open JPEG2000 stream"; return false; } number_components = imageHasAlpha() ? 4 : 3; for (i = 0 ; i < (long)number_components ; ++i) { component_info[i].tlx = 0; component_info[i].tly = 0; component_info[i].hstep = 1; component_info[i].vstep = 1; component_info[i].width = imageWidth(); component_info[i].height = imageHeight(); component_info[i].prec = imageBitsDepth(); component_info[i].sgnd = false; } jp2_image = jas_image_create(number_components, component_info, JAS_CLRSPC_UNKNOWN); if (jp2_image == 0) { jas_stream_close(jp2_stream); kDebug() << "Unable to create JPEG2000 image"; return false; } if (observer) { observer->progressInfo(m_image, 0.1F); } // ------------------------------------------------------------------- // Check color space. if (number_components >= 3 ) // RGB & RGBA { // Alpha Channel if (number_components == 4 ) { jas_image_setcmpttype(jp2_image, 3, JAS_IMAGE_CT_OPACITY); } jas_image_setclrspc(jp2_image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(jp2_image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(jp2_image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(jp2_image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } // ------------------------------------------------------------------- // Set ICC color profile. // FIXME : doesn't work yet! jas_cmprof_t* cm_profile = 0; jas_iccprof_t* icc_profile = 0; QByteArray profile_rawdata = m_image->getIccProfile().data(); icc_profile = jas_iccprof_createfrombuf((uchar*)profile_rawdata.data(), profile_rawdata.size()); if (icc_profile != 0) { cm_profile = jas_cmprof_createfromiccprof(icc_profile); if (cm_profile != 0) { jas_image_setcmprof(jp2_image, cm_profile); } } // ------------------------------------------------------------------- // Convert to JPEG 2000 pixels. for (i = 0 ; i < (long)number_components ; ++i) { pixels[i] = jas_matrix_create(1, (unsigned int)imageWidth()); if (pixels[i] == 0) { for (x = 0 ; x < i ; ++x) { jas_matrix_destroy(pixels[x]); } jas_image_destroy(jp2_image); kDebug() << "Error encoding JPEG2000 image data : Memory Allocation Failed"; return false; } } unsigned char* data = imageData(); unsigned char* pixel; unsigned short r, g, b, a=0; uint checkpoint = 0; for (y = 0 ; y < (long)imageHeight() ; ++y) { if (observer && y == (long)checkpoint) { checkpoint += granularity(observer, imageHeight(), 0.8F); if (!observer->continueQuery(m_image)) { jas_image_destroy(jp2_image); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); return false; } observer->progressInfo(m_image, 0.1 + (0.8 * ( ((float)y)/((float)imageHeight()) ))); } for (x = 0 ; x < (long)imageWidth() ; ++x) { pixel = &data[((y * imageWidth()) + x) * imageBytesDepth()]; if ( imageSixteenBit() ) // 16 bits image. { b = (unsigned short)(pixel[0]+256*pixel[1]); g = (unsigned short)(pixel[2]+256*pixel[3]); r = (unsigned short)(pixel[4]+256*pixel[5]); if (imageHasAlpha()) { a = (unsigned short)(pixel[6]+256*pixel[7]); } } else // 8 bits image. { b = (unsigned short)pixel[0]; g = (unsigned short)pixel[1]; r = (unsigned short)pixel[2]; if (imageHasAlpha()) { a = (unsigned short)(pixel[3]); } } jas_matrix_setv(pixels[0], x, r); jas_matrix_setv(pixels[1], x, g); jas_matrix_setv(pixels[2], x, b); if (number_components > 3) { jas_matrix_setv(pixels[3], x, a); } } for (i = 0 ; i < (long)number_components ; ++i) { int ret = jas_image_writecmpt(jp2_image, (short) i, 0, (unsigned int)y, (unsigned int)imageWidth(), 1, pixels[i]); if (ret != 0) { kDebug() << "Error encoding JPEG2000 image data"; jas_image_destroy(jp2_image); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); return false; } } } QVariant qualityAttr = imageGetAttribute("quality"); int quality = qualityAttr.isValid() ? qualityAttr.toInt() : 90; if (quality < 0) { quality = 90; } if (quality > 100) { quality = 100; } QString rate; QTextStream ts( &rate, QIODevice::WriteOnly ); // NOTE: to have a lossless compression use quality=100. // jp2_encode()::optstr: // - rate=#B => the resulting file size is about # bytes // - rate=0.0 .. 1.0 => the resulting file size is about the factor times // the uncompressed size ts << "rate=" << ( quality / 100.0F ); kDebug() << "JPEG2000 quality: " << quality; kDebug() << "JPEG2000 " << rate; int ret = jp2_encode(jp2_image, jp2_stream, rate.toUtf8().data()); if (ret != 0) { kDebug() << "Unable to encode JPEG2000 image"; jas_image_destroy(jp2_image); jas_stream_close(jp2_stream); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); return false; } if (observer) { observer->progressInfo(m_image, 1.0); } imageSetAttribute("savedformat", "JP2K"); saveMetadata(filePath); jas_image_destroy(jp2_image); jas_stream_close(jp2_stream); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); return true; }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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: % % MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) { char *key, magick[MaxTextExtent], *options; const char *option; long format, y; jas_image_cmptparm_t component_info[4]; jas_image_t *jp2_image; jas_matrix_t *pixels[4]; jas_stream_t *jp2_stream; MagickBooleanType status; QuantumAny range; register const PixelPacket *p; register long i, x; unsigned short *map; unsigned long number_components; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Intialize JPEG 2000 API. */ if (image->colorspace != RGBColorspace) (void) TransformImageColorspace(image,RGBColorspace); jp2_stream=JP2StreamManager(image); if (jp2_stream == (jas_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToManageJP2Stream"); number_components=image->matte ? 4UL : 3UL; if ((image_info->type != TrueColorType) && IsGrayImage(image,&image->exception)) number_components=1; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) ResetMagickMemory(&component_info,0,sizeof(component_info)); for (i=0; i < (long) number_components; i++) { component_info[i].tlx=0; component_info[i].tly=0; component_info[i].hstep=1; component_info[i].vstep=1; component_info[i].width=(unsigned int) image->columns; component_info[i].height=(unsigned int) image->rows; component_info[i].prec=(int) MagickMax(MagickMin(image->depth,16),2); component_info[i].sgnd=MagickFalse; } jp2_image=jas_image_create((int) number_components,component_info, JAS_CLRSPC_UNKNOWN); if (jp2_image == (jas_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToCreateImage"); if (number_components == 1) { /* sRGB Grayscale. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_SGRAY); jas_image_setcmpttype(jp2_image,0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } else { /* sRGB. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_SRGB); jas_image_setcmpttype(jp2_image,0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(jp2_image,1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(jp2_image,2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); if (number_components == 4) jas_image_setcmpttype(jp2_image,3,JAS_IMAGE_CT_OPACITY); } /* Convert to JPEG 2000 pixels. */ for (i=0; i < (long) number_components; i++) { pixels[i]=jas_matrix_create(1,(int) image->columns); if (pixels[i] == (jas_matrix_t *) NULL) { for (x=0; x < i; x++) jas_matrix_destroy(pixels[x]); jas_image_destroy(jp2_image); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } range=GetQuantumRange((unsigned long) component_info[0].prec); map=(unsigned short *) AcquireQuantumMemory(MaxMap+1,sizeof(*map)); for (i=0; i <= (long) MaxMap; i++) map[i]=(unsigned short) ScaleQuantumToMap((Quantum) ScaleQuantumToAny((Quantum) i,range)); if (map == (unsigned short *) NULL) { for (i=0; i < (long) number_components; i++) jas_matrix_destroy(pixels[i]); jas_image_destroy(jp2_image); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (long) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (long) image->columns; x++) { if (number_components == 1) jas_matrix_setv(pixels[0],x,map[ScaleQuantumToMap( PixelIntensityToQuantum(p))]); else { jas_matrix_setv(pixels[0],x,map[ScaleQuantumToMap(p->red)]); jas_matrix_setv(pixels[1],x,map[ScaleQuantumToMap(p->green)]); jas_matrix_setv(pixels[2],x,map[ScaleQuantumToMap(p->blue)]); if (number_components > 3) jas_matrix_setv(pixels[3],x,map[ScaleQuantumToMap((Quantum) (QuantumRange-p->opacity))]); } p++; } for (i=0; i < (long) number_components; i++) (void) jas_image_writecmpt(jp2_image,(short) i,0,(unsigned int) y, (unsigned int) image->columns,1,pixels[i]); status=SetImageProgress(image,SaveImageTag,y,image->rows); if (status == MagickFalse) break; } map=(unsigned short *) RelinquishMagickMemory(map); (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); LocaleLower(magick); format=jas_image_strtofmt(magick); options=(char *) NULL; ResetImageOptionIterator(image_info); key=GetNextImageOption(image_info); while (key != (char *) NULL) { option=GetImageOption(image_info,key); if (option != (const char *) NULL) { if (LocaleNCompare(key,"jp2:",4) == 0) { (void) ConcatenateString(&options,key+4); if (*option != '\0') { (void) ConcatenateString(&options,"="); (void) ConcatenateString(&options,option); } (void) ConcatenateString(&options," "); } } key=GetNextImageOption(image_info); } option=GetImageOption(image_info,"jp2:rate"); if ((option == (const char *) NULL) && (image_info->compression != LosslessJPEGCompression) && (image->quality != UndefinedCompressionQuality) && ((double) image->quality <= 99.5) && ((image->rows*image->columns) > 2500)) { char option[MaxTextExtent]; double alpha, header_size, number_pixels, rate, target_size; alpha=115.0-image->quality; rate=100.0/(alpha*alpha); header_size=550.0; header_size+=(number_components-1)*142; number_pixels=(double) image->rows*image->columns*number_components* (GetImageQuantumDepth(image,MagickTrue)/8); target_size=(number_pixels*rate)+header_size; rate=target_size/number_pixels; (void) FormatMagickString(option,MaxTextExtent,"rate=%g",rate); (void) ConcatenateString(&options,option); } status=jas_image_encode(jp2_image,jp2_stream,format,options) != 0 ? MagickTrue : MagickFalse; (void) jas_stream_close(jp2_stream); for (i=0; i < (long) number_components; i++) jas_matrix_destroy(pixels[i]); jas_image_destroy(jp2_image); if (status != MagickFalse) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); return(MagickTrue); }
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 * *$$$*/ { 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]; /* printf(" SAGOUT DECODE:\n"); printf(" tlx %d \n",image->tlx_); printf(" tly %d \n",image->tly_); printf(" brx %d \n",image->brx_); printf(" bry %d \n",image->bry_); printf(" numcmpts %d \n",image->numcmpts_); printf(" maxcmpts %d \n",image->maxcmpts_); #ifdef JAS_1_500_4 printf(" colormodel %d \n",image->colormodel_); #endif #ifdef JAS_1_700_2 printf(" colorspace %d \n",image->clrspc_); #endif printf(" inmem %d \n",image->inmem_); printf(" COMPONENT:\n"); printf(" tlx %d \n",pcmpt->tlx_); printf(" tly %d \n",pcmpt->tly_); printf(" hstep %d \n",pcmpt->hstep_); printf(" vstep %d \n",pcmpt->vstep_); printf(" width %d \n",pcmpt->width_); printf(" height %d \n",pcmpt->height_); printf(" prec %d \n",pcmpt->prec_); printf(" sgnd %d \n",pcmpt->sgnd_); printf(" cps %d \n",pcmpt->cps_); #ifdef JAS_1_700_2 printf(" type %d \n",pcmpt->type_); #endif */ /* 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; }
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; jas_cmprof_t *cm_profile; jas_iccprof_t *icc_profile; jas_image_t *jp2_image; jas_matrix_t *pixels[4]; jas_stream_t *jp2_stream; long components[4], y; MagickBooleanType status; QuantumAny pixel, *map[4], range; register long i, x; register PixelPacket *q; unsigned long maximum_component_depth, number_components, x_step[4], y_step[4]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize JPEG 2000 API. */ jp2_stream=JP2StreamManager(image); if (jp2_stream == (jas_stream_t *) NULL) ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); 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"); } switch (jas_clrspc_fam(jas_image_clrspc(jp2_image))) { case JAS_CLRSPC_FAM_RGB: { components[0]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_RGB_R); components[1]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_RGB_G); components[2]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_RGB_B); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,"MissingImageChannel"); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,3); if (components[3] > 0) { image->matte=MagickTrue; number_components++; } break; } case JAS_CLRSPC_FAM_GRAY: { components[0]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_GRAY_Y); if (components[0] < 0) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CorruptImageError,"MissingImageChannel"); } 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"); } number_components=3; components[3]=jas_image_getcmptbytype(jp2_image,JAS_IMAGE_CT_UNKNOWN); if (components[3] > 0) { image->matte=MagickTrue; number_components++; } image->colorspace=YCbCrColorspace; break; } default: { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CoderError,"ColorspaceModelIsNotSupported"); } } image->columns=jas_image_width(jp2_image); image->rows=jas_image_height(jp2_image); image->compression=JPEG2000Compression; for (i=0; i < (long) number_components; i++) { unsigned long height, width; width=(unsigned long) (jas_image_cmptwidth(jp2_image,components[i])* jas_image_cmpthstep(jp2_image,components[i])); height=(unsigned long) (jas_image_cmptheight(jp2_image,components[i])* jas_image_cmptvstep(jp2_image,components[i])); x_step[i]=(unsigned int) jas_image_cmpthstep(jp2_image,components[i]); y_step[i]=(unsigned int) jas_image_cmptvstep(jp2_image,components[i]); if ((width != image->columns) || (height != image->rows) || (jas_image_cmpttlx(jp2_image,components[i]) != 0) || (jas_image_cmpttly(jp2_image,components[i]) != 0) || (x_step[i] != 1) || (y_step[i] != 1) || (jas_image_cmptsgnd(jp2_image,components[i]) != MagickFalse)) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported"); } } /* Convert JPEG 2000 pixels. */ image->matte=number_components > 3 ? MagickTrue : MagickFalse; maximum_component_depth=0; for (i=0; i < (long) number_components; i++) { maximum_component_depth=(unsigned int) MagickMax((size_t) jas_image_cmptprec(jp2_image,components[i]),(size_t) maximum_component_depth); pixels[i]=jas_matrix_create(1,(int) (image->columns/x_step[i])); if (pixels[i] == (jas_matrix_t *) NULL) { for (--i; i >= 0; i--) jas_matrix_destroy(pixels[i]); jas_image_destroy(jp2_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } image->depth=maximum_component_depth; if (image_info->ping != MagickFalse) { (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); return(GetFirstImageInList(image)); } for (i=0; i < (long) number_components; i++) { long j; map[i]=(QuantumAny *) AcquireQuantumMemory(MaxMap+1,sizeof(**map)); if (map[i] == (QuantumAny *) NULL) { for (--i; i >= 0; i--) map[i]=(QuantumAny *) RelinquishMagickMemory(map[i]); for (i=0; i < (long) number_components; i++) jas_matrix_destroy(pixels[i]); jas_image_destroy(jp2_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } range=GetQuantumRange((unsigned long) jas_image_cmptprec(jp2_image, components[i])); for (j=0; j <= (long) MaxMap; j++) map[i][j]=ScaleQuantumToMap(ScaleAnyToQuantum((QuantumAny) j,range)); } for (y=0; y < (long) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (i=0; i < (long) number_components; i++) (void) jas_image_readcmpt(jp2_image,(short) components[i],0, ((unsigned int) y)/y_step[i],((unsigned int) image->columns)/x_step[i], 1,pixels[i]); switch (number_components) { case 1: { /* Grayscale. */ for (x=0; x < (long) image->columns; x++) { pixel=(QuantumAny) jas_matrix_getv(pixels[0],x/x_step[0]); q->red=(Quantum) map[0][pixel]; q->green=q->red; q->blue=q->red; q++; } break; } case 3: { /* RGB. */ for (x=0; x < (long) image->columns; x++) { pixel=(QuantumAny) jas_matrix_getv(pixels[0],x/x_step[0]); q->red=(Quantum) map[0][pixel]; pixel=(QuantumAny) jas_matrix_getv(pixels[1],x/x_step[1]); q->green=(Quantum) map[1][pixel]; pixel=(QuantumAny) jas_matrix_getv(pixels[2],x/x_step[2]); q->blue=(Quantum) map[2][pixel]; q++; } break; } case 4: { /* RGBA. */ for (x=0; x < (long) image->columns; x++) { pixel=(QuantumAny) jas_matrix_getv(pixels[0],x/x_step[0]); q->red=(Quantum) map[0][pixel]; pixel=(QuantumAny) jas_matrix_getv(pixels[1],x/x_step[1]); q->green=(Quantum) map[1][pixel]; pixel=(QuantumAny) jas_matrix_getv(pixels[2],x/x_step[2]); q->blue=(Quantum) map[2][pixel]; pixel=(QuantumAny) jas_matrix_getv(pixels[3],x/x_step[3]); q->opacity=(Quantum) (QuantumRange-map[3][pixel]); q++; } break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,y,image->rows); if (status == MagickFalse) break; } for (i=0; i < (long) number_components; i++) map[i]=(QuantumAny *) RelinquishMagickMemory(map[i]); cm_profile=jas_image_cmprof(jp2_image); icc_profile=(jas_iccprof_t *) NULL; if (cm_profile != (jas_cmprof_t *) NULL) icc_profile=jas_iccprof_createfromcmprof(cm_profile); 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)) { StringInfo *icc_profile, *profile; jas_stream_memobj_t *blob; /* Extract the icc profile, handle errors without much noise. */ blob=(jas_stream_memobj_t *) icc_stream->obj_; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %lu bytes",(unsigned long) blob->len_); profile=AcquireStringInfo(blob->len_); SetStringInfoDatum(profile,blob->buf_); icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile == (StringInfo *) NULL) (void) SetImageProfile(image,"icc",profile); else (void) ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); (void) jas_stream_close(icc_stream); } } (void) jas_stream_close(jp2_stream); jas_image_destroy(jp2_image); for (i=0; i < (long) number_components; i++) jas_matrix_destroy(pixels[i]); return(GetFirstImageInList(image)); }
static gboolean process (GeglOperation *operation, GeglBuffer *output, const GeglRectangle *result) { GeglChantO *o = GEGL_CHANT_PROPERTIES (operation); GeglRectangle rect = {0,0,0,0}; jas_image_t *image; gint width, height, depth; gsize bpc; guchar *data = NULL; gboolean ret; int components[3]; jas_matrix_t *matrices[3] = {NULL, NULL, NULL}; gint i; gint row; gboolean b; gushort *ptr_s; guchar *ptr_b; image = NULL; width = height = depth = 0; if (!query_jp2 (o->path, &width, &height, &depth, &image)) return FALSE; rect.height = height; rect.width = width; switch (depth) { case 8: bpc = sizeof (guchar); break; case 16: bpc = sizeof (gushort); break; default: g_warning ("%s: Programmer stupidity error", G_STRLOC); return FALSE; } data = (guchar *) g_malloc (width * height * 3 * bpc); ptr_s = (gushort *) data; ptr_b = data; switch (depth) { case 16: gegl_buffer_get (output, 1.0, &rect, babl_format ("R'G'B' u16"), data, GEGL_AUTO_ROWSTRIDE); break; case 8: default: gegl_buffer_get (output, 1.0, &rect, babl_format ("R'G'B' u8"), data, GEGL_AUTO_ROWSTRIDE); } ret = FALSE; b = FALSE; do { components[0] = jas_image_getcmptbytype (image, JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R)); components[1] = jas_image_getcmptbytype (image, JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G)); components[2] = jas_image_getcmptbytype (image, JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B)); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { g_warning (_("One or more of R, G, B components are missing " "from '%s'"), o->path); break; } if (jas_image_cmptsgnd (image, components[0]) || jas_image_cmptsgnd (image, components[1]) || jas_image_cmptsgnd (image, components[2])) { g_warning (_("One or more of R, G, B components have signed " "data in '%s'"), o->path); break; } for (i = 0; i < 3; i++) matrices[i] = jas_matrix_create(1, width); for (row = 0; row < height; row++) { gint plane, col; jas_seqent_t *jrow[3] = {NULL, NULL, NULL}; for (plane = 0; plane < 3; plane++) { int r = jas_image_readcmpt (image, components[plane], 0, row, width, 1, matrices[plane]); if (r) { g_warning (_("Error reading row %d component %d from '%s'"), row, plane, o->path); b = TRUE; break; } } if (b) break; for (plane = 0; plane < 3; plane++) jrow[plane] = jas_matrix_getref (matrices[plane], 0, 0); for (col = 0; col < width; col++) { switch (depth) { case 16: *ptr_s++ = (gushort) jrow[0][col]; *ptr_s++ = (gushort) jrow[1][col]; *ptr_s++ = (gushort) jrow[2][col]; break; case 8: default: *ptr_b++ = (guchar) jrow[0][col]; *ptr_b++ = (guchar) jrow[1][col]; *ptr_b++ = (guchar) jrow[2][col]; } } } if (b) break; switch (depth) { case 16: gegl_buffer_set (output, &rect, babl_format ("R'G'B' u16"), data, GEGL_AUTO_ROWSTRIDE); break; case 8: default: gegl_buffer_set (output, &rect, babl_format ("R'G'B' u8"), data, GEGL_AUTO_ROWSTRIDE); } ret = TRUE; } while (FALSE); /* structured goto */ for (i = 0; i < 3; i++) if (matrices[i]) jas_matrix_destroy (matrices[i]); if (data) g_free (data); if (image) jas_image_destroy (image); return ret; }
bool JP2KLoader::load(const QString& filePath, DImgLoaderObserver* observer) { readMetadata(filePath, DImg::JPEG); FILE* file = fopen(QFile::encodeName(filePath), "rb"); if (!file) { loadingFailed(); return false; } unsigned char header[9]; if (fread(&header, 9, 1, file) != 1) { fclose(file); loadingFailed(); return false; } unsigned char jp2ID[5] = { 0x6A, 0x50, 0x20, 0x20, 0x0D, }; unsigned char jpcID[2] = { 0xFF, 0x4F }; if (memcmp(&header[4], &jp2ID, 5) != 0 && memcmp(&header, &jpcID, 2) != 0) { // not a jpeg2000 file fclose(file); loadingFailed(); return false; } fclose(file); imageSetAttribute("format", "JP2K"); if (!(m_loadFlags & LoadImageData) && !(m_loadFlags & LoadICCData)) { // libjasper will load the full image in memory already when calling jas_image_decode. // This is bad when scanning. See bugs 215458 and 195583. //FIXME: Use Exiv2 or OpenJPEG to extract this info DMetadata metadata(filePath); QSize size = metadata.getImageDimensions(); if (size.isValid()) { imageWidth() = size.width(); imageHeight() = size.height(); } return true; } // ------------------------------------------------------------------- // Initialize JPEG 2000 API. register long i, x, y; int components[4]; unsigned int maximum_component_depth, scale[4], x_step[4], y_step[4]; unsigned long number_components; jas_image_t* jp2_image = 0; jas_stream_t* jp2_stream = 0; jas_matrix_t* pixels[4]; int init = jas_init(); if (init != 0) { kDebug() << "Unable to init JPEG2000 decoder"; loadingFailed(); return false; } jp2_stream = jas_stream_fopen(QFile::encodeName(filePath), "rb"); if (jp2_stream == 0) { kDebug() << "Unable to open JPEG2000 stream"; loadingFailed(); return false; } jp2_image = jas_image_decode(jp2_stream, -1, 0); if (jp2_image == 0) { jas_stream_close(jp2_stream); kDebug() << "Unable to decode JPEG2000 image"; loadingFailed(); return false; } jas_stream_close(jp2_stream); // some pseudo-progress if (observer) { observer->progressInfo(m_image, 0.1F); } // ------------------------------------------------------------------- // Check color space. int colorModel; switch (jas_clrspc_fam(jas_image_clrspc(jp2_image))) { case JAS_CLRSPC_FAM_RGB: { components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_R); components[1] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_G); components[2] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_B); if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0)) { jas_image_destroy(jp2_image); kDebug() << "Error parsing JPEG2000 image : Missing Image Channel"; loadingFailed(); return false; } number_components = 3; components[3] = jas_image_getcmptbytype(jp2_image, 3); if (components[3] > 0) { m_hasAlpha = true; ++number_components; } colorModel = DImg::RGB; break; } case JAS_CLRSPC_FAM_GRAY: { components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_GRAY_Y); if (components[0] < 0) { jas_image_destroy(jp2_image); kDebug() << "Error parsing JP2000 image : Missing Image Channel"; loadingFailed(); return false; } number_components = 1; colorModel = DImg::GRAYSCALE; 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)) { jas_image_destroy(jp2_image); kDebug() << "Error parsing JP2000 image : Missing Image Channel"; loadingFailed(); return false; } number_components = 3; components[3] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_UNKNOWN); if (components[3] > 0) { m_hasAlpha = true; ++number_components; } // FIXME : image->colorspace=YCbCrColorspace; colorModel = DImg::YCBCR; break; } default: { jas_image_destroy(jp2_image); kDebug() << "Error parsing JP2000 image : Colorspace Model Is Not Supported"; loadingFailed(); return false; } } // ------------------------------------------------------------------- // Check image geometry. imageWidth() = jas_image_width(jp2_image); imageHeight() = jas_image_height(jp2_image); for (i = 0; i < (long)number_components; ++i) { if ((((jas_image_cmptwidth(jp2_image, components[i])* jas_image_cmpthstep(jp2_image, components[i])) != (long)imageWidth())) || (((jas_image_cmptheight(jp2_image, components[i])* jas_image_cmptvstep(jp2_image, components[i])) != (long)imageHeight())) || (jas_image_cmpttlx(jp2_image, components[i]) != 0) || (jas_image_cmpttly(jp2_image, components[i]) != 0) || (jas_image_cmptsgnd(jp2_image, components[i]) != false)) { jas_image_destroy(jp2_image); kDebug() << "Error parsing JPEG2000 image : Irregular Channel Geometry Not Supported"; loadingFailed(); return false; } x_step[i] = jas_image_cmpthstep(jp2_image, components[i]); y_step[i] = jas_image_cmptvstep(jp2_image, components[i]); } // ------------------------------------------------------------------- // Get image format. m_hasAlpha = number_components > 3; maximum_component_depth = 0; for (i = 0; i < (long)number_components; ++i) { maximum_component_depth = qMax((long)jas_image_cmptprec(jp2_image,components[i]), (long)maximum_component_depth); pixels[i] = jas_matrix_create(1, ((unsigned int)imageWidth())/x_step[i]); if (!pixels[i]) { jas_image_destroy(jp2_image); kDebug() << "Error decoding JPEG2000 image data : Memory Allocation Failed"; loadingFailed(); return false; } } if (maximum_component_depth > 8) { m_sixteenBit = true; } for (i = 0 ; i < (long)number_components ; ++i) { scale[i] = 1; int prec = jas_image_cmptprec(jp2_image, components[i]); if (m_sixteenBit && prec < 16) { scale[i] = (1 << (16 - jas_image_cmptprec(jp2_image, components[i]))); } } // ------------------------------------------------------------------- // Get image data. uchar* data = 0; if (m_loadFlags & LoadImageData) { if (m_sixteenBit) // 16 bits image. { data = new_failureTolerant(imageWidth()*imageHeight()*8); } else { data = new_failureTolerant(imageWidth()*imageHeight()*4); } if (!data) { kDebug() << "Error decoding JPEG2000 image data : Memory Allocation Failed"; jas_image_destroy(jp2_image); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); loadingFailed(); return false; } uint checkPoint = 0; uchar* dst = data; unsigned short* dst16 = (unsigned short*)data; for (y = 0 ; y < (long)imageHeight() ; ++y) { for (i = 0 ; i < (long)number_components; ++i) { int ret = jas_image_readcmpt(jp2_image, (short)components[i], 0, ((unsigned int) y) / y_step[i], ((unsigned int) imageWidth()) / x_step[i], 1, pixels[i]); if (ret != 0) { kDebug() << "Error decoding JPEG2000 image data"; delete [] data; jas_image_destroy(jp2_image); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); loadingFailed(); return false; } } switch (number_components) { case 1: // Grayscale. { for (x = 0 ; x < (long)imageWidth() ; ++x) { dst[0] = (uchar)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0])); dst[1] = dst[0]; dst[2] = dst[0]; dst[3] = 0xFF; dst += 4; } break; } case 3: // RGB. { if (!m_sixteenBit) // 8 bits image. { for (x = 0 ; x < (long)imageWidth() ; ++x) { // Blue dst[0] = (uchar)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2])); // Green dst[1] = (uchar)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1])); // Red dst[2] = (uchar)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0])); // Alpha dst[3] = 0xFF; dst += 4; } } else // 16 bits image. { for (x = 0 ; x < (long)imageWidth() ; ++x) { // Blue dst16[0] = (unsigned short)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2])); // Green dst16[1] = (unsigned short)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1])); // Red dst16[2] = (unsigned short)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0])); // Alpha dst16[3] = 0xFFFF; dst16 += 4; } } break; } case 4: // RGBA. { if (!m_sixteenBit) // 8 bits image. { for (x = 0 ; x < (long)imageWidth() ; ++x) { // Blue dst[0] = (uchar)(scale[2] * jas_matrix_getv(pixels[2], x/x_step[2])); // Green dst[1] = (uchar)(scale[1] * jas_matrix_getv(pixels[1], x/x_step[1])); // Red dst[2] = (uchar)(scale[0] * jas_matrix_getv(pixels[0], x/x_step[0])); // Alpha dst[3] = (uchar)(scale[3] * jas_matrix_getv(pixels[3], x/x_step[3])); dst += 4; } } else // 16 bits image. { for (x = 0 ; x < (long)imageWidth() ; ++x) { // Blue dst16[0] = (unsigned short)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2])); // Green dst16[1] = (unsigned short)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1])); // Red dst16[2] = (unsigned short)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0])); // Alpha dst16[3] = (unsigned short)(scale[3]*jas_matrix_getv(pixels[3], x/x_step[3])); dst16 += 4; } } break; } } // use 0-10% and 90-100% for pseudo-progress if (observer && y >= (long)checkPoint) { checkPoint += granularity(observer, y, 0.8F); if (!observer->continueQuery(m_image)) { delete [] data; jas_image_destroy(jp2_image); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); loadingFailed(); return false; } observer->progressInfo(m_image, 0.1 + (0.8 * ( ((float)y)/((float)imageHeight()) ))); } } } // ------------------------------------------------------------------- // Get ICC color profile. if (m_loadFlags & LoadICCData) { jas_iccprof_t* icc_profile = 0; jas_stream_t* icc_stream = 0; jas_cmprof_t* cm_profile = 0; cm_profile = jas_image_cmprof(jp2_image); if (cm_profile != 0) { icc_profile = jas_iccprof_createfromcmprof(cm_profile); } if (icc_profile != 0) { icc_stream = jas_stream_memopen(NULL, 0); if (icc_stream != 0) { if (jas_iccprof_save(icc_profile, icc_stream) == 0) { if (jas_stream_flush(icc_stream) == 0) { jas_stream_memobj_t* blob = (jas_stream_memobj_t*) icc_stream->obj_; QByteArray profile_rawdata; profile_rawdata.resize(blob->len_); memcpy(profile_rawdata.data(), blob->buf_, blob->len_); imageSetIccProfile(profile_rawdata); jas_stream_close(icc_stream); } } } } } if (observer) { observer->progressInfo(m_image, 1.0); } imageData() = data; imageSetAttribute("format", "JP2K"); imageSetAttribute("originalColorModel", colorModel); imageSetAttribute("originalBitDepth", maximum_component_depth); imageSetAttribute("originalSize", QSize(imageWidth(), imageHeight())); jas_image_destroy(jp2_image); for (i = 0 ; i < (long)number_components ; ++i) { jas_matrix_destroy(pixels[i]); } jas_cleanup(); return true; }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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: % % MagickBooleanType WriteJP2Image(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char *key, magick[MaxTextExtent], *options; const char *option; jas_image_cmptparm_t component_info[4]; jas_image_t *jp2_image; jas_matrix_t *pixels[4]; jas_stream_t *jp2_stream; MagickBooleanType status; QuantumAny range; register const Quantum *p; register ssize_t i, x; size_t number_components; ssize_t format, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Initialize JPEG 2000 API. */ if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); jp2_stream=JP2StreamManager(image); if (jp2_stream == (jas_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToManageJP2Stream"); number_components=image->alpha_trait ? 4UL : 3UL; if (IsGrayColorspace(image->colorspace) != MagickFalse) number_components=1; if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) ResetMagickMemory(&component_info,0,sizeof(component_info)); for (i=0; i < (ssize_t) number_components; i++) { component_info[i].tlx=0; component_info[i].tly=0; component_info[i].hstep=1; component_info[i].vstep=1; component_info[i].width=(unsigned int) image->columns; component_info[i].height=(unsigned int) image->rows; component_info[i].prec=(int) MagickMax(MagickMin(image->depth,16),2); component_info[i].sgnd=MagickFalse; } jp2_image=jas_image_create((int) number_components,component_info, JAS_CLRSPC_UNKNOWN); if (jp2_image == (jas_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToCreateImage"); switch (image->colorspace) { case RGBColorspace: case sRGBColorspace: { /* RGB colorspace. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_SRGB); jas_image_setcmpttype(jp2_image,0, (jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(jp2_image,1, (jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(jp2_image,2, (jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); if (number_components == 4) jas_image_setcmpttype(jp2_image,3,JAS_IMAGE_CT_OPACITY); break; } case GRAYColorspace: { /* Grayscale colorspace. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_SGRAY); jas_image_setcmpttype(jp2_image,0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); break; } case YCbCrColorspace: { /* YCbCr colorspace. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_SYCBCR); jas_image_setcmpttype(jp2_image,0,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(0)); jas_image_setcmpttype(jp2_image,1,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(1)); jas_image_setcmpttype(jp2_image,2,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(2)); if (number_components == 4) jas_image_setcmpttype(jp2_image,3,JAS_IMAGE_CT_OPACITY); break; } case XYZColorspace: { /* XYZ colorspace. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_CIEXYZ); jas_image_setcmpttype(jp2_image,0,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(0)); jas_image_setcmpttype(jp2_image,1,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(1)); jas_image_setcmpttype(jp2_image,2,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(2)); if (number_components == 4) jas_image_setcmpttype(jp2_image,3,JAS_IMAGE_CT_OPACITY); break; } case LabColorspace: { /* Lab colorspace. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_CIELAB); jas_image_setcmpttype(jp2_image,0,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(0)); jas_image_setcmpttype(jp2_image,1,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(1)); jas_image_setcmpttype(jp2_image,2,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(2)); if (number_components == 4) jas_image_setcmpttype(jp2_image,3,JAS_IMAGE_CT_OPACITY); break; } default: { /* Unknow. */ jas_image_setclrspc(jp2_image,JAS_CLRSPC_UNKNOWN); jas_image_setcmpttype(jp2_image,0,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(0)); jas_image_setcmpttype(jp2_image,1,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(1)); jas_image_setcmpttype(jp2_image,2,(jas_image_cmpttype_t) JAS_IMAGE_CT_COLOR(2)); if (number_components == 4) jas_image_setcmpttype(jp2_image,3,JAS_IMAGE_CT_OPACITY); break; } } /* Convert to JPEG 2000 pixels. */ for (i=0; i < (ssize_t) number_components; i++) { pixels[i]=jas_matrix_create(1,(int) image->columns); if (pixels[i] == (jas_matrix_t *) NULL) { for (x=0; x < i; x++) jas_matrix_destroy(pixels[x]); jas_image_destroy(jp2_image); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } } range=GetQuantumRange((size_t) component_info[0].prec); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (number_components == 1) jas_matrix_setv(pixels[0],x,(jas_seqent_t) ScaleQuantumToAny( GetPixelIntensity(image,p),range)); else { jas_matrix_setv(pixels[0],x,(jas_seqent_t) ScaleQuantumToAny( GetPixelRed(image,p),range)); jas_matrix_setv(pixels[1],x,(jas_seqent_t) ScaleQuantumToAny( GetPixelGreen(image,p),range)); jas_matrix_setv(pixels[2],x,(jas_seqent_t) ScaleQuantumToAny( GetPixelBlue(image,p),range)); if (number_components > 3) jas_matrix_setv(pixels[3],x,(jas_seqent_t) ScaleQuantumToAny( GetPixelAlpha(image,p),range)); } p+=GetPixelChannels(image); } for (i=0; i < (ssize_t) number_components; i++) (void) jas_image_writecmpt(jp2_image,(short) i,0,(unsigned int) y, (unsigned int) image->columns,1,pixels[i]); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) CopyMagickString(magick,image_info->magick,MaxTextExtent); if (LocaleCompare(magick,"J2C") == 0) (void) CopyMagickString(magick,"JPC",MaxTextExtent); LocaleLower(magick); format=jas_image_strtofmt(magick); options=(char *) NULL; ResetImageOptionIterator(image_info); key=GetNextImageOption(image_info); for ( ; key != (char *) NULL; key=GetNextImageOption(image_info)) { option=GetImageOption(image_info,key); if (option == (const char *) NULL) continue; if (LocaleNCompare(key,"jp2:",4) == 0) { (void) ConcatenateString(&options,key+4); if (*option != '\0') { (void) ConcatenateString(&options,"="); (void) ConcatenateString(&options,option); } (void) ConcatenateString(&options," "); } } option=GetImageOption(image_info,"jp2:rate"); if ((option == (const char *) NULL) && (image_info->compression != LosslessJPEGCompression) && (image->quality != UndefinedCompressionQuality) && ((double) image->quality <= 99.5) && ((image->rows*image->columns) > 2500)) { char option[MaxTextExtent]; double alpha, header_size, number_pixels, rate, target_size; alpha=115.0-image->quality; rate=100.0/(alpha*alpha); header_size=550.0; header_size+=(number_components-1)*142; number_pixels=(double) image->rows*image->columns*number_components* (GetImageQuantumDepth(image,MagickTrue)/8); target_size=(number_pixels*rate)+header_size; rate=target_size/number_pixels; (void) FormatLocaleString(option,MaxTextExtent,"rate=%g",rate); (void) ConcatenateString(&options,option); } status=jas_image_encode(jp2_image,jp2_stream,format,options) != 0 ? MagickTrue : MagickFalse; if (options != (char *) NULL) options=DestroyString(options); (void) jas_stream_close(jp2_stream); for (i=0; i < (ssize_t) number_components; i++) jas_matrix_destroy(pixels[i]); jas_image_destroy(jp2_image); if (status != MagickFalse) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); return(MagickTrue); }
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; }
// 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; }
bool CxImageJAS::Decode(CxFile *hFile, uint32_t imagetype) { if (hFile == NULL) return false; jas_image_t *image=0; jas_stream_t *in=0; jas_matrix_t **bufs=0; int32_t i,error=0; int32_t fmt; //jas_setdbglevel(0); cx_try { if (jas_init()) cx_throw("cannot initialize jasper"); in = jas_stream_fdopen(0, "rb"); if (!in) cx_throw("error: cannot open standard input"); CxFileJas src(hFile,in); fmt = jas_image_getfmt(in); if (fmt<0) cx_throw("error: unknowm format"); image = jas_image_decode(in, fmt, 0); if (!image){ fmt = -1; cx_throw("error: cannot load image data"); } char szfmt[4]; *szfmt = '\0'; strncpy(szfmt,jas_image_fmttostr(fmt),3); szfmt[3] = '\0'; fmt = -1; #if CXIMAGE_SUPPORT_JP2 if (strcmp(szfmt,"jp2")==0) fmt = CXIMAGE_FORMAT_JP2; #endif #if CXIMAGE_SUPPORT_JPC if (strcmp(szfmt,"jpc")==0) fmt = CXIMAGE_FORMAT_JPC; #endif #if CXIMAGE_SUPPORT_RAS if (strcmp(szfmt,"ras")==0) fmt = CXIMAGE_FORMAT_RAS; #endif #if CXIMAGE_SUPPORT_PNM if (strcmp(szfmt,"pnm")==0) fmt = CXIMAGE_FORMAT_PNM; #endif #if CXIMAGE_SUPPORT_PGX if (strcmp(szfmt,"pgx")==0) fmt = CXIMAGE_FORMAT_PGX; #endif //if (fmt<0) // cx_throw("error: unknowm format"); int32_t x,y,w,h,depth,cmptno; w = jas_image_cmptwidth(image,0); h = jas_image_cmptheight(image,0); depth = jas_image_cmptprec(image,0); if (info.nEscape == -1){ head.biWidth = w; head.biHeight= h; info.dwType = fmt<0 ? 0 : fmt; cx_throw("output dimensions returned"); } if (image->numcmpts_ > 64 || image->numcmpts_ < 0) cx_throw("error: too many components"); // <LD> 01/Jan/2005: Always force conversion to sRGB. Seems to be required for many types of JPEG2000 file. // if (depth!=1 && depth!=4 && depth!=8) if (image->numcmpts_>=3 && depth <=8) { jas_image_t *newimage; jas_cmprof_t *outprof; //jas_eprintf("forcing conversion to sRGB\n"); outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB); if (!outprof) { cx_throw("cannot create sRGB profile"); } newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER); if (!newimage) { jas_cmprof_destroy(outprof); // <LD> 01/Jan/2005: Destroy color profile on error. cx_throw("cannot convert to sRGB"); } jas_image_destroy(image); jas_cmprof_destroy(outprof); image = newimage; } bufs = (jas_matrix_t **)calloc(image->numcmpts_, sizeof(jas_matrix_t**)); for (i = 0; i < image->numcmpts_; ++i) { bufs[i] = jas_matrix_create(1, w); if (!bufs[i]) { cx_throw("error: cannot allocate memory"); } } int32_t nshift = (depth>8) ? (depth-8) : 0; if (image->numcmpts_==3 && image->cmpts_[0]->width_ == image->cmpts_[1]->width_ && image->cmpts_[1]->width_ == image->cmpts_[2]->width_ && image->cmpts_[0]->height_ == image->cmpts_[1]->height_ && image->cmpts_[1]->height_ == image->cmpts_[2]->height_ && image->cmpts_[0]->prec_ == image->cmpts_[1]->prec_ && image->cmpts_[1]->prec_ == image->cmpts_[2]->prec_ ) { if(!Create(w,h,24,fmt)) cx_throw(""); RGBQUAD c; for (y=0; y<h; y++) { for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { jas_image_readcmpt(image, cmptno, 0, y, w, 1, bufs[cmptno]); } for (x=0; x<w; x++){ c.rgbRed = (uint8_t)((jas_matrix_getv(bufs[0], x)>>nshift)); c.rgbGreen = (uint8_t)((jas_matrix_getv(bufs[1], x)>>nshift)); c.rgbBlue = (uint8_t)((jas_matrix_getv(bufs[2], x)>>nshift)); SetPixelColor(x,h-1-y,c); } } } else { info.nNumFrames = image->numcmpts_; if ((info.nFrame<0)||(info.nFrame>=info.nNumFrames)){ cx_throw("wrong frame!"); } for (cmptno=0; cmptno<=info.nFrame; cmptno++) { w = jas_image_cmptwidth(image,cmptno); h = jas_image_cmptheight(image,cmptno); depth = jas_image_cmptprec(image,cmptno); if (depth>8) depth=8; if(!Create(w,h,depth,imagetype)) cx_throw(""); SetGrayPalette(); for (y=0; y<h; y++) { jas_image_readcmpt(image, cmptno, 0, y, w, 1, bufs[0]); for (x=0; x<w; x++){ SetPixelIndex(x,h-1-y,(uint8_t)((jas_matrix_getv(bufs[0], x)>>nshift))); } } } } } cx_catch {
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 }
static void WriteJP2KImage( const GenericImage<P>& img, const ImageInfo& info, const ImageOptions& options, jas_stream_t* jp2Stream, jas_image_t* jp2Image, int jp2Format, const JPEG2000ImageOptions& jp2Options ) { jas_matrix_t* pixels = nullptr; try { pixels = jas_matrix_create( 1, img.Width() ); if ( pixels == nullptr ) throw Error( "Memory allocation error writing JPEG2000 image." ); for ( int c = 0; c < img.NumberOfChannels(); ++c ) { for ( int y = 0; y < img.Height(); ++y ) { const typename P::sample* f = img.ScanLine( y, c ); if ( options.bitsPerSample == 8 ) { if ( jp2Options.signedSample ) { int8 v; for ( int x = 0; x < img.Width(); ++x ) { P::FromSample( v, *f++ ); jas_matrix_set( pixels, 0, x, v ); } } else { uint8 v; for ( int x = 0; x < img.Width(); ++x ) { P::FromSample( v, *f++ ); jas_matrix_set( pixels, 0, x, v ); } } } else { if ( jp2Options.signedSample ) { int16 v; for ( int x = 0; x < img.Width(); ++x ) { P::FromSample( v, *f++ ); jas_matrix_set( pixels, 0, x, v ); } } else { uint16 v; for ( int x = 0; x < img.Width(); ++x ) { P::FromSample( v, *f++ ); jas_matrix_set( pixels, 0, x, v ); } } } jas_image_writecmpt( jp2Image, c, 0, y, img.Width(), 1, pixels ); } } IsoString jp2OptionsStr; jp2OptionsStr.AppendFormat( "mode=%s", jp2Options.lossyCompression ? "real" : "int" ); if ( jp2Options.lossyCompression ) jp2OptionsStr.AppendFormat( " rate=%g", jp2Options.compressionRate ); if ( jp2Options.tiledImage ) { jp2OptionsStr.AppendFormat( " tilewidth=%d", Range( jp2Options.tileWidth, 8, img.Width() ) ); jp2OptionsStr.AppendFormat( " tileheight=%d", Range( jp2Options.tileHeight, 8, img.Height() ) ); } if ( jp2Options.numberOfLayers > 1 ) { jp2OptionsStr.Append( " ilyrrates=" ); float dr = (jp2Options.lossyCompression ? jp2Options.compressionRate : 1.0F)/jp2Options.numberOfLayers; for ( int l = 1; ; ) { jp2OptionsStr.AppendFormat( "%g", l*dr ); if ( ++l == jp2Options.numberOfLayers ) break; jp2OptionsStr.Append( ',' ); } jp2OptionsStr.Append( " prg=" ); switch ( jp2Options.progressionOrder ) { default: case JPEG2000ProgressionOrder::LRCP: jp2OptionsStr.Append( "lrcp" ); break; case JPEG2000ProgressionOrder::RLCP: jp2OptionsStr.Append( "rlcp" ); break; case JPEG2000ProgressionOrder::RPCL: jp2OptionsStr.Append( "rpcl" ); break; case JPEG2000ProgressionOrder::PCRL: jp2OptionsStr.Append( "pcrl" ); break; case JPEG2000ProgressionOrder::CPRL: jp2OptionsStr.Append( "cprl" ); break; } } if ( jas_image_encode( jp2Image, jp2Stream, jp2Format, jp2OptionsStr.Begin() ) < 0 ) throw Error( "Unable to encode JPEG2000 image." ); jas_matrix_destroy( pixels ), pixels = nullptr; } catch ( ... ) { if ( pixels != nullptr ) jas_matrix_destroy( pixels ); throw; } }
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 GrFmtJpeg2000Reader::ReadData( uchar* data, int step, int color ) { bool result = false; color = color > 0 || ( m_iscolor && color < 0 ); if( m_stream && m_image ) { bool convert; int colorspace; if( color ) { convert = (jas_image_clrspc( m_image ) != JAS_CLRSPC_SRGB); colorspace = JAS_CLRSPC_SRGB; } else { convert = (jas_clrspc_fam( jas_image_clrspc( m_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( m_image, clrprof, JAS_CMXFORM_INTENT_RELCLR ); if( img ) { jas_image_destroy( m_image ); m_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( m_image, JAS_IMAGE_CT_RGB_B ); cmptlut[1] = jas_image_getcmptbytype( m_image, JAS_IMAGE_CT_RGB_G ); cmptlut[2] = jas_image_getcmptbytype( m_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( m_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( m_image, cmptlut[i] ); int offset = jas_image_cmptsgnd( m_image, cmptlut[i] ) ? maxval / 2 : 0; int yend = jas_image_cmptbry( m_image, cmptlut[i] ); int ystep = jas_image_cmptvstep( m_image, cmptlut[i] ); int xend = jas_image_cmptbrx( m_image, cmptlut[i] ); int xstep = jas_image_cmpthstep( m_image, cmptlut[i] ); jas_matrix_t *buffer = jas_matrix_create( yend / ystep, xend / xstep ); if( buffer ) { if( !jas_image_readcmpt( m_image, cmptlut[i], 0, 0, xend / xstep, yend / ystep, buffer )) { if( m_bit_depth == 8 || !m_native_depth ) 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; }
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; }
static int pnm_getdata(jas_stream_t *in, pnm_hdr_t *hdr, jas_image_t *image) { int ret; #if 0 int numcmpts; #endif int cmptno; int fmt; jas_matrix_t *data[3]; int x; int y; int_fast64_t v; int depth; int type; int c; int n; ret = -1; #if 0 numcmpts = jas_image_numcmpts(image); #endif fmt = pnm_fmt(hdr->magic); type = pnm_type(hdr->magic); depth = pnm_maxvaltodepth(hdr->maxval); data[0] = 0; data[1] = 0; data[2] = 0; for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) { if (!(data[cmptno] = jas_matrix_create(1, hdr->width))) { goto done; } } for (y = 0; y < hdr->height; ++y) { if (type == PNM_TYPE_PBM) { if (fmt == PNM_FMT_BIN) { for (x = 0; x < hdr->width;) { if ((c = jas_stream_getc(in)) == EOF) { goto done; } n = 8; while (n > 0 && x < hdr->width) { jas_matrix_set(data[0], 0, x, 1 - ((c >> 7) & 1)); c <<= 1; --n; ++x; } } } else { for (x = 0; x < hdr->width; ++x) { int uv; if (pnm_getbitstr(in, &uv)) { goto done; } jas_matrix_set(data[0], 0, x, 1 - uv); } } } else { for (x = 0; x < hdr->width; ++x) {
jas_image_t *jpg_decode(jas_stream_t *in, char *optstr) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; FILE *input_file; jpg_dest_t dest_mgr_buf; jpg_dest_t *dest_mgr = &dest_mgr_buf; int num_scanlines; jas_image_t *image; /* Avoid compiler warnings about unused parameters. */ optstr = 0; image = 0; input_file = 0; if (!(input_file = tmpfile())) { goto error; } if (jpg_copystreamtofile(input_file, in)) { goto error; } rewind(input_file); /* Allocate and initialize a JPEG decompression object. */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); /* Specify the data source for decompression. */ jpeg_stdio_src(&cinfo, input_file); /* Read the file header to obtain the image information. */ jpeg_read_header(&cinfo, TRUE); /* Start the decompressor. */ jpeg_start_decompress(&cinfo); /* Create an image object to hold the decoded data. */ if (!(image = jpg_mkimage(&cinfo))) { goto error; } /* Initialize the data sink object. */ dest_mgr->image = image; dest_mgr->data = jas_matrix_create(1, cinfo.output_width); dest_mgr->start_output = jpg_start_output; dest_mgr->put_pixel_rows = jpg_put_pixel_rows; dest_mgr->finish_output = jpg_finish_output; dest_mgr->buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, (JDIMENSION) 1); dest_mgr->buffer_height = 1; dest_mgr->error = 0; /* Process the compressed data. */ (*dest_mgr->start_output)(&cinfo, dest_mgr); while (cinfo.output_scanline < cinfo.output_height) { num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer, dest_mgr->buffer_height); (*dest_mgr->put_pixel_rows)(&cinfo, dest_mgr, num_scanlines); } (*dest_mgr->finish_output)(&cinfo, dest_mgr); /* Complete the decompression process. */ jpeg_finish_decompress(&cinfo); /* Destroy the JPEG decompression object. */ jpeg_destroy_decompress(&cinfo); jas_matrix_destroy(dest_mgr->data); fclose(input_file); if (dest_mgr->error) { goto error; } return image; error: if (image) { jas_image_destroy(image); } if (input_file) { fclose(input_file); } return 0; }
int FROM_jpeg2000(char *injpc,int bufsize,unsigned int *outfld) /*$$$ SUBPROGRAM DOCUMENTATION BLOCK * . . . . * SUBPROGRAM: FROM_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.700.2 or better 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 * 2015-10-26 M.Valin - removed GRIB library connections, light refactoring, * changed function name * * USAGE: int FROM_jpeg2000(char *injpc,int bufsize,int *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 allowed. * * REMARKS: * * Requires JasPer Software version 1.700.2 or better * * ATTRIBUTES: * LANGUAGE: C * OS: Linux * *$$$*/ { int ier; int i,j,k; jas_image_t *image=0; jas_stream_t *jpcstream; jas_image_cmpt_t *pcmpt; char *opts=0; jas_matrix_t *data; #define ROW unsigned long // ROW *my_row; unsigned int value; // 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\n"); return -3; } pcmpt=image->cmpts_[0]; #if defined(DEBUG) printf(" SAGOUT DECODE:\n"); printf(" tlx %d \n",image->tlx_); printf(" tly %d \n",image->tly_); printf(" brx %d \n",image->brx_); printf(" bry %d \n",image->bry_); printf(" numcmpts %d \n",image->numcmpts_); printf(" maxcmpts %d \n",image->maxcmpts_); printf(" colorspace %d \n",image->clrspc_); printf(" inmem %d \n",image->inmem_); printf(" COMPONENT:\n"); printf(" tlx %d \n",pcmpt->tlx_); printf(" tly %d \n",pcmpt->tly_); printf(" hstep %d \n",pcmpt->hstep_); printf(" vstep %d \n",pcmpt->vstep_); printf(" width %d \n",pcmpt->width_); printf(" height %d \n",pcmpt->height_); printf(" prec %d \n",pcmpt->prec_); printf(" sgnd %d \n",pcmpt->sgnd_); printf(" cps %d \n",pcmpt->cps_); printf(" type %d \n",pcmpt->type_); #endif // Expecting jpeg2000 image to be grayscale only. // No color components. // if (image->numcmpts_ != 1 ) { printf("FROM_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; // printf ("deltap = %d\n",data->rows_[1]-data->rows_[0]); for (i=0;i<pcmpt->height_;i++) { // my_row = (ROW *)data->rows_[i]; // printf ("p = %16p\n",my_row); for (j=0;j<pcmpt->width_;j++) { // value = my_row[j]; // outfld[k++] = my_row[j]; // printf ("%4ld ",my_row[j]); // printf ("%16.16x ",my_row[j]); outfld[k++]=data->rows_[i][j]; } // printf ("%d \n",k); } // // Clean up JasPer work structures. // jas_matrix_destroy(data); ier=jas_stream_close(jpcstream); jas_image_destroy(image); return 0; }
/* Encode a single code block. */ int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *tcmpt, jpc_enc_band_t *band, jpc_enc_cblk_t *cblk) { jpc_enc_pass_t *pass; jpc_enc_pass_t *endpasses; int bitpos; int n; int adjust; int ret; int passtype; int t; jpc_bitstream_t *bout; jpc_enc_pass_t *termpass; jpc_enc_rlvl_t *rlvl; int vcausal; int segsym; int termmode; int c; bout = 0; rlvl = band->rlvl; cblk->stream = jas_stream_memopen(0, 0); assert(cblk->stream); cblk->mqenc = jpc_mqenc_create(JPC_NUMCTXS, cblk->stream); assert(cblk->mqenc); jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs); cblk->numpasses = (cblk->numbps > 0) ? (3 * cblk->numbps - 2) : 0; if (cblk->numpasses > 0) { cblk->passes = jas_malloc(cblk->numpasses * sizeof(jpc_enc_pass_t)); assert(cblk->passes); } else { cblk->passes = 0; } endpasses = &cblk->passes[cblk->numpasses]; for (pass = cblk->passes; pass != endpasses; ++pass) { pass->start = 0; pass->end = 0; pass->term = JPC_ISTERMINATED(pass - cblk->passes, 0, cblk->numpasses, (tcmpt->cblksty & JPC_COX_TERMALL) != 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0); pass->type = JPC_SEGTYPE(pass - cblk->passes, 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0); pass->lyrno = -1; if (pass == endpasses - 1) { assert(pass->term == 1); pass->term = 1; } } cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2, jas_matrix_numcols(cblk->data) + 2); assert(cblk->flags); bitpos = cblk->numbps - 1; pass = cblk->passes; n = cblk->numpasses; while (--n >= 0) { if (pass->type == JPC_SEG_MQ) { /* NOP */ } else { assert(pass->type == JPC_SEG_RAW); if (!bout) { bout = jpc_bitstream_sopen(cblk->stream, "w"); assert(bout); } } #if 1 passtype = (pass - cblk->passes + 2) % 3; #else passtype = JPC_PASSTYPE(pass - cblk->passes + 2); #endif pass->start = jas_stream_tell(cblk->stream); #if 0 assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream)); #endif assert(bitpos >= 0); vcausal = (tcmpt->cblksty & JPC_COX_VSC) != 0; segsym = (tcmpt->cblksty & JPC_COX_SEGSYM) != 0; if (pass->term) { termmode = ((tcmpt->cblksty & JPC_COX_PTERM) ? JPC_MQENC_PTERM : JPC_MQENC_DEFTERM) + 1; } else { termmode = 0; } switch (passtype) { case JPC_SIGPASS: ret = (pass->type == JPC_SEG_MQ) ? jpc_encsigpass(cblk->mqenc, bitpos, band->orient, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec) : jpc_encrawsigpass(bout, bitpos, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec); break; case JPC_REFPASS: ret = (pass->type == JPC_SEG_MQ) ? jpc_encrefpass(cblk->mqenc, bitpos, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec) : jpc_encrawrefpass(bout, bitpos, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec); break; case JPC_CLNPASS: assert(pass->type == JPC_SEG_MQ); ret = jpc_encclnpass(cblk->mqenc, bitpos, band->orient, vcausal, segsym, cblk->flags, cblk->data, termmode, &pass->nmsedec); break; default: assert(0); break; } if (pass->type == JPC_SEG_MQ) { if (pass->term) { jpc_mqenc_init(cblk->mqenc); } jpc_mqenc_getstate(cblk->mqenc, &pass->mqencstate); pass->end = jas_stream_tell(cblk->stream); if (tcmpt->cblksty & JPC_COX_RESET) { jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs); } } else { if (pass->term) { if (jpc_bitstream_pending(bout)) { jpc_bitstream_outalign(bout, 0x2a); } jpc_bitstream_close(bout); bout = 0; pass->end = jas_stream_tell(cblk->stream); } else { pass->end = jas_stream_tell(cblk->stream) + jpc_bitstream_pending(bout); /* NOTE - This will not work. need to adjust by # of pending output bytes */ } } #if 0 /* XXX - This assertion fails sometimes when various coding modes are used. This seems to be harmless, but why does it happen at all? */ assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream)); #endif pass->wmsedec = jpc_fixtodbl(band->rlvl->tcmpt->synweight) * jpc_fixtodbl(band->rlvl->tcmpt->synweight) * jpc_fixtodbl(band->synweight) * jpc_fixtodbl(band->synweight) * jpc_fixtodbl(band->absstepsize) * jpc_fixtodbl(band->absstepsize) * ((double) (1 << bitpos)) * ((double)(1 << bitpos)) * jpc_fixtodbl(pass->nmsedec); pass->cumwmsedec = pass->wmsedec; if (pass != cblk->passes) { pass->cumwmsedec += pass[-1].cumwmsedec; } if (passtype == JPC_CLNPASS) { --bitpos; } ++pass; } #if 0 dump_passes(cblk->passes, cblk->numpasses, cblk); #endif n = 0; endpasses = &cblk->passes[cblk->numpasses]; for (pass = cblk->passes; pass != endpasses; ++pass) { if (pass->start < n) { pass->start = n; } if (pass->end < n) { pass->end = n; } if (!pass->term) { termpass = pass; while (termpass - pass < cblk->numpasses && !termpass->term) { ++termpass; } if (pass->type == JPC_SEG_MQ) { t = (pass->mqencstate.lastbyte == 0xff) ? 1 : 0; if (pass->mqencstate.ctreg >= 5) { adjust = 4 + t; } else { adjust = 5 + t; } pass->end += adjust; } if (pass->end > termpass->end) { pass->end = termpass->end; } if ((c = getthebyte(cblk->stream, pass->end - 1)) == EOF) { abort(); } if (c == 0xff) { ++pass->end; } n = JAS_MAX(n, pass->end); } else { n = JAS_MAX(n, pass->end); } } #if 0 dump_passes(cblk->passes, cblk->numpasses, cblk); #endif if (bout) { jpc_bitstream_close(bout); } return 0; }
static void createJasperRaster(struct pam * const inpamP, jas_image_t * const jasperP) { jas_matrix_t ** matrix; /* malloc'ed */ /* matrix[X] is the data for Plane X of the current row */ unsigned int plane; unsigned int row; tuple * tuplerow; bool oddMaxval; sample jasperMaxval; matrix = malloc(inpamP->depth * sizeof(jas_matrix_t *)); if (matrix == NULL) pm_error("Out of memory"); for (plane = 0; plane < inpamP->depth; ++plane) { matrix[plane] = jas_matrix_create(1, inpamP->width); if (matrix[plane] == NULL) pm_error("Unable to create matrix for plane %u. " "jas_matrix_create() failed.", plane); } tuplerow = pnm_allocpamrow(inpamP); jasperMaxval = pm_bitstomaxval(pm_maxvaltobits(inpamP->maxval)); oddMaxval = jasperMaxval != inpamP->maxval; for (row = 0; row < inpamP->height; ++row) { unsigned int col; pnm_readpamrow(inpamP, tuplerow); for (col = 0; col < inpamP->width; ++col) { unsigned int plane; for (plane = 0; plane < inpamP->depth; ++plane) { unsigned int jasperSample; if (oddMaxval) jasperSample = tuplerow[col][plane] * jasperMaxval / inpamP->maxval; else jasperSample = tuplerow[col][plane]; jas_matrix_set(matrix[plane], 0, col, jasperSample); } } { unsigned int plane; for (plane = 0; plane < inpamP->depth; ++plane) { int rc; rc = jas_image_writecmpt(jasperP, plane, 0, row, inpamP->width, 1, matrix[plane]); if (rc != 0) pm_error("jas_image_writecmpt() of plane %u failed.", plane); } } } pnm_freepamrow(tuplerow); for (plane = 0; plane < inpamP->depth; ++plane) jas_matrix_destroy(matrix[plane]); free(matrix); }