apr_status_t dims_brightness_operation (dims_request_rec *d, char *args, char **err) { MagickStatusType flags; GeometryInfo geometry; flags = ParseGeometry(args, &geometry); //MAGICK_CHECK(MagickBrightnessContrastImage(d->wand, // geometry.rho, geometry.sigma), d); return DIMS_SUCCESS; }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsGeometry() returns MagickTrue if the geometry specification is valid. % Examples are 100, 100x200, x200, 100x200+10+20, +10+20, 200%, 200x200!, etc. % % The format of the IsGeometry method is: % % MagickBooleanType IsGeometry(const char *geometry) % % A description of each parameter follows: % % o geometry: This string is the geometry specification. % */ MagickExport MagickBooleanType IsGeometry(const char *geometry) { GeometryInfo geometry_info; MagickStatusType flags; if (geometry == (const char *) NULL) return(MagickFalse); flags=ParseGeometry(geometry,&geometry_info); return(flags != NoValue ? MagickTrue : MagickFalse); }
apr_status_t dims_sharpen_operation (dims_request_rec *d, char *args, char **err) { MagickStatusType flags; GeometryInfo geometry; flags = ParseGeometry(args, &geometry); if ((flags & SigmaValue) == 0) { geometry.sigma=1.0; } MAGICK_CHECK(MagickSharpenImage(d->wand, geometry.rho, geometry.sigma), d); return DIMS_SUCCESS; }
void ForEachPoint(Functor && f, int scale) { ParseGeometry(scale); if (m_points.empty()) { // it's a point feature if (GetFeatureType() == feature::GEOM_POINT) f(m_center); } else { for (size_t i = 0; i < m_points.size(); ++i) f(m_points[i]); } }
// output_data apr_status_t small_light_filter_imagemagick_output_data( ap_filter_t *f, apr_bucket_brigade *bb, void *v_ctx, apr_bucket *e) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, f->r, "small_light_filter_imagemagick_output_data"); request_rec *r = f->r; small_light_module_ctx_t* ctx = (small_light_module_ctx_t*)v_ctx; small_light_module_imagemagick_ctx_t *lctx = ctx->lctx; struct timeval t2, t21, t22, t23, t3; MagickBooleanType status = MagickFalse; // check data received. if (lctx->image == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "no data received."); r->status = HTTP_INTERNAL_SERVER_ERROR; return APR_EGENERAL; } // start image modifing. gettimeofday(&t2, NULL); small_light_image_size_t sz; small_light_calc_image_size(&sz, r, ctx, 10000.0, 10000.0); // init wand small_light_filter_imagemagick_output_data_init(); lctx->wand = NewMagickWand(); // prepare. if (sz.jpeghint_flg != 0) { char *jpeg_size_opt = (char *)apr_psprintf(r->pool, "%dx%d", (int)sz.dw, (int)sz.dh); MagickSetOption(lctx->wand, "jpeg:size", jpeg_size_opt); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickSetOption(jpeg:size, %s)", jpeg_size_opt); } // load image. gettimeofday(&t21, NULL); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickReadImageBlob"); status = MagickReadImageBlob(lctx->wand, (void *)lctx->image, lctx->image_len); if (status == MagickFalse) { small_light_filter_imagemagick_output_data_fini(ctx); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "couldn't read image"); r->status = HTTP_INTERNAL_SERVER_ERROR; return APR_EGENERAL; } // calc size. gettimeofday(&t22, NULL); double iw = (double)MagickGetImageWidth(lctx->wand); double ih = (double)MagickGetImageHeight(lctx->wand); small_light_calc_image_size(&sz, r, ctx, iw, ih); // pass through. if (sz.pt_flg != 0) { small_light_filter_imagemagick_output_data_fini(ctx); apr_bucket *b = apr_bucket_pool_create(lctx->image, lctx->image_len, r->pool, ctx->bb->bucket_alloc); APR_BRIGADE_INSERT_TAIL(ctx->bb, b); APR_BRIGADE_INSERT_TAIL(ctx->bb, apr_bucket_eos_create(ctx->bb->bucket_alloc)); return ap_pass_brigade(f->next, ctx->bb); } // crop, scale. status = MagickTrue; if (sz.scale_flg != 0) { char *crop_geo = (char *)apr_psprintf(r->pool, "%f!x%f!+%f+%f", sz.sw, sz.sh, sz.sx, sz.sy); char *size_geo = (char *)apr_psprintf(r->pool, "%f!x%f!", sz.dw, sz.dh); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickTransformImage(wand, ""%s"", ""%s"")", crop_geo, size_geo); MagickWand *trans_wand; trans_wand = MagickTransformImage(lctx->wand, crop_geo, size_geo); if (trans_wand == NULL || trans_wand == lctx->wand) { small_light_filter_imagemagick_output_data_fini(ctx); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MagickTransformImage failed"); r->status = HTTP_INTERNAL_SERVER_ERROR; return APR_EGENERAL; } DestroyMagickWand(lctx->wand); lctx->wand = trans_wand; } else { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "no scale"); } // create canvas then draw image to the canvas. if (sz.cw > 0.0 && sz.ch > 0.0) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "NewMagickWand()"); MagickWand *canvas_wand = NewMagickWand(); PixelWand *canvas_color = NewPixelWand(); PixelSetRed(canvas_color, sz.cc.r / 255.0); PixelSetGreen(canvas_color, sz.cc.g / 255.0); PixelSetBlue(canvas_color, sz.cc.b / 255.0); PixelSetAlpha(canvas_color, sz.cc.a / 255.0); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickNewImage(canvas_wand, %f, %f, bgcolor)", sz.cw, sz.ch); status = MagickNewImage(canvas_wand, sz.cw, sz.ch, canvas_color); DestroyPixelWand(canvas_color); if (status == MagickFalse) { small_light_filter_imagemagick_output_data_fini(ctx); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MagickNewImage(canvas_wand, %f, %f, bgcolor) failed", sz.cw, sz.ch); r->status = HTTP_INTERNAL_SERVER_ERROR; return APR_EGENERAL; } ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickCompositeImage(canvas_wand, wand, AtopCompositeOp, %f, %f)", sz.dx, sz.dy); status = MagickCompositeImage(canvas_wand, lctx->wand, AtopCompositeOp, sz.dx, sz.dy); if (status == MagickFalse) { small_light_filter_imagemagick_output_data_fini(ctx); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "MagickCompositeImage(canvas_wand, wand, AtopCompositeOp, %f, %f) failed", sz.dx, sz.dy); r->status = HTTP_INTERNAL_SERVER_ERROR; return APR_EGENERAL; } DestroyMagickWand(lctx->wand); lctx->wand = canvas_wand; } // effects. char *unsharp = (char *)apr_table_get(ctx->prm, "unsharp"); if (unsharp) { GeometryInfo geo; ParseGeometry(unsharp, &geo); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickUnsharpMaskImage(wand, %f, %f, %f, %f)", geo.rho, geo.sigma, geo.xi, geo.psi); status = MagickUnsharpMaskImage(lctx->wand, geo.rho, geo.sigma, geo.xi, geo.psi); if (status == MagickFalse) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "unsharp failed"); } } char *sharpen = (char *)apr_table_get(ctx->prm, "sharpen"); if (sharpen) { GeometryInfo geo; ParseGeometry(sharpen, &geo); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickSharpenImage(wand, %f, %f)", geo.rho, geo.sigma); status = MagickSharpenImage(lctx->wand, geo.rho, geo.sigma); if (status == MagickFalse) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "sharpen failed"); } } char *blur = (char *)apr_table_get(ctx->prm, "blur"); if (blur) { GeometryInfo geo; ParseGeometry(blur, &geo); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickBlurImage(wand, %f, %f)", geo.rho, geo.sigma); status = MagickBlurImage(lctx->wand, geo.rho, geo.sigma); if (status == MagickFalse) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "blur failed"); } } // border. if (sz.bw > 0.0 || sz.bh > 0.0) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "draw border"); DrawingWand *border_wand = NewDrawingWand(); PixelWand *border_color; border_color = NewPixelWand(); PixelSetRed(border_color, sz.bc.r / 255.0); PixelSetGreen(border_color, sz.bc.g / 255.0); PixelSetBlue(border_color, sz.bc.b / 255.0); PixelSetAlpha(border_color, sz.bc.a / 255.0); DrawSetFillColor(border_wand, border_color); DrawSetStrokeColor(border_wand, border_color); DrawSetStrokeWidth(border_wand, 1); DrawRectangle(border_wand, 0, 0, sz.cw - 1, sz.bh - 1); DrawRectangle(border_wand, 0, 0, sz.bw - 1, sz.ch - 1); DrawRectangle(border_wand, 0, sz.ch - sz.bh, sz.cw - 1, sz.ch - 1); DrawRectangle(border_wand, sz.cw - sz.bw, 0, sz.cw - 1, sz.ch - 1); MagickDrawImage(lctx->wand, border_wand); DestroyPixelWand(border_color); DestroyDrawingWand(border_wand); } gettimeofday(&t23, NULL); // set params. double q = small_light_parse_double(r, (char *)apr_table_get(ctx->prm, "q")); if (q > 0.0) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickSetImageComressionQualty(wand, %f)", q); MagickSetImageCompressionQuality(lctx->wand, q); } char *of = (char *)apr_table_get(ctx->prm, "of"); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "MagickSetFormat(wand, '%s')", of); MagickSetFormat(lctx->wand, of); // get small_lighted image as binary. unsigned char *canvas_buff; const char *sled_image; size_t sled_image_size; canvas_buff = MagickGetImageBlob(lctx->wand, &sled_image_size); sled_image = (const char *)apr_pmemdup(r->pool, canvas_buff, sled_image_size); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "sled_image_size = %d", sled_image_size); // free buffer and wand. MagickRelinquishMemory(canvas_buff); small_light_filter_imagemagick_output_data_fini(ctx); // insert new bucket to bucket brigade. apr_bucket *b = apr_bucket_pool_create(sled_image, sled_image_size, r->pool, ctx->bb->bucket_alloc); APR_BRIGADE_INSERT_TAIL(ctx->bb, b); // insert eos to bucket brigade. APR_BRIGADE_INSERT_TAIL(ctx->bb, apr_bucket_eos_create(ctx->bb->bucket_alloc)); // set correct Content-Type and Content-Length. char *cont_type = apr_psprintf(r->pool, "image/%s", of); ap_set_content_type(r, cont_type); ap_set_content_length(r, sled_image_size); // end. gettimeofday(&t3, NULL); // http header. int info = small_light_parse_int(r, (char *)apr_table_get(ctx->prm, "info")); if (info != SMALL_LIGHT_INT_INVALID_VALUE && info != 0) { char *info = (char *)apr_psprintf(r->pool, "transfer=%ldms, modify image=%ldms (load=%ldms, scale=%ldms, save=%ldms)", small_light_timeval_diff(&ctx->t, &t2) / 1000L, small_light_timeval_diff(&t2, &t3) / 1000L, small_light_timeval_diff(&t21, &t22) / 1000L, small_light_timeval_diff(&t22, &t23) / 1000L, small_light_timeval_diff(&t23, &t3) / 1000L ); ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "uri=%s, info=%s)", r->unparsed_uri, info); apr_table_setn(r->headers_out, "X-SmallLight-Description", info); } return ap_pass_brigade(f->next, ctx->bb); }
static MagickBooleanType WritePS2Image(const ImageInfo *image_info,Image *image) { static const char *PostscriptProlog[]= { "%%%%BeginProlog", "%%", "%% Display a color image. The image is displayed in color on", "%% Postscript viewers or printers that support color, otherwise", "%% it is displayed as grayscale.", "%%", "/DirectClassImage", "{", " %%", " %% Display a DirectClass image.", " %%", " colorspace 0 eq", " {", " /DeviceRGB setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [0 1 0 1 0 1]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " { /DataSource pixel_stream %s } ifelse", " >> image", " }", " {", " /DeviceCMYK setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [1 0 1 0 1 0 1 0]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " { /DataSource pixel_stream %s } ifelse", " >> image", " } ifelse", "} bind def", "", "/PseudoClassImage", "{", " %%", " %% Display a PseudoClass image.", " %%", " %% Parameters:", " %% colors: number of colors in the colormap.", " %%", " currentfile buffer readline pop", " token pop /colors exch def pop", " colors 0 eq", " {", " %%", " %% Image is grayscale.", " %%", " currentfile buffer readline pop", " token pop /bits exch def pop", " /DeviceGray setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent bits", " /Decode [0 1]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " {", " /DataSource pixel_stream %s", " <<", " /K "CCITTParam, " /Columns columns", " /Rows rows", " >> /CCITTFaxDecode filter", " } ifelse", " >> image", " }", " {", " %%", " %% Parameters:", " %% colormap: red, green, blue color packets.", " %%", " /colormap colors 3 mul string def", " currentfile colormap readhexstring pop pop", " currentfile buffer readline pop", " [ /Indexed /DeviceRGB colors 1 sub colormap ] setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [0 255]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " compression 0 gt", " { /DataSource pixel_stream %s }", " { /DataSource pixel_stream %s } ifelse", " >> image", " } ifelse", "} bind def", "", "/DisplayImage", "{", " %%", " %% Display a DirectClass or PseudoClass image.", " %%", " %% Parameters:", " %% x & y translation.", " %% x & y scale.", " %% label pointsize.", " %% image label.", " %% image columns & rows.", " %% class: 0-DirectClass or 1-PseudoClass.", " %% colorspace: 0-RGB or 1-CMYK.", " %% compression: 0-RLECompression or 1-NoCompression.", " %% hex color packets.", " %%", " gsave", " /buffer 512 string def", " /pixel_stream currentfile def", "", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", " /Helvetica findfont pointsize scalefont setfont", (char *) NULL }, *PostscriptEpilog[]= { " x y scale", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " currentfile buffer readline pop", " token pop /class exch def pop", " currentfile buffer readline pop", " token pop /colorspace exch def pop", " currentfile buffer readline pop", " token pop /compression exch def pop", " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse", (char *) NULL }; char buffer[MaxTextExtent], date[MaxTextExtent], page_geometry[MaxTextExtent], **labels; CompressionType compression; const char **q, *value; double pointsize; GeometryInfo geometry_info; MagickOffsetType scene, start, stop; MagickBooleanType progress, status; MagickOffsetType offset; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; register ssize_t i; SegmentInfo bounds; size_t length, page, text_size; ssize_t j, y; time_t timer; unsigned char *pixels; /* Open output 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); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif default: break; } (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); page=1; scene=0; do { /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(size_t) (100.0*2.54*resolution.x+0.5)/100.0; resolution.y=(size_t) (100.0*2.54*resolution.y+0.5)/100.0; } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS2") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MaxTextExtent,date); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+geometry.width; bounds.y2=(double) geometry.y+geometry.height+text_size; if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%BoundingBox: (atend)\n", MaxTextExtent); else { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1, bounds.y1,bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Helvetica\n"); (void) WriteBlobString(image,"%%LanguageLevel: 2\n"); if (LocaleCompare(image_info->magick,"PS2") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); if (image_info->adjoin == MagickFalse) (void) CopyMagickString(buffer,"%%Pages: 1\n",MaxTextExtent); else (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%Pages: %.20g\n",(double) GetImageListLength(image)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); /* Output Postscript commands. */ for (q=PostscriptProlog; *q; q++) { switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,*q, "/ASCII85Decode filter"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,*q, "/DCTDecode filter"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,*q, "/LZWDecode filter"); break; } case FaxCompression: case Group4Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,*q," "); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,*q, "/RunLengthDecode filter"); break; } } (void) WriteBlobString(image,buffer); (void) WriteBlobByte(image,'\n'); } value=GetImageProperty(image,"label"); if (value != (const char *) NULL) for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image," currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MaxTextExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } for (q=PostscriptEpilog; *q; q++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n",*q); (void) WriteBlobString(image,buffer); } if (LocaleCompare(image_info->magick,"PS2") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Page: 1 %.20g\n", (double) page++); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%PageResources: font Times-Roman\n"); if (LocaleCompare(image_info->magick,"PS2") != 0) (void) WriteBlobString(image,"userdict begin\n"); start=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BeginData:%13ld %s Bytes\n",0L, compression == NoCompression ? "ASCII" : "Binary"); (void) WriteBlobString(image,buffer); stop=TellBlob(image); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n%g %g\n%g\n", (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (MagickSizeType) ((size_t) number_pixels)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (IsGrayImage(image,&image->exception) != MagickFalse))) { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n1\n%d\n", (double) image->columns,(double) image->rows,(int) (image->colorspace == CMYKColorspace)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%d\n", (int) ((compression != FaxCompression) && (compression != Group4Compression))); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image); break; } (void) Huffman2DEncodeImage(image_info,image,image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case RLECompression: default: { register unsigned char *q; /* Allocate pixel array. */ length=(size_t) number_pixels; pixels=(unsigned char *) AcquireQuantumMemory(length, sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(PixelIntensityToQuantum(p)); p++; } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (progress == MagickFalse) break; } length=(size_t) (q-pixels); if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( PixelIntensityToQuantum(p))); p++; } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (image->matte != MagickFalse)) { (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n0\n%d\n", (double) image->columns,(double) image->rows,(int) (image->colorspace == CMYKColorspace)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%d\n", (int) (compression == NoCompression)); (void) WriteBlobString(image,buffer); switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case RLECompression: default: { register unsigned char *q; /* Allocate pixel array. */ length=(size_t) number_pixels; pixels=(unsigned char *) AcquireQuantumMemory(length, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); /* Dump Packbit encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((image->matte != MagickFalse) && (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) { *q++=ScaleQuantumToChar((Quantum) QuantumRange); *q++=ScaleQuantumToChar((Quantum) QuantumRange); *q++=ScaleQuantumToChar((Quantum) QuantumRange); } else if (image->colorspace != CMYKColorspace) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); } else { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelIndex( indexes+x)); } p++; } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } length=(size_t) (q-pixels); if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((image->matte != MagickFalse) && (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) { Ascii85Encode(image,ScaleQuantumToChar((Quantum) QuantumRange)); Ascii85Encode(image,ScaleQuantumToChar((Quantum) QuantumRange)); Ascii85Encode(image,ScaleQuantumToChar((Quantum) QuantumRange)); } else if (image->colorspace != CMYKColorspace) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); } else { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); } p++; } progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } Ascii85Flush(image); break; } } } else { /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n1\n%d\n", (double) image->columns,(double) image->rows,(int) (image->colorspace == CMYKColorspace)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%d\n", (int) (compression == NoCompression)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%02X%02X%02X\n", ScaleQuantumToChar(image->colormap[i].red), ScaleQuantumToChar(image->colormap[i].green), ScaleQuantumToChar(image->colormap[i].blue)); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: default: { register unsigned char *q; /* Allocate pixel array. */ length=(size_t) number_pixels; pixels=(unsigned char *) AcquireQuantumMemory(length, sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } length=(size_t) (q-pixels); if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex( indexes+x)); progress=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (progress == MagickFalse) break; } Ascii85Flush(image); break; } } } (void) WriteBlobByte(image,'\n'); length=(size_t) (TellBlob(image)-stop); stop=TellBlob(image); offset=SeekBlob(image,start,SEEK_SET); if (offset < 0) ThrowWriterException(CorruptImageError,"ImproperImageHeader"); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BeginData:%13ld %s Bytes\n",(long) length, compression == NoCompression ? "ASCII" : "Binary"); (void) WriteBlobString(image,buffer); offset=SeekBlob(image,stop,SEEK_SET); (void) WriteBlobString(image,"%%EndData\n"); if (LocaleCompare(image_info->magick,"PS2") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 1) { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); }
static Image *ReadEMFImage(const ImageInfo *image_info, ExceptionInfo *exception) { Gdiplus::Bitmap *bitmap; Gdiplus::BitmapData bitmap_data; Gdiplus::GdiplusStartupInput startup_input; Gdiplus::Graphics *graphics; Gdiplus::Image *source; Gdiplus::Rect rect; GeometryInfo geometry_info; Image *image; MagickStatusType flags; register Quantum *q; register ssize_t x; ssize_t y; ULONG_PTR token; unsigned char *p; wchar_t fileName[MagickPathExtent]; 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); image=AcquireImage(image_info,exception); if (Gdiplus::GdiplusStartup(&token,&startup_input,NULL) != Gdiplus::Status::Ok) ThrowReaderException(CoderError, "GdiplusStartupFailed"); MultiByteToWideChar(CP_UTF8,0,image->filename,-1,fileName,MagickPathExtent); source=Gdiplus::Image::FromFile(fileName); if (source == (Gdiplus::Image *) NULL) { Gdiplus::GdiplusShutdown(token); ThrowReaderException(FileOpenError,"UnableToOpenFile"); } image->resolution.x=source->GetHorizontalResolution(); image->resolution.y=source->GetVerticalResolution(); image->columns=(size_t) source->GetWidth(); image->rows=(size_t) source->GetHeight(); if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0)) { image->columns=(size_t) floor((Gdiplus::REAL) source->GetWidth() / source->GetHorizontalResolution() * image->resolution.x + 0.5); image->rows=(size_t)floor((Gdiplus::REAL) source->GetHeight() / source->GetVerticalResolution() * image->resolution.y + 0.5); } } bitmap=new Gdiplus::Bitmap((INT) image->columns,(INT) image->rows, PixelFormat32bppARGB); graphics=Gdiplus::Graphics::FromImage(bitmap); graphics->SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic); graphics->SetSmoothingMode(Gdiplus::SmoothingModeHighQuality); graphics->SetTextRenderingHint(Gdiplus::TextRenderingHintClearTypeGridFit); graphics->Clear(Gdiplus::Color((BYTE) ScaleQuantumToChar( image->background_color.alpha),(BYTE) ScaleQuantumToChar( image->background_color.red),(BYTE) ScaleQuantumToChar( image->background_color.green),(BYTE) ScaleQuantumToChar( image->background_color.blue))); graphics->DrawImage(source,0,0,(INT) image->columns,(INT) image->rows); delete graphics; delete source; rect=Gdiplus::Rect(0,0,(INT) image->columns,(INT) image->rows); if (bitmap->LockBits(&rect,Gdiplus::ImageLockModeRead,PixelFormat32bppARGB, &bitmap_data) != Gdiplus::Ok) { delete bitmap; Gdiplus::GdiplusShutdown(token); ThrowReaderException(FileOpenError,"UnableToReadImageData"); } image->alpha_trait=BlendPixelTrait; for (y=0; y < (ssize_t) image->rows; y++) { p=(unsigned char *) bitmap_data.Scan0+(y*abs(bitmap_data.Stride)); if (bitmap_data.Stride < 0) q=GetAuthenticPixels(image,0,image->rows-y-1,image->columns,1,exception); else q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } bitmap->UnlockBits(&bitmap_data); delete bitmap; Gdiplus::GdiplusShutdown(token); return(image); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e H T M L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method WriteHTMLImage writes an image in the HTML encoded image format. % % The format of the WriteHTMLImage method is: % % unsigned int WriteHTMLImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o status: Method WriteHTMLImage return True if the image is written. % False is returned is there is a memory shortage or if the image file % fails to write. % % o image_info: Specifies a pointer to an ImageInfo structure. % % o image: A pointer to a Image structure. % % */ Export unsigned int WriteHTMLImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], filename[MaxTextExtent], mapname[MaxTextExtent], url[MaxTextExtent]; Image *next; ImageInfo *local_info; int x, y; register char *p; register PixelPacket *q; unsigned int height, status, width; /* Open image. */ status=OpenBlob(image_info,image,WriteBinaryType); if (status == False) WriterExit(FileOpenWarning,"Unable to open file",image); CloseBlob(image); TransformRGBImage(image,RGBColorspace); *url='\0'; if ((Latin1Compare(image_info->magick,"FTP") == 0) || (Latin1Compare(image_info->magick,"HTTP") == 0)) { /* Extract URL base from filename. */ p=strrchr(image->filename,'/'); if (p) { p++; (void) strcpy(url,image_info->magick); (void) strcat(url,":"); url[Extent(url)+p-image->filename]='\0'; (void) strncat(url,image->filename,p-image->filename); (void) strcpy(image->filename,p); } } /* Refer to image map file. */ (void) strcpy(filename,image->filename); AppendImageFormat("map",filename); (void) strcpy(mapname,BaseFilename(filename)); (void) strcpy(image->filename,image_info->filename); (void) strcpy(filename,image->filename); local_info=CloneImageInfo(image_info); if (local_info == (ImageInfo *) NULL) WriterExit(FileOpenWarning,"Unable to allocate memory",image); local_info->adjoin=True; status=True; if (Latin1Compare(image_info->magick,"SHTML") != 0) { /* Open output image file. */ status=OpenBlob(image_info,image,WriteBinaryType); if (status == False) WriterExit(FileOpenWarning,"Unable to open file",image); /* Write the HTML image file. */ (void) strcpy(buffer,"<html version=\"2.0\">\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"<head>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) sprintf(buffer,"<title>%.1024s</title>\n", image->label ? image->label : BaseFilename(image->filename)); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"</head>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"<body>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"<center>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) sprintf(buffer,"<h1>%.1024s</h1>\n",image->filename); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"<br><br>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(filename,image->filename); AppendImageFormat("gif",filename); (void) sprintf(buffer, "<img ismap usemap=#%.1024s src=\"%.1024s\" border=0>\n", mapname,filename); (void) WriteBlob(image,strlen(buffer),buffer); /* Determine the size and location of each image tile. */ width=image->columns; height=image->rows; x=0; y=0; if (image->montage != (char *) NULL) (void) ParseGeometry(image->montage,&x,&y,&width,&height); /* Write an image map. */ (void) sprintf(buffer,"<map name=%.1024s>\n",mapname); (void) WriteBlob(image,strlen(buffer),buffer); (void) sprintf(buffer," <area href=""%.1024s""",url); (void) WriteBlob(image,strlen(buffer),buffer); if (image->directory == (char *) NULL) { (void) sprintf(buffer,"%.1024s shape=rect coords=0,0,%u,%u>\n", image->filename,width-1,height-1); (void) WriteBlob(image,strlen(buffer),buffer); } else for (p=image->directory; *p != '\0'; p++) if (*p != '\n') (void) WriteByte(image,*p); else { (void) sprintf(buffer," shape=rect coords=%d,%d,%d,%d>\n", x,y,x+(int) width-1,y+(int) height-1); (void) WriteBlob(image,strlen(buffer),buffer); if (*(p+1) != '\0') { (void) sprintf(buffer," <area href=""%.1024s""",url); (void) WriteBlob(image,strlen(buffer),buffer); } x+=width; if (x >= (int) image->columns) { x=0; y+=height; } } (void) strcpy(buffer,"</map>\n"); (void) WriteBlob(image,strlen(buffer),buffer); if (image->montage != (char *) NULL) { char color[MaxTextExtent] = "#000"; /* Make montage background transparent. */ q=GetPixelCache(image,0,0,1,1); if (q != (PixelPacket *) NULL) FormatString(color,HexColorFormat,q->red,q->green,q->blue); TransparentImage(image,color); } (void) strcpy(filename,image->filename); (void) strcpy(buffer,"</center>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"</body>\n"); (void) WriteBlob(image,strlen(buffer),buffer); (void) strcpy(buffer,"</html>\n"); status=WriteBlob(image,strlen(buffer),buffer); CloseBlob(image); /* Write the image as transparent GIF. */ (void) strcpy(image->filename,filename); AppendImageFormat("gif",image->filename); next=image->next; image->next=(Image *) NULL; status|=WriteGIFImage(local_info,image); image->next=next; /* Determine image map filename. */ (void) strcpy(image->filename,filename); for (p=filename+Extent(filename)-1; p > (filename+1); p--) if (*p == '.') { (void) strncpy(image->filename,filename,p-filename); image->filename[p-filename]='\0'; break; } (void) strcat(image->filename,"_map.shtml"); } /* Open image map. */ status=OpenBlob(local_info,image,WriteBinaryType); if (status == False) WriterExit(FileOpenWarning,"Unable to open file",image); DestroyImageInfo(local_info); /* Determine the size and location of each image tile. */ width=image->columns; height=image->rows; x=0; y=0; if (image->montage != (char *) NULL) (void) ParseGeometry(image->montage,&x,&y,&width,&height); /* Write an image map. */ (void) sprintf(buffer,"<map name=%.1024s>\n",mapname); (void) WriteBlob(image,strlen(buffer),buffer); (void) sprintf(buffer," <area href=""%.1024s""",url); (void) WriteBlob(image,strlen(buffer),buffer); if (image->directory == (char *) NULL) { (void) sprintf(buffer,"%.1024s shape=rect coords=0,0,%u,%u>\n", image->filename,width-1,height-1); (void) WriteBlob(image,strlen(buffer),buffer); } else for (p=image->directory; *p != '\0'; p++) if (*p != '\n') (void) WriteByte(image,*p); else { (void) sprintf(buffer," shape=rect coords=%d,%d,%d,%d>\n",x,y, x+(int) width-1,y+(int) height-1); (void) WriteBlob(image,strlen(buffer),buffer); if (*(p+1) != '\0') { (void) sprintf(buffer," <area href=""%.1024s""",url); (void) WriteBlob(image,strlen(buffer),buffer); } x+=width; if (x >= (int) image->columns) { x=0; y+=height; } } (void) strcpy(buffer,"</map>\n"); (void) WriteBlob(image,strlen(buffer),buffer); CloseBlob(image); (void) strcpy(image->filename,filename); return(status); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d Y U V I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadYUVImage() reads an image with digital YUV (CCIR 601 4:1:1, plane % or partition interlaced, or 4:2:2 plane, partition interlaced or % noninterlaced) bytes and returns it. It allocates the memory necessary % for the new Image structure and returns a pointer to the new image. % % The format of the ReadYUVImage method is: % % Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *chroma_image, *image, *resize_image; InterlaceType interlace; MagickBooleanType status; register const PixelPacket *chroma_pixels; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, horizontal_factor, vertical_factor, y; size_t quantum; unsigned char *scanline; /* Allocate image structure. */ 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); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } quantum=(size_t) (image->depth <= 8 ? 1 : 2); interlace=image_info->interlace; horizontal_factor=2; vertical_factor=2; if (image_info->sampling_factor != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->sampling_factor,&geometry_info); horizontal_factor=(ssize_t) geometry_info.rho; vertical_factor=(ssize_t) geometry_info.sigma; if ((flags & SigmaValue) == 0) vertical_factor=horizontal_factor; if ((horizontal_factor != 1) && (horizontal_factor != 2) && (vertical_factor != 1) && (vertical_factor != 2)) ThrowReaderException(CorruptImageError,"UnexpectedSamplingFactor"); } if ((interlace == UndefinedInterlace) || ((interlace == NoInterlace) && (vertical_factor == 2))) { interlace=NoInterlace; /* CCIR 4:2:2 */ if (vertical_factor == 2) interlace=PlaneInterlace; /* CCIR 4:1:1 */ } if (interlace != PartitionInterlace) { /* Open image file. */ status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Allocate memory for a scanline. */ if (interlace == NoInterlace) scanline=(unsigned char *) AcquireQuantumMemory((size_t) 2UL* image->columns+2UL,quantum*sizeof(*scanline)); else scanline=(unsigned char *) AcquireQuantumMemory(image->columns, quantum*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); do { chroma_image=CloneImage(image,(image->columns + horizontal_factor - 1) / horizontal_factor, (image->rows + vertical_factor - 1) / vertical_factor, MagickTrue,exception); if (chroma_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (interlace == PartitionInterlace) { AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *chroma_pixels; if (interlace == NoInterlace) { if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL)) (void) ReadBlob(image,(size_t) (2*quantum*image->columns),scanline); p=scanline; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; chroma_pixels=QueueAuthenticPixels(chroma_image,0,y, chroma_image->columns,1,exception); if (chroma_pixels == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=2) { SetPixelRed(chroma_pixels,0); if (quantum == 1) SetPixelGreen(chroma_pixels,ScaleCharToQuantum(*p++)); else { SetPixelGreen(chroma_pixels,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } if (quantum == 1) SetPixelRed(q,ScaleCharToQuantum(*p++)); else { SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } SetPixelGreen(q,0); SetPixelBlue(q,0); q++; SetPixelGreen(q,0); SetPixelBlue(q,0); if (quantum == 1) SetPixelBlue(chroma_pixels,ScaleCharToQuantum(*p++)); else { SetPixelBlue(chroma_pixels,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } if (quantum == 1) SetPixelRed(q,ScaleCharToQuantum(*p++)); else { SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } chroma_pixels++; q++; } } else { if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL)) (void) ReadBlob(image,(size_t) quantum*image->columns,scanline); p=scanline; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (quantum == 1) SetPixelRed(q,ScaleCharToQuantum(*p++)); else { SetPixelRed(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } SetPixelGreen(q,0); SetPixelBlue(q,0); q++; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (interlace == NoInterlace) if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("U",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } if (interlace != NoInterlace) { for (y=0; y < (ssize_t) chroma_image->rows; y++) { (void) ReadBlob(image,(size_t) quantum*chroma_image->columns,scanline); p=scanline; q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { SetPixelRed(q,0); if (quantum == 1) SetPixelGreen(q,ScaleCharToQuantum(*p++)); else { SetPixelGreen(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } SetPixelBlue(q,0); q++; } if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; } if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("V",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } for (y=0; y < (ssize_t) chroma_image->rows; y++) { (void) ReadBlob(image,(size_t) quantum*chroma_image->columns,scanline); p=scanline; q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { if (quantum == 1) SetPixelBlue(q,ScaleCharToQuantum(*p++)); else { SetPixelBlue(q,ScaleShortToQuantum(((*p) << 8) | *(p+1))); p+=2; } q++; } if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; } } /* Scale image. */ resize_image=ResizeImage(chroma_image,image->columns,image->rows, TriangleFilter,1.0,exception); chroma_image=DestroyImage(chroma_image); if (resize_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1, &resize_image->exception); if ((q == (PixelPacket *) NULL) || (chroma_pixels == (const PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(chroma_pixels)); SetPixelBlue(q,GetPixelBlue(chroma_pixels)); chroma_pixels++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } resize_image=DestroyImage(resize_image); SetImageColorspace(image,YCbCrColorspace); if (interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (interlace == NoInterlace) count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline); else count=ReadBlob(image,(size_t) quantum*image->columns,scanline); if (count != 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (count != 0); scanline=(unsigned char *) RelinquishMagickMemory(scanline); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
MagickExport MagickStatusType ParseMetaGeometry(const char *geometry,ssize_t *x, ssize_t *y,size_t *width,size_t *height) { GeometryInfo geometry_info; MagickStatusType flags; size_t former_height, former_width; /* Ensure the image geometry is valid. */ assert(x != (ssize_t *) NULL); assert(y != (ssize_t *) NULL); assert(width != (size_t *) NULL); assert(height != (size_t *) NULL); if ((geometry == (char *) NULL) || (*geometry == '\0')) return(NoValue); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",geometry); /* Parse geometry using GetGeometry. */ SetGeometryInfo(&geometry_info); former_width=(*width); former_height=(*height); flags=GetGeometry(geometry,x,y,width,height); if ((flags & PercentValue) != 0) { MagickStatusType flags; PointInfo scale; /* Geometry is a percentage of the image size. */ flags=ParseGeometry(geometry,&geometry_info); scale.x=geometry_info.rho; if ((flags & RhoValue) == 0) scale.x=100.0; scale.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) scale.y=scale.x; *width=(size_t) floor(scale.x*former_width/100.0+0.5); if (*width == 0) *width=1; *height=(size_t) floor(scale.y*former_height/100.0+0.5); if (*height == 0) *height=1; former_width=(*width); former_height=(*height); } if (((flags & AspectValue) == 0) && ((*width != former_width) || (*height != former_height))) { MagickRealType scale_factor; /* Respect aspect ratio of the image. */ if ((former_width == 0) || (former_height == 0)) scale_factor=1.0; else if (((flags & RhoValue) != 0) && (flags & SigmaValue) != 0) { scale_factor=(MagickRealType) *width/(MagickRealType) former_width; if ((flags & MinimumValue) == 0) { if (scale_factor > ((MagickRealType) *height/ (MagickRealType) former_height)) scale_factor=(MagickRealType) *height/(MagickRealType) former_height; } else if (scale_factor < ((MagickRealType) *height/ (MagickRealType) former_height)) scale_factor=(MagickRealType) *height/(MagickRealType) former_height; } else if ((flags & RhoValue) != 0) { scale_factor=(MagickRealType) *width/(MagickRealType) former_width; if (((flags & MinimumValue) != 0) && (scale_factor < ((MagickRealType) *width/ (MagickRealType) former_height))) scale_factor=(MagickRealType) *width/(MagickRealType) former_height; } else { scale_factor=(MagickRealType) *height/(MagickRealType) former_height; if (((flags & MinimumValue) != 0) && (scale_factor < ((MagickRealType) *height/ (MagickRealType) former_width))) scale_factor=(MagickRealType) *height/(MagickRealType) former_width; } *width=MagickMax((size_t) floor(scale_factor*former_width+0.5), 1UL); *height=MagickMax((size_t) floor(scale_factor*former_height+0.5), 1UL); } if ((flags & GreaterValue) != 0) { if (former_width < *width) *width=former_width; if (former_height < *height) *height=former_height; } if ((flags & LessValue) != 0) { if (former_width > *width) *width=former_width; if (former_height > *height) *height=former_height; } if ((flags & AreaValue) != 0) { MagickRealType area, distance; PointInfo scale; /* Geometry is a maximum area in pixels. */ (void) ParseGeometry(geometry,&geometry_info); area=geometry_info.rho; distance=sqrt((double) former_width*former_height); scale.x=(double) former_width/(double) (distance/sqrt((double) area)); scale.y=(double) former_height/(double) (distance/sqrt((double) area)); if ((scale.x < (double) *width) || (scale.y < (double) *height)) { *width=(size_t) (former_width/(distance/sqrt((double) area))); *height=(size_t) (former_height/(distance/ sqrt((double) area))); } former_width=(*width); former_height=(*height); } return(flags); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T E X T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTEXTImage() reads a text file and returns it as an image. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadTEXTImage method is: % % Image *ReadTEXTImage(const ImageInfo *image_info,Image *image, % char *text,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o text: the text storage buffer. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image, char *text,ExceptionInfo *exception) { char filename[MaxTextExtent], geometry[MaxTextExtent], *p; DrawInfo *draw_info; Image *texture; MagickBooleanType status; PointInfo delta; RectangleInfo page; ssize_t offset; TypeMetric metrics; /* 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); /* Set the page geometry. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } page.width=612; page.height=792; page.x=43; page.y=43; if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); /* Initialize Image structure. */ image->columns=(size_t) floor((((double) page.width*image->x_resolution)/ delta.x)+0.5); image->rows=(size_t) floor((((double) page.height*image->y_resolution)/ delta.y)+0.5); image->page.x=0; image->page.y=0; texture=(Image *) NULL; if (image_info->texture != (char *) NULL) { ImageInfo *read_info; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->filename,image_info->texture, MaxTextExtent); texture=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); } /* Annotate the text image. */ (void) SetImageBackgroundColor(image); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,image_info->filename); (void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x, (long) page.y); (void) CloneString(&draw_info->geometry,geometry); status=GetTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) ThrowReaderException(TypeError,"UnableToGetTypeMetrics"); page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); (void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x, (long) page.y); (void) CloneString(&draw_info->geometry,geometry); (void) CopyMagickString(filename,image_info->filename,MaxTextExtent); if (*draw_info->text != '\0') *draw_info->text='\0'; p=text; for (offset=2*page.y; p != (char *) NULL; ) { /* Annotate image with text. */ (void) ConcatenateString(&draw_info->text,text); (void) ConcatenateString(&draw_info->text,"\n"); offset+=(ssize_t) (metrics.ascent-metrics.descent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,offset,image->rows); if (status == MagickFalse) break; } p=ReadBlobString(image,text); if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) continue; if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture); (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); } (void) AnnotateImage(image,draw_info); if (p == (char *) NULL) break; /* Page is full-- allocate next image structure. */ *draw_info->text='\0'; offset=2*page.y; AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image->next->columns=image->columns; image->next->rows=image->rows; image=SyncNextImageInList(image); (void) CopyMagickString(image->filename,filename,MaxTextExtent); (void) SetImageBackgroundColor(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture); (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); } (void) AnnotateImage(image,draw_info); if (texture != (Image *) NULL) texture=DestroyImage(texture); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
/* Extern: rm_sync_image_options Purpose: Propagate ImageInfo values to the Image Ref: SyncImageSettings (in mogrify.c) */ void rm_sync_image_options(Image *image, Info *info) { MagickStatusType flags; GeometryInfo geometry_info; const char *option; // The option strings will be set only when their attribute values were // set in the optional argument block. option = GetImageOption(info,"background"); if (option) { image->background_color = info->background_color; } option = GetImageOption(info,"bordercolor"); if (option) { image->border_color = info->border_color; } if (info->colorspace != UndefinedColorspace) { image->colorspace = info->colorspace; } if (info->compression != UndefinedCompression) { image->compression = info->compression; } option = GetImageOption(info, "delay"); if (option) { image->delay = strtoul(option, NULL, 0); } if (info->density) { flags = ParseGeometry(info->density, &geometry_info); image->x_resolution = geometry_info.rho; image->y_resolution = geometry_info.sigma; if ((flags & SigmaValue) == 0) { image->y_resolution = image->x_resolution; } } if (info->depth != 0) { image->depth = info->depth; } option = GetImageOption(info, "dispose"); if (option) { image->dispose = rm_dispose_to_enum(option); } if (info->extract) { ParseAbsoluteGeometry(info->extract, &image->extract_info); } if (info->fuzz != 0.0) { image->fuzz = info->fuzz; } option = GetImageOption(info, "gravity"); if (option) { image->gravity = rm_gravity_to_enum(option); } if (info->interlace != NoInterlace) { image->interlace = info->interlace; } option = GetImageOption(info,"mattecolor"); if (option) { image->matte_color = info->matte_color; } if (info->orientation != UndefinedOrientation) { image->orientation = info->orientation; } if (info->page) { (void)ParseAbsoluteGeometry(info->page, &image->page); } if (info->quality != 0UL) { image->quality = info->quality; } option = GetImageOption(info, "scene"); if (option) { image->scene = info->scene; } option = GetImageOption(info, "tile-offset"); if (option) { (void)ParseAbsoluteGeometry(option, &image->tile_offset); } option = GetImageOption(info, "transparent"); if (option) { image->transparent_color = info->transparent_color; } #if defined(HAVE_ST_TYPE) if (info->type != UndefinedType) { image->type = info->type; } #endif if (info->units != UndefinedResolution) { if (image->units != info->units) { switch (image->units) { case PixelsPerInchResolution: { if (info->units == PixelsPerCentimeterResolution) { image->x_resolution /= 2.54; image->y_resolution /= 2.54; } break; } case PixelsPerCentimeterResolution: { if (info->units == PixelsPerInchResolution) { image->x_resolution *= 2.54; image->y_resolution *= 2.54; } break; } default: break; } } image->units = info->units; } #if defined(HAVE_SETIMAGEARTIFACT) copy_options(image, info); #endif }
void CMiniMap::ConfigCommand(const std::string& line) { const vector<string> words = CSimpleParser::Tokenize(line, 1); if (words.empty()) { return; } const string command = StringToLower(words[0]); if (command == "fullproxy") { if (words.size() >= 2) { fullProxy = !!atoi(words[1].c_str()); } else { fullProxy = !fullProxy; } } else if (command == "icons") { if (words.size() >= 2) { useIcons = !!atoi(words[1].c_str()); } else { useIcons = !useIcons; } } else if (command == "unitexp") { if (words.size() >= 2) { unitExponent = atof(words[1].c_str()); } UpdateGeometry(); } else if (command == "unitsize") { if (words.size() >= 2) { unitBaseSize = atof(words[1].c_str()); } unitBaseSize = std::max(0.0f, unitBaseSize); UpdateGeometry(); } else if (command == "drawcommands") { if (words.size() >= 2) { drawCommands = std::max(0, atoi(words[1].c_str())); } else { drawCommands = (drawCommands > 0) ? 0 : 1; } } else if (command == "drawprojectiles") { if (words.size() >= 2) { drawProjectiles = !!atoi(words[1].c_str()); } else { drawProjectiles = !drawProjectiles; } } else if (command == "simplecolors") { if (words.size() >= 2) { simpleColors = !!atoi(words[1].c_str()); } else { simpleColors = !simpleColors; } } // the following commands can not be used in dualscreen mode if (gu->dualScreenMode) { return; } if ((command == "geo") || (command == "geometry")) { if (words.size() < 2) { return; } ParseGeometry(words[1]); UpdateGeometry(); } else if ((command == "min") || (command == "minimize")) { if (words.size() >= 2) { minimized = !!atoi(words[1].c_str()); } else { minimized = !minimized; } } else if ((command == "max") || (command == "maximize") || (command == "maxspect")) { bool newMax = maximized; if (words.size() >= 2) { newMax = !!atoi(words[1].c_str()); } else { newMax = !newMax; } if (newMax != maximized) { ToggleMaximized(command == "maxspect"); } } }
MAGICK_NET_EXPORT MagickStatusType MagickGeometry_Initialize(GeometryInfo *instance, const char *geometry) { return ParseGeometry(geometry, instance); }
static MagickBooleanType WritePCLImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MaxTextExtent]; const char *option; MagickBooleanType status; MagickOffsetType scene; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t density, length, one, packets; ssize_t y; unsigned char bits_per_pixel, *compress_pixels, *pixels, *previous_pixels; /* Open output 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); density=75; if (image_info->density != (char *) NULL) { GeometryInfo geometry; (void) ParseGeometry(image_info->density,&geometry); density=(size_t) geometry.rho; } scene=0; one=1; do { if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); /* Initialize the printer. */ (void) WriteBlobString(image,"\033E"); /* printer reset */ (void) WriteBlobString(image,"\033*r3F"); /* set presentation mode */ (void) FormatLocaleString(buffer,MaxTextExtent,"\033*r%.20gs%.20gT", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"\033*t%.20gR",(double) density); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"\033&l0E"); /* top margin 0 */ if (IsImageMonochrome(image,exception) != MagickFalse) { /* Monochrome image: use default printer monochrome setup. */ bits_per_pixel=1; } else if (image->storage_class == DirectClass) { /* DirectClass image. */ bits_per_pixel=24; (void) WriteBlobString(image,"\033*v6W"); /* set color mode */ (void) WriteBlobByte(image,0); /* RGB */ (void) WriteBlobByte(image,3); /* direct by pixel */ (void) WriteBlobByte(image,0); /* bits per index (ignored) */ (void) WriteBlobByte(image,8); /* bits per red component */ (void) WriteBlobByte(image,8); /* bits per green component */ (void) WriteBlobByte(image,8); /* bits per blue component */ } else { /* Colormapped image. */ bits_per_pixel=8; (void) WriteBlobString(image,"\033*v6W"); /* set color mode... */ (void) WriteBlobByte(image,0); /* RGB */ (void) WriteBlobByte(image,1); /* indexed by pixel */ (void) WriteBlobByte(image,bits_per_pixel); /* bits per index */ (void) WriteBlobByte(image,8); /* bits per red component */ (void) WriteBlobByte(image,8); /* bits per green component */ (void) WriteBlobByte(image,8); /* bits per blue component */ for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MaxTextExtent, "\033*v%da%db%dc%.20gI", ScaleQuantumToChar(image->colormap[i].red), ScaleQuantumToChar(image->colormap[i].green), ScaleQuantumToChar(image->colormap[i].blue),(double) i); (void) WriteBlobString(image,buffer); } for (one=1; i < (ssize_t) (one << bits_per_pixel); i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"\033*v%.20gI", (double) i); (void) WriteBlobString(image,buffer); } } option=GetImageOption(image_info,"pcl:fit-to-page"); if ((option != (const char *) NULL) && (IsMagickTrue(option) != MagickFalse)) (void) WriteBlobString(image,"\033*r3A"); else (void) WriteBlobString(image,"\033*r1A"); /* start raster graphics */ (void) WriteBlobString(image,"\033*b0Y"); /* set y offset */ length=(image->columns*bits_per_pixel+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(length+1,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(pixels,0,(length+1)*sizeof(*pixels)); compress_pixels=(unsigned char *) NULL; previous_pixels=(unsigned char *) NULL; switch (image->compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,"\033*b0M"); (void) WriteBlobString(image,buffer); break; } case RLECompression: { compress_pixels=(unsigned char *) AcquireQuantumMemory(length+256, sizeof(*compress_pixels)); if (compress_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(compress_pixels,0,(length+256)* sizeof(*compress_pixels)); (void) FormatLocaleString(buffer,MaxTextExtent,"\033*b2M"); (void) WriteBlobString(image,buffer); break; } default: { compress_pixels=(unsigned char *) AcquireQuantumMemory(3*length+256, sizeof(*compress_pixels)); if (compress_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(compress_pixels,0,(3*length+256)* sizeof(*compress_pixels)); previous_pixels=(unsigned char *) AcquireQuantumMemory(length+1, sizeof(*previous_pixels)); if (previous_pixels == (unsigned char *) NULL) { compress_pixels=(unsigned char *) RelinquishMagickMemory( compress_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(previous_pixels,0,(length+1)* sizeof(*previous_pixels)); (void) FormatLocaleString(buffer,MaxTextExtent,"\033*b3M"); (void) WriteBlobString(image,buffer); break; } } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (bits_per_pixel) { case 1: { register unsigned char bit, byte; /* Monochrome image. */ bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelIntensity(image,p) < ((MagickRealType) QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) *q++=byte << (8-bit); break; } case 8: { /* Colormapped image. */ for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } break; } case 24: case 32: { /* Truecolor image. */ for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } break; } } switch (image->compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,"\033*b%.20gW", (double) length); (void) WriteBlobString(image,buffer); (void) WriteBlob(image,length,pixels); break; } case RLECompression: { packets=PCLPackbitsCompressImage(length,pixels,compress_pixels); (void) FormatLocaleString(buffer,MaxTextExtent,"\033*b%.20gW", (double) packets); (void) WriteBlobString(image,buffer); (void) WriteBlob(image,packets,compress_pixels); break; } default: { if (y == 0) for (i=0; i < (ssize_t) length; i++) previous_pixels[i]=(~pixels[i]); packets=PCLDeltaCompressImage(length,previous_pixels,pixels, compress_pixels); (void) FormatLocaleString(buffer,MaxTextExtent,"\033*b%.20gW", (double) packets); (void) WriteBlobString(image,buffer); (void) WriteBlob(image,packets,compress_pixels); (void) CopyMagickMemory(previous_pixels,pixels,length* sizeof(*pixels)); break; } } } (void) WriteBlobString(image,"\033*rB"); /* end graphics */ switch (image->compression) { case NoCompression: break; case RLECompression: { compress_pixels=(unsigned char *) RelinquishMagickMemory( compress_pixels); break; } default: { previous_pixels=(unsigned char *) RelinquishMagickMemory( previous_pixels); compress_pixels=(unsigned char *) RelinquishMagickMemory( compress_pixels); break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"\033E"); (void) CloseBlob(image); return(MagickTrue); }
MagickExport MagickBooleanType GradientImage(Image *image, const GradientType type,const SpreadMethod method,const StopInfo *stops, const size_t number_stops,ExceptionInfo *exception) { const char *artifact; DrawInfo *draw_info; GeometryInfo geometry_info; GradientInfo *gradient; MagickBooleanType status; MagickStatusType flags; /* Set gradient start-stop end points. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(stops != (const StopInfo *) NULL); assert(number_stops > 0); draw_info=AcquireDrawInfo(); gradient=(&draw_info->gradient); gradient->type=type; gradient->bounding_box.width=image->columns; gradient->bounding_box.height=image->rows; artifact=GetImageArtifact(image,"gradient:bounding-box"); if (artifact != (const char *) NULL) (void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box); gradient->gradient_vector.x2=(double) image->columns-1.0; gradient->gradient_vector.y2=(double) image->rows-1.0; if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0)) gradient->gradient_vector.x2=0.0; artifact=GetImageArtifact(image,"gradient:vector"); if (artifact != (const char *) NULL) { flags=ParseGeometry(artifact,&geometry_info); gradient->gradient_vector.x1=geometry_info.rho; if ((flags & SigmaValue) != 0) gradient->gradient_vector.y1=geometry_info.sigma; if ((flags & XiValue) != 0) gradient->gradient_vector.x2=geometry_info.xi; if ((flags & PsiValue) != 0) gradient->gradient_vector.y2=geometry_info.psi; } gradient->center.x=(double) gradient->gradient_vector.x2/2.0; gradient->center.y=(double) gradient->gradient_vector.y2/2.0; artifact=GetImageArtifact(image,"gradient:center"); if (artifact != (const char *) NULL) { flags=ParseGeometry(artifact,&geometry_info); gradient->center.x=geometry_info.rho; if ((flags & SigmaValue) != 0) gradient->center.y=geometry_info.sigma; } gradient->radius=MagickMax(gradient->center.x,gradient->center.y); artifact=GetImageArtifact(image,"gradient:radius"); if (artifact != (const char *) NULL) gradient->radius=StringToDouble(artifact,(char **) NULL); gradient->spread=method; /* Define the gradient to fill between the stops. */ gradient->number_stops=number_stops; gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops, sizeof(*gradient->stops)); if (gradient->stops == (StopInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) CopyMagickMemory(gradient->stops,stops,(size_t) number_stops* sizeof(*stops)); /* Draw a gradient on the image. */ status=DrawGradientImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); return(status); }
Export Image *MontageImages(const Image *images,const MontageInfo *montage_info) { #define MontageImageText " Creating visual image directory... " #define TileImageText " Creating image tiles... " AnnotateInfo *annotate_info; char geometry[MaxTextExtent]; FrameInfo frame_info; Image *image, **image_list, **master_list, *montage_image, *texture, *tiled_image; ImageInfo *local_info; int x, x_offset, y, y_offset; MonitorHandler handler; register int i; register PixelPacket *q; RectangleInfo bounding_box, tile_info; unsigned int border_width, bevel_width, concatenate, count, font_height, height, images_per_page, max_height, number_images, number_lines, tile, tiles, tiles_per_column, tiles_per_row, tiles_per_page, title_offset, total_tiles, width; assert(images != (Image *) NULL); assert(montage_info != (MontageInfo *) NULL); /* Convert image list to an image group. */ image_list=ListToGroupImage(images,&number_images); if (image_list == (Image **) NULL) { MagickWarning(ResourceLimitWarning,"Unable to montage image_list", "Memory allocation failed"); return((Image *) NULL); } master_list=image_list; /* Create image tiles. */ for (tile=0; tile < number_images; tile++) { handler=SetMonitorHandler((MonitorHandler) NULL); width=image_list[tile]->columns; height=image_list[tile]->rows; x=0; y=0; (void) ParseImageGeometry(montage_info->geometry,&x,&y,&width,&height); image_list[tile]->orphan=True; tiled_image=ZoomImage(image_list[tile],width,height); if (tiled_image == (Image *) NULL) { for (i=0; i < (int) tile; i++) DestroyImage(image_list[i]); (void) SetMonitorHandler(handler); return((Image *) NULL); } image_list[tile]=tiled_image; (void) SetMonitorHandler(handler); ProgressMonitor(TileImageText,tile,number_images); } /* Sort image_list by increasing tile number. */ for (tile=0; tile < number_images; tile++) if (image_list[tile]->scene == 0) break; if (tile == number_images) qsort((void *) image_list,number_images,sizeof(Image *), (int (*)(const void *, const void *)) SceneCompare); /* Determine tiles per row and column. */ tiles_per_row=1; tiles_per_column=1; while ((tiles_per_row*tiles_per_column) < number_images) { tiles_per_row++; tiles_per_column++; } if (montage_info->tile != (char *) NULL) { tiles_per_column=number_images; x=0; y=0; (void) ParseGeometry(montage_info->tile,&x,&y,&tiles_per_row, &tiles_per_column); } /* Determine tile sizes. */ border_width=montage_info->border_width; bevel_width=0; if (montage_info->frame != (char *) NULL) { int flags; frame_info.width=0; frame_info.height=0; frame_info.outer_bevel=0; frame_info.inner_bevel=0; flags=ParseGeometry(montage_info->frame,&frame_info.outer_bevel, &frame_info.inner_bevel,&frame_info.width,&frame_info.height); if ((flags & HeightValue) == 0) frame_info.height=frame_info.width; if ((flags & XValue) == 0) frame_info.outer_bevel=(frame_info.width >> 2)+1; if ((flags & YValue) == 0) frame_info.inner_bevel=frame_info.outer_bevel; frame_info.x=frame_info.width; frame_info.y=frame_info.height; bevel_width=Max(frame_info.inner_bevel,frame_info.outer_bevel); border_width=Max(frame_info.width,frame_info.height); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A C H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMPCImage() reads an Magick Persistent Cache image file and returns % it. It allocates the memory necessary for the new Image structure and % returns a pointer to the new image. % % The format of the ReadMPCImage method is: % % Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register long i; size_t length; ssize_t count; StringInfo *profile; unsigned long depth, quantum_depth; /* 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); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); quantum_depth=MAGICKCORE_QUANTUM_DEPTH; image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ p=keyword; do { if (isspace((int) ((unsigned char) c)) != 0) break; if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); *p++=(char) c; c=ReadBlobByte(image); if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,MaxTextExtent); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { long storage_class; storage_class=ParseMagickOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { long colorspace; colorspace=ParseMagickOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { long compression; compression=ParseMagickOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { long dispose; dispose=ParseMagickOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { long endian; endian=ParseMagickOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"matte") == 0) { long matte; matte=ParseMagickOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble(options); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { long matte; matte=ParseMagickOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { long orientation; orientation=ParseMagickOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=AcquireStringInfo((size_t) StringToLong(options)); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"quantum-depth") == 0) { quantum_depth=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { long rendering_intent; rendering_intent=ParseMagickOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(long) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { long type; type=ParseMagickOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { long units; units=ParseMagickOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (quantum_depth != MAGICKCORE_QUANTUM_DEPTH) ThrowReaderException(CacheError,"InconsistentPersistentCacheDepth"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=colormap; switch (depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (long) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (long) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned long pixel; for (i=0; i < (long) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
ngx_int_t ngx_http_small_light_imagemagick_process(ngx_http_request_t *r, ngx_http_small_light_ctx_t *ctx) { ngx_http_small_light_imagemagick_ctx_t *ictx; ngx_http_small_light_image_size_t sz; MagickBooleanType status; int rmprof_flg, progressive_flg, cmyk2rgb_flg; double iw, ih, q; char *unsharp, *sharpen, *blur, *of, *of_orig; MagickWand *trans_wand, *canvas_wand; DrawingWand *border_wand; PixelWand *bg_color, *canvas_color, *border_color; GeometryInfo geo; ngx_fd_t fd; MagickWand *icon_wand; u_char *p, *embedicon; size_t embedicon_path_len, embedicon_len, sled_image_size; ngx_int_t type; u_char jpeg_size_opt[32], crop_geo[128], size_geo[128], embedicon_path[256]; ColorspaceType color_space; #if MagickLibVersion >= 0x690 int autoorient_flg; #endif status = MagickFalse; ictx = (ngx_http_small_light_imagemagick_ctx_t *)ctx->ictx; /* adjust image size */ ngx_http_small_light_calc_image_size(r, ctx, &sz, 10000.0, 10000.0); /* prepare */ if (sz.jpeghint_flg != 0) { p = ngx_snprintf((u_char *)jpeg_size_opt, sizeof(jpeg_size_opt) - 1, "%dx%d", (ngx_int_t)sz.dw, (ngx_int_t)sz.dh); *p = '\0'; ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0, "jpeg_size_opt:%s", jpeg_size_opt); MagickSetOption(ictx->wand, "jpeg:size", (char *)jpeg_size_opt); } /* load image. */ status = MagickReadImageBlob(ictx->wand, (void *)ictx->image, ictx->image_len); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "couldn't read image %s:%d", __FUNCTION__, __LINE__); return NGX_ERROR; } MagickSetFirstIterator(ictx->wand); color_space = MagickGetImageColorspace(ictx->wand); /* remove all profiles */ rmprof_flg = ngx_http_small_light_parse_flag(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "rmprof")); if (rmprof_flg != 0) { status = MagickProfileImage(ictx->wand, "*", NULL, 0); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "couldn't profiling image %s:%d", __FUNCTION__, __LINE__); } } of_orig = MagickGetImageFormat(ictx->wand); status = MagickTrue; #if MagickLibVersion >= 0x690 /* auto-orient */ autoorient_flg = ngx_http_small_light_parse_flag(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "autoorient")); if (autoorient_flg != 0) { status = MagickAutoOrientImage(ictx->wand); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; DestroyString(of_orig); return NGX_ERROR; } } #endif /* rotate. */ if (sz.angle) { bg_color = NewPixelWand(); PixelSetRed(bg_color, sz.cc.r / 255.0); PixelSetGreen(bg_color, sz.cc.g / 255.0); PixelSetBlue(bg_color, sz.cc.b / 255.0); PixelSetAlpha(bg_color, sz.cc.a / 255.0); switch (sz.angle) { case 90: case 180: case 270: MagickRotateImage(ictx->wand, bg_color, sz.angle); break; default: ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "image not rotated. 'angle'(%ui) must be 90 or 180 or 270. %s:%d", sz.angle, __FUNCTION__, __LINE__); break; } DestroyPixelWand(bg_color); } /* calc size. */ iw = (double)MagickGetImageWidth(ictx->wand); ih = (double)MagickGetImageHeight(ictx->wand); ngx_http_small_light_calc_image_size(r, ctx, &sz, iw, ih); /* pass through. */ if (sz.pt_flg != 0) { ctx->of = ctx->inf; DestroyString(of_orig); return NGX_OK; } /* crop, scale. */ if (sz.scale_flg != 0) { p = ngx_snprintf(crop_geo, sizeof(crop_geo) - 1, "%f!x%f!+%f+%f", sz.sw, sz.sh, sz.sx, sz.sy); *p = '\0'; p = ngx_snprintf(size_geo, sizeof(size_geo) - 1, "%f!x%f!", sz.dw, sz.dh); *p = '\0'; ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0, "crop_geo:%s", crop_geo); ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0, "size_geo:%s", size_geo); MagickResetImagePage(ictx->wand, "+0+0"); trans_wand = MagickTransformImage(ictx->wand, (char *)crop_geo, (char *)size_geo); if (trans_wand == NULL || trans_wand == ictx->wand) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; DestroyString(of_orig); return NGX_ERROR; } DestroyMagickWand(ictx->wand); ictx->wand = trans_wand; } /* create canvas then draw image to the canvas. */ if (sz.cw > 0.0 && sz.ch > 0.0) { canvas_wand = NewMagickWand(); canvas_color = NewPixelWand(); PixelSetRed(canvas_color, sz.cc.r / 255.0); PixelSetGreen(canvas_color, sz.cc.g / 255.0); PixelSetBlue(canvas_color, sz.cc.b / 255.0); PixelSetAlpha(canvas_color, sz.cc.a / 255.0); status = MagickNewImage(canvas_wand, sz.cw, sz.ch, canvas_color); DestroyPixelWand(canvas_color); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; DestroyMagickWand(canvas_wand); DestroyString(of_orig); return NGX_ERROR; } status = MagickTransformImageColorspace(canvas_wand, color_space); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; DestroyMagickWand(canvas_wand); DestroyString(of_orig); return NGX_ERROR; } status = MagickCompositeImage(canvas_wand, ictx->wand, AtopCompositeOp, sz.dx, sz.dy); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; DestroyMagickWand(canvas_wand); DestroyString(of_orig); return NGX_ERROR; } DestroyMagickWand(ictx->wand); ictx->wand = canvas_wand; } /* CMYK to sRGB */ cmyk2rgb_flg = ngx_http_small_light_parse_flag(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "cmyk2rgb")); if (cmyk2rgb_flg != 0 && color_space == CMYKColorspace) { status = MagickTransformImageColorspace(ictx->wand, sRGBColorspace); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; DestroyString(of_orig); return NGX_ERROR; } } /* effects. */ unsharp = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "unsharp"); if (ngx_strlen(unsharp) > 0) { ParseGeometry(unsharp, &geo); if (geo.rho > ctx->radius_max || geo.sigma > ctx->sigma_max) { ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "As unsharp geometry is too large, ignored. %s:%d", __FUNCTION__, __LINE__); } else { status = MagickUnsharpMaskImage(ictx->wand, geo.rho, geo.sigma, geo.xi, geo.psi); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "unsharp failed %s:%d", __FUNCTION__, __LINE__); } } } sharpen = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "sharpen"); if (ngx_strlen(sharpen) > 0) { ParseGeometry(sharpen, &geo); if (geo.rho > ctx->radius_max || geo.sigma > ctx->sigma_max) { ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "As sharpen geometry is too large, ignored. %s:%d", __FUNCTION__, __LINE__); } else { status = MagickSharpenImage(ictx->wand, geo.rho, geo.sigma); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "sharpen failed %s:%d", __FUNCTION__, __LINE__); } } } blur = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "blur"); if (ngx_strlen(blur) > 0) { ParseGeometry(blur, &geo); if (geo.rho > ctx->radius_max || geo.sigma > ctx->sigma_max) { ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "As blur geometry is too large, ignored. %s:%d", __FUNCTION__, __LINE__); } else { status = MagickBlurImage(ictx->wand, geo.rho, geo.sigma); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "blur failed %s:%d", __FUNCTION__, __LINE__); } } } /* border. */ if (sz.bw > 0.0 || sz.bh > 0.0) { border_wand = NewDrawingWand(); border_color = NewPixelWand(); PixelSetRed(border_color, sz.bc.r / 255.0); PixelSetGreen(border_color, sz.bc.g / 255.0); PixelSetBlue(border_color, sz.bc.b / 255.0); PixelSetAlpha(border_color, sz.bc.a / 255.0); DrawSetFillColor(border_wand, border_color); DrawSetStrokeColor(border_wand, border_color); DrawSetStrokeWidth(border_wand, 1); if (sz.cw > 0.0 && sz.ch > 0.0) { DrawRectangle(border_wand, 0, 0, sz.cw - 1, sz.bh - 1); DrawRectangle(border_wand, 0, 0, sz.bw - 1, sz.ch - 1); DrawRectangle(border_wand, 0, sz.ch - sz.bh, sz.cw - 1, sz.ch - 1); DrawRectangle(border_wand, sz.cw - sz.bw, 0, sz.cw - 1, sz.ch - 1); } else { DrawRectangle(border_wand, 0, 0, sz.dw - 1, sz.bh - 1); DrawRectangle(border_wand, 0, 0, sz.bw - 1, sz.dh - 1); DrawRectangle(border_wand, 0, sz.dh - sz.bh, sz.dw - 1, sz.dh - 1); DrawRectangle(border_wand, sz.dw - sz.bw, 0, sz.dw - 1, sz.dh - 1); } MagickDrawImage(ictx->wand, border_wand); DestroyPixelWand(border_color); DestroyDrawingWand(border_wand); } /* embed icon */ embedicon = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "embedicon"); if (ctx->material_dir->len > 0 && ngx_strlen(embedicon) > 0) { if (ngx_strstrn((u_char *)embedicon, "/", 1 - 1)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "invalid parameter 'embedicon':%s %s:%d", embedicon, __FUNCTION__, __LINE__); DestroyString(of_orig); return NGX_ERROR; } embedicon_len = ngx_strlen(embedicon); embedicon_path_len = ctx->material_dir->len + ngx_strlen("/") + embedicon_len; if (embedicon_path_len > sizeof(embedicon_path) - 1) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "embedicon path is too long. maximun value is %z %s:%d", sizeof(embedicon_path) - 1, __FUNCTION__, __LINE__); DestroyString(of_orig); return NGX_ERROR; } p = embedicon_path; p = ngx_cpystrn(p, ctx->material_dir->data, ctx->material_dir->len + 1); p = ngx_cpystrn(p, (u_char *)"/", 1 + 1); p = ngx_cpystrn(p, embedicon, embedicon_len + 1); if ((fd = ngx_open_file(embedicon_path, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0)) == NGX_INVALID_FILE) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to open embeddedicon file:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); DestroyString(of_orig); return NGX_ERROR; } if (ngx_close_file(fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to close:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); DestroyString(of_orig); return NGX_ERROR; } if (ngx_strstrn(embedicon_path, "..", 2 - 1)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "invalid embeddedicon_path:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); DestroyString(of_orig); return NGX_ERROR; } icon_wand = NewMagickWand(); if (MagickReadImage(icon_wand, (char *)embedicon_path) == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to read embed icon image file:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); DestroyMagickWand(icon_wand); DestroyString(of_orig); return NGX_ERROR; } MagickCompositeImageChannel(ictx->wand, AllChannels, icon_wand, OverCompositeOp, sz.ix, sz.iy); DestroyMagickWand(icon_wand); } /* set params. */ q = ngx_http_small_light_parse_double(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "q")); if (q > 0.0) { MagickSetImageCompressionQuality(ictx->wand, q); } progressive_flg = ngx_http_small_light_parse_flag(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "progressive")); if (progressive_flg != 0) { MagickSetInterlaceScheme(ictx->wand, LineInterlace); } of = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "of"); if (ngx_strlen(of) > 0) { type = ngx_http_small_light_type(of); if (type == NGX_HTTP_SMALL_LIGHT_IMAGE_NONE) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "of is invalid(%s) %s:%d", of, __FUNCTION__, __LINE__); of = (char *)ngx_http_small_light_image_exts[ictx->type - 1]; } else if (type == NGX_HTTP_SMALL_LIGHT_IMAGE_WEBP) { #if defined(MAGICKCORE_WEBP_DELEGATE) ictx->type = type; #else ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "WebP is not supported %s:%d", __FUNCTION__, __LINE__); of = (char *)ngx_http_small_light_image_exts[ictx->type - 1]; #endif } else { ictx->type = type; } MagickSetFormat(ictx->wand, of); ctx->of = ngx_http_small_light_image_types[ictx->type - 1]; } else { MagickSetFormat(ictx->wand, of_orig); ctx->of = ctx->inf; } DestroyString(of_orig); ctx->content = MagickGetImageBlob(ictx->wand, &sled_image_size); ctx->content_length = sled_image_size; ngx_pfree(r->pool, ctx->content_orig); ictx->complete = 1; return NGX_OK; }
static MagickBooleanType WritePS3Image(const ImageInfo *image_info,Image *image) { static const char *PostscriptProlog[]= { "/ByteStreamDecodeFilter", "{", " /z exch def", " /r exch def", " /c exch def", " z "PS3_NoCompression" eq { /ASCII85Decode filter } if", " z "PS3_FaxCompression" eq", " {", " <<", " /K "CCITTParam, " /Columns c", " /Rows r", " >>", " /CCITTFaxDecode filter", " } if", " z "PS3_JPEGCompression" eq { /DCTDecode filter } if", " z "PS3_LZWCompression" eq { /LZWDecode filter } if", " z "PS3_RLECompression" eq { /RunLengthDecode filter } if", " z "PS3_ZipCompression" eq { /FlateDecode filter } if", "} bind def", "", "/DirectClassImageDict", "{", " colorspace "PS3_RGBColorspace" eq", " {", " /DeviceRGB setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /DataSource pixel_stream", " /MultipleDataSources false", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " /Decode [0 1 0 1 0 1]", " >>", " }", " {", " /DeviceCMYK setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /DataSource pixel_stream", " /MultipleDataSources false", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " /Decode", " compression "PS3_JPEGCompression" eq", " { [1 0 1 0 1 0 1 0] }", " { [0 1 0 1 0 1 0 1] }", " ifelse", " >>", " }", " ifelse", "} bind def", "", "/PseudoClassImageDict", "{", " % Colors in colormap image.", " currentfile buffer readline pop", " token pop /colors exch def pop", " colors 0 eq", " {", " % Depth of grayscale image.", " currentfile buffer readline pop", " token pop /bits exch def pop", " /DeviceGray setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent bits", " /Decode [0 1]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " /DataSource pixel_stream", " >>", " }", " {", " % RGB colormap.", " /colormap colors 3 mul string def", " compression "PS3_NoCompression" eq", " { currentfile /ASCII85Decode filter colormap readstring pop pop }", " { currentfile colormap readstring pop pop }", " ifelse", " [ /Indexed /DeviceRGB colors 1 sub colormap ] setcolorspace", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 8", " /Decode [0 255]", " /ImageMatrix [columns 0 0 rows neg 0 rows]", " /DataSource pixel_stream", " >>", " }", " ifelse", "} bind def", "", "/NonMaskedImageDict", "{", " class "PS3_PseudoClass" eq", " { PseudoClassImageDict }", " { DirectClassImageDict }", " ifelse", "} bind def", "", "/MaskedImageDict", "{", " <<", " /ImageType 3", " /InterleaveType 3", " /DataDict NonMaskedImageDict", " /MaskDict", " <<", " /ImageType 1", " /Width columns", " /Height rows", " /BitsPerComponent 1", " /DataSource mask_stream", " /MultipleDataSources false", " /ImageMatrix [ columns 0 0 rows neg 0 rows]", " /Decode [ 0 1 ]", " >>", " >>", "} bind def", "", "/ClipImage", "{} def", "", "/DisplayImage", "{", " /buffer 512 string def", " % Translation.", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " % Image size and font size.", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", (char *) NULL }, *PostscriptEpilog[]= { " x y scale", " % Clipping path.", " currentfile buffer readline pop", " token pop /clipped exch def pop", " % Showpage.", " currentfile buffer readline pop", " token pop /sp exch def pop", " % Image pixel size.", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " % Colorspace (RGB/CMYK).", " currentfile buffer readline pop", " token pop /colorspace exch def pop", " % Transparency.", " currentfile buffer readline pop", " token pop /alpha exch def pop", " % Stencil mask?", " currentfile buffer readline pop", " token pop /stencil exch def pop", " % Image class (direct/pseudo).", " currentfile buffer readline pop", " token pop /class exch def pop", " % Compression type.", " currentfile buffer readline pop", " token pop /compression exch def pop", " % Clip and render.", " /pixel_stream currentfile columns rows compression ByteStreamDecodeFilter def", " clipped { ClipImage } if", " alpha stencil not and", " { MaskedImageDict mask_stream resetfile }", " { NonMaskedImageDict }", " ifelse", " stencil { 0 setgray imagemask } { image } ifelse", " sp { showpage } if", "} bind def", (char *) NULL }; char buffer[MaxTextExtent], date[MaxTextExtent], **labels, page_geometry[MaxTextExtent]; CompressionType compression; const char *option, **q, *value; double pointsize; GeometryInfo geometry_info; long j; MagickBooleanType status; MagickOffsetType offset, scene, start, stop; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register long i; SegmentInfo bounds; size_t length; time_t timer; unsigned char *pixels; unsigned long page, pixel, text_size; /* Open output 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(MagickFalse); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((IsMonochromeImage(image,&image->exception) == MagickFalse) || (image->matte != MagickFalse)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif default: break; } (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); page=0; scene=0; do { /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x*=2.54; resolution.y*=2.54; } SetGeometry(image,&geometry); (void) FormatMagickString(page_geometry,MaxTextExtent,"%lux%lu", image->columns,image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatMagickString(page_geometry,MaxTextExtent,"%lux%lu%+ld%+ld", image->page.width,image->page.height,image->page.x,image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(unsigned long) (scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(unsigned long) (scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(long) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(unsigned long) (MultilineCensus(value)*pointsize+12); page++; if (page == 1) { /* Postscript header on the first page. */ if (LocaleCompare(image_info->magick,"PS3") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatMagickString(buffer,MaxTextExtent, "%%%%Creator: ImageMagick %s\n",MagickLibVersionText); (void) WriteBlobString(image,buffer); (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Title: %s\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MaxTextExtent,date); (void) FormatMagickString(buffer,MaxTextExtent, "%%%%CreationDate: %s\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+scale.x; bounds.y2=(double) geometry.y+scale.y+text_size; if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) { (void) WriteBlobString(image,"%%BoundingBox: (atend)\n"); (void) WriteBlobString(image,"%%HiResBoundingBox: (atend)\n"); } else { (void) FormatMagickString(buffer,MaxTextExtent, "%%%%BoundingBox: %g %g %g %g\n",floor(bounds.x1+0.5), floor(bounds.y1+0.5),ceil(bounds.x2-0.5),ceil(bounds.y2-0.5)); (void) WriteBlobString(image,buffer); (void) FormatMagickString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); if (image->colorspace == CMYKColorspace) (void) WriteBlobString(image, "%%DocumentProcessColors: Cyan Magenta Yellow Black\n"); else if (IsGrayImage(image,&image->exception) != MagickFalse) (void) WriteBlobString(image, "%%DocumentProcessColors: Black\n"); } /* Font resources */ value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Helvetica\n"); (void) WriteBlobString(image,"%%LanguageLevel: 3\n"); /* Pages, orientation and order. */ if (LocaleCompare(image_info->magick,"PS3") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); if (image_info->adjoin == MagickFalse) (void) CopyMagickString(buffer,"%%Pages: 1\n",MaxTextExtent); else (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Pages: %lu\n", (unsigned long) GetImageListLength(image)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); /* The static postscript procedures prolog. */ (void)WriteBlobString(image,"%%BeginProlog\n"); for (q=PostscriptProlog; *q; q++) { (void) WriteBlobString(image,*q); (void) WriteBlobByte(image,'\n'); } /* One label line for each line in label string. */ value=GetImageProperty(image,"label"); if (value != (const char *) NULL) { (void) WriteBlobString(image,"\n %% Labels.\n /Helvetica " " findfont pointsize scalefont setfont\n"); for (i=(long) MultilineCensus(value)-1; i >= 0; i--) { (void) WriteBlobString(image, " currentfile buffer readline pop token pop\n"); (void) FormatMagickString(buffer,MaxTextExtent, " 0 y %g add moveto show pop\n",i*pointsize+12); (void) WriteBlobString(image,buffer); } } /* The static postscript procedures epilog. */ for (q=PostscriptEpilog; *q; q++) { (void) WriteBlobString(image,*q); (void) WriteBlobByte(image,'\n'); } (void)WriteBlobString(image,"%%EndProlog\n"); } (void) FormatMagickString(buffer,MaxTextExtent,"%%%%Page: 1 %lu\n",page); (void) WriteBlobString(image,buffer); /* Page bounding box. */ (void) FormatMagickString(buffer,MaxTextExtent, "%%%%PageBoundingBox: %ld %ld %ld %ld\n",geometry.x,geometry.y,geometry.x+ (long) geometry.width,geometry.y+(long) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); /* Page process colors if not RGB. */ if (image->colorspace == CMYKColorspace) (void) WriteBlobString(image, "%%PageProcessColors: Cyan Magenta Yellow Black\n"); else if (IsGrayImage(image,&image->exception) != MagickFalse) (void) WriteBlobString(image,"%%PageProcessColors: Black\n"); /* Adjust document bounding box to bound page bounding box. */ if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+scale.x) > bounds.x2) bounds.x2=(double) geometry.x+scale.x; if ((double) (geometry.y+scale.y+text_size) > bounds.y2) bounds.y2=(double) geometry.y+scale.y+text_size; /* Page font resource if there's a label. */ value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%PageResources: font Helvetica\n"); /* PS clipping path from Photoshop clipping path. */ if ((image->clip_mask == (Image *) NULL) || (LocaleNCompare("8BIM:",image->clip_mask->magick_filename,5) != 0)) (void) WriteBlobString(image,"/ClipImage {} def\n"); else { const char *value; value=GetImageProperty(image,image->clip_mask->magick_filename); if (value == (const char *) NULL) return(MagickFalse); (void) WriteBlobString(image,value); (void) WriteBlobByte(image,'\n'); } /* Push a dictionary for our own def's if this an EPS. */ if (LocaleCompare(image_info->magick,"PS3") != 0) (void) WriteBlobString(image,"userdict begin\n"); /* Image mask. */ if ((image->matte != MagickFalse) && (WritePS3MaskImage(image_info,image,compression) == MagickFalse)) { (void) CloseBlob(image); return(MagickFalse); } /* Remember position of BeginData comment so we can update it. */ start=TellBlob(image); (void) FormatMagickString(buffer,MaxTextExtent, "%%%%BeginData:%13ld %s Bytes\n",0L, compression == NoCompression ? "ASCII" : "BINARY"); (void) WriteBlobString(image,buffer); stop=TellBlob(image); (void) WriteBlobString(image,"DisplayImage\n"); /* Translate, scale, and font point size. */ (void) FormatMagickString(buffer,MaxTextExtent,"%ld %ld\n%g %g\n%f\n", geometry.x,geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); /* Output labels. */ labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { if (compression != NoCompression) { for (j=0; labels[i][j] != '\0'; j++) (void) WriteBlobByte(image,(unsigned char) labels[i][j]); (void) WriteBlobByte(image,'\n'); } else { (void) WriteBlobString(image,"<~"); Ascii85Initialize(image); for (j=0; labels[i][j] != '\0'; j++) Ascii85Encode(image,(unsigned char) labels[i][j]); Ascii85Flush(image); } labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } /* Photoshop clipping path active? */ if ((image->clip_mask != (Image *) NULL) && (LocaleNCompare("8BIM:",image->clip_mask->magick_filename,5) == 0)) (void) WriteBlobString(image,"true\n"); else (void) WriteBlobString(image,"false\n"); /* Showpage for non-EPS. */ (void) WriteBlobString(image, LocaleCompare(image_info->magick,"PS3") == 0 ? "true\n" : "false\n"); /* Image columns, rows, and color space. */ (void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n%s\n", image->columns,image->rows,image->colorspace == CMYKColorspace ? PS3_CMYKColorspace : PS3_RGBColorspace); (void) WriteBlobString(image,buffer); /* Masked image? */ (void) WriteBlobString(image,image->matte != MagickFalse ? "true\n" : "false\n"); /* Render with imagemask operator? */ option=GetImageOption(image_info,"ps3:imagemask"); (void) WriteBlobString(image,((option != (const char *) NULL) && (IsMonochromeImage(image,&image->exception) != MagickFalse)) ? "true\n" : "false\n"); /* Output pixel data. */ pixels=(unsigned char *) NULL; length=0; if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image_info->type != ColorSeparationType) && (image_info->type != ColorSeparationMatteType) && (image->colorspace != CMYKColorspace) && ((IsGrayImage(image,&image->exception) != MagickFalse) || (IsMonochromeImage(image,&image->exception) != MagickFalse))) { /* Gray images. */ (void) WriteBlobString(image,PS3_PseudoClass"\n"); switch (compression) { case NoCompression: default: { (void) WriteBlobString(image,PS3_NoCompression"\n"); break; } case FaxCompression: case Group4Compression: { (void) WriteBlobString(image,PS3_FaxCompression"\n"); break; } case JPEGCompression: { (void) WriteBlobString(image,PS3_JPEGCompression"\n"); break; } case LZWCompression: { (void) WriteBlobString(image,PS3_LZWCompression"\n"); break; } case RLECompression: { (void) WriteBlobString(image,PS3_RLECompression"\n"); break; } case ZipCompression: { (void) WriteBlobString(image,PS3_ZipCompression"\n"); break; } } /* Number of colors -- 0 for single component non-color mapped data. */ (void) WriteBlobString(image,"0\n"); /* 1 bit or 8 bit components? */ (void) FormatMagickString(buffer,MaxTextExtent,"%d\n", IsMonochromeImage(image,&image->exception) != MagickFalse ? 1 : 8); (void) WriteBlobString(image,buffer); /* Image data. */ if (compression == JPEGCompression) status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); else if ((compression == FaxCompression) || (compression == Group4Compression)) { if (LocaleCompare(CCITTParam,"0") == 0) status=HuffmanEncodeImage(image_info,image,image); else status=Huffman2DEncodeImage(image_info,image,image); } else { status=SerializeImageChannel(image_info,image,&pixels,&length); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } switch (compression) { case NoCompression: default: { Ascii85Initialize(image); for (i=0; i < (long) length; i++) Ascii85Encode(image,pixels[i]); Ascii85Flush(image); status=MagickTrue; break; } case LZWCompression: { status=LZWEncodeImage(image,length,pixels); break; } case RLECompression: { status=PackbitsEncodeImage(image,length,pixels); break; } case ZipCompression: { status=ZLIBEncodeImage(image,length,pixels); break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression)) { /* Truecolor image. */ (void) WriteBlobString(image,PS3_DirectClass"\n"); switch (compression) { case NoCompression: default: { (void) WriteBlobString(image,PS3_NoCompression"\n"); break; } case RLECompression: { (void) WriteBlobString(image,PS3_RLECompression"\n"); break; } case JPEGCompression: { (void) WriteBlobString(image,PS3_JPEGCompression"\n"); break; } case LZWCompression: { (void) WriteBlobString(image,PS3_LZWCompression"\n"); break; } case ZipCompression: { (void) WriteBlobString(image,PS3_ZipCompression"\n"); break; } } /* Image data. */ if (compression == JPEGCompression) status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); else { /* Stream based compressions. */ status=SerializeImage(image_info,image,&pixels,&length); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } switch (compression) { case NoCompression: default: { Ascii85Initialize(image); for (i=0; i < (long) length; i++) Ascii85Encode(image,pixels[i]); Ascii85Flush(image); status=MagickTrue; break; } case RLECompression: { status=PackbitsEncodeImage(image,length,pixels); break; } case LZWCompression: { status=LZWEncodeImage(image,length,pixels); break; } case ZipCompression: { status=ZLIBEncodeImage(image,length,pixels); break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } } else { /* Colormapped images. */ (void) WriteBlobString(image,PS3_PseudoClass"\n"); switch (compression) { case NoCompression: default: { (void) WriteBlobString(image,PS3_NoCompression"\n"); break; } case JPEGCompression: { (void) WriteBlobString(image,PS3_JPEGCompression"\n"); break; } case RLECompression: { (void) WriteBlobString(image,PS3_RLECompression"\n"); break; } case LZWCompression: { (void) WriteBlobString(image,PS3_LZWCompression"\n"); break; } case ZipCompression: { (void) WriteBlobString(image,PS3_ZipCompression"\n"); break; } } /* Number of colors in color map. */ (void) FormatMagickString(buffer,MaxTextExtent,"%lu\n", image->colors); (void) WriteBlobString(image,buffer); /* Color map - uncompressed. */ if ((compression != NoCompression) && (compression != UndefinedCompression)) { for (i=0; i < (long) image->colors; i++) { pixel=ScaleQuantumToChar(image->colormap[i].red); (void) WriteBlobByte(image,(unsigned char) pixel); pixel=ScaleQuantumToChar(image->colormap[i].green); (void) WriteBlobByte(image,(unsigned char) pixel); pixel=ScaleQuantumToChar(image->colormap[i].blue); (void) WriteBlobByte(image,(unsigned char) pixel); } } else { Ascii85Initialize(image); for (i=0; i < (long) image->colors; i++) { pixel=ScaleQuantumToChar(image->colormap[i].red); Ascii85Encode(image,(unsigned char) pixel); pixel=ScaleQuantumToChar(image->colormap[i].green); Ascii85Encode(image,(unsigned char) pixel); pixel=ScaleQuantumToChar(image->colormap[i].blue); Ascii85Encode(image,(unsigned char) pixel); } Ascii85Flush(image); } status=SerializeImageIndexes(image_info,image,&pixels,&length); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } switch (compression) { case NoCompression: default: { Ascii85Initialize(image); for (i=0; i < (long) length; i++) Ascii85Encode(image,pixels[i]); Ascii85Flush(image); status=MagickTrue; break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); break; } case RLECompression: { status=PackbitsEncodeImage(image,length,pixels); break; } case LZWCompression: { status=LZWEncodeImage(image,length,pixels); break; } case ZipCompression: { status=ZLIBEncodeImage(image,length,pixels); break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); } (void) WriteBlobByte(image,'\n'); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } /* Update BeginData now that we know the data size. */ length=(size_t) (TellBlob(image)-stop); stop=TellBlob(image); offset=SeekBlob(image,start,SEEK_SET); if (offset < 0) ThrowWriterException(CorruptImageError,"ImproperImageHeader"); (void) FormatMagickString(buffer,MaxTextExtent, "%%%%BeginData:%13ld %s Bytes\n",(long) length, compression == NoCompression ? "ASCII" : "BINARY"); (void) WriteBlobString(image,buffer); offset=SeekBlob(image,stop,SEEK_SET); (void) WriteBlobString(image,"%%EndData\n"); /* End private dictionary if this an EPS. */ if (LocaleCompare(image_info->magick,"PS3") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 1) { (void) FormatMagickString(buffer,MaxTextExtent, "%%%%BoundingBox: %g %g %g %g\n",floor(bounds.x1+0.5), floor(bounds.y1+0.5),ceil(bounds.x2-0.5),ceil(bounds.y2-0.5)); (void) WriteBlobString(image,buffer); (void) FormatMagickString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); }
static MagickBooleanType WriteJBIGImage(const ImageInfo *image_info, Image *image) { double version; long y; MagickBooleanType status; MagickOffsetType scene; register const PixelPacket *p; register IndexPacket *indexes; register long x; register unsigned char *q; struct jbg_enc_state jbig_info; unsigned char bit, byte, *pixels; unsigned long number_packets; /* 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); version=strtod(JBG_VERSION,(char **) NULL); scene=0; do { /* Allocate pixel data. */ if (image_info->colorspace == UndefinedColorspace) (void) SetImageColorspace(image,RGBColorspace); number_packets=(image->columns+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(number_packets, image->rows*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert pixels to a bitmap. */ (void) SetImageType(image,BilevelType); q=pixels; for (y=0; y < (long) image->rows; y++) { p=AcquireImagePixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetIndexes(image); bit=0; byte=0; for (x=0; x < (long) image->columns; x++) { byte<<=1; if (PixelIntensity(p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } p++; } if (bit != 0) *q++=byte << (8-bit); if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (QuantumTick(y,image->rows) != MagickFalse)) { status=image->progress_monitor(SaveImageTag,y,image->rows, image->client_data); if (status == MagickFalse) break; } } /* Initialize JBIG info structure. */ jbg_enc_init(&jbig_info,image->columns,image->rows,1,&pixels, (void (*)(unsigned char *,size_t,void *)) JBIGEncode,image); if (image_info->scene != 0) jbg_enc_layers(&jbig_info,(int) image_info->scene); else { long sans_offset; unsigned long x_resolution, y_resolution; x_resolution=640; y_resolution=480; sans_offset=0; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->density,&geometry_info); x_resolution=geometry_info.rho; y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) y_resolution=x_resolution; } if (image->units == PixelsPerCentimeterResolution) { x_resolution*=2.54; y_resolution*=2.54; } (void) jbg_enc_lrlmax(&jbig_info,x_resolution,y_resolution); } (void) jbg_enc_lrange(&jbig_info,-1,-1); jbg_enc_options(&jbig_info,JBG_ILEAVE | JBG_SMID,JBG_TPDON | JBG_TPBON | JBG_DPON,version < 1.6 ? -1 : 0,-1,-1); /* Write JBIG image. */ jbg_enc_out(&jbig_info); jbg_enc_free(&jbig_info); pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { status=image->progress_monitor(SaveImagesTag,scene, GetImageListLength(image),image->client_data); if (status == MagickFalse) break; } scene++; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
static MagickBooleanType WriteCALSImage(const ImageInfo *image_info, Image *image) { char header[129]; Image *group4_image; ImageInfo *write_info; MagickBooleanType status; register ssize_t i; size_t density, length, orient_x, orient_y; ssize_t count; unsigned char *group4; /* Open output 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); /* Create standard CALS header. */ count=WriteCALSRecord(image,"srcdocid: NONE"); (void) count; count=WriteCALSRecord(image,"dstdocid: NONE"); count=WriteCALSRecord(image,"txtfilid: NONE"); count=WriteCALSRecord(image,"figid: NONE"); count=WriteCALSRecord(image,"srcgph: NONE"); count=WriteCALSRecord(image,"docls: NONE"); count=WriteCALSRecord(image,"rtype: 1"); orient_x=0; orient_y=0; switch (image->orientation) { case TopRightOrientation: { orient_x=180; orient_y=270; break; } case BottomRightOrientation: { orient_x=180; orient_y=90; break; } case BottomLeftOrientation: { orient_y=90; break; } case LeftTopOrientation: { orient_x=270; break; } case RightTopOrientation: { orient_x=270; orient_y=180; break; } case RightBottomOrientation: { orient_x=90; orient_y=180; break; } case LeftBottomOrientation: { orient_x=90; break; } default: { orient_y=270; } } (void) FormatLocaleString(header,MaxTextExtent,"rorient: %03ld,%03ld", (long) orient_x,(long) orient_y); count=WriteCALSRecord(image,header); (void) FormatLocaleString(header,MaxTextExtent,"rpelcnt: %06lu,%06lu", (unsigned long) image->columns,(unsigned long) image->rows); count=WriteCALSRecord(image,header); density=200; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; (void) ParseGeometry(image_info->density,&geometry_info); density=(size_t) floor(geometry_info.rho+0.5); } (void) FormatLocaleString(header,MaxTextExtent,"rdensty: %04lu", (unsigned long) density); count=WriteCALSRecord(image,header); count=WriteCALSRecord(image,"notes: NONE"); (void) ResetMagickMemory(header,' ',128); for (i=0; i < 5; i++) (void) WriteBlob(image,128,(unsigned char *) header); /* Write CALS pixels. */ write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent); group4_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (group4_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, &image->exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) { (void) CloseBlob(image); return(MagickFalse); } write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); (void) CloseBlob(image); return(status); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadImage() reads an image or image sequence from a file or file handle. % The method returns a NULL if there is a memory shortage or if the image % cannot be read. On failure, a NULL image is returned and exception % describes the reason for the failure. % % The format of the ReadImage method is: % % Image *ReadImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Read the image defined by the file or filename members of % this structure. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ReadImage(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MaxTextExtent], magick[MaxTextExtent], magick_filename[MaxTextExtent]; const char *value; const DelegateInfo *delegate_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; GeometryInfo geometry_info; Image *image, *next; ImageInfo *read_info; MagickStatusType flags, thread_support; PolicyDomain domain; PolicyRights rights; /* Determine image type from filename prefix or suffix (e.g. image.jpg). */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image_info->filename != (char *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); read_info=CloneImageInfo(image_info); (void) CopyMagickString(magick_filename,read_info->filename,MaxTextExtent); (void) SetImageInfo(read_info,0,exception); (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) CopyMagickString(magick,read_info->magick,MaxTextExtent); domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,read_info->magick) == MagickFalse) { errno=EPERM; (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, "NotAuthorized","`%s'",read_info->filename); return((Image *) NULL); } /* Call appropriate image reader based on image type. */ sans_exception=AcquireExceptionInfo(); magick_info=GetMagickInfo(read_info->magick,sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (magick_info != (const MagickInfo *) NULL) { if (GetMagickEndianSupport(magick_info) == MagickFalse) read_info->endian=UndefinedEndian; else if ((image_info->endian == UndefinedEndian) && (GetMagickRawSupport(magick_info) != MagickFalse)) { size_t lsb_first; lsb_first=1; read_info->endian=(*(char *) &lsb_first) == 1 ? LSBEndian : MSBEndian; } } if ((magick_info != (const MagickInfo *) NULL) && (GetMagickSeekableStream(magick_info) != MagickFalse)) { MagickBooleanType status; image=AcquireImage(read_info,exception); (void) CopyMagickString(image->filename,read_info->filename, MaxTextExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return((Image *) NULL); } if (IsBlobSeekable(image) == MagickFalse) { /* Coder requires a seekable stream. */ *read_info->filename='\0'; status=ImageToFile(image,read_info->filename,exception); if (status == MagickFalse) { (void) CloseBlob(image); read_info=DestroyImageInfo(read_info); image=DestroyImage(image); return((Image *) NULL); } read_info->temporary=MagickTrue; } (void) CloseBlob(image); image=DestroyImage(image); } image=NewImageList(); if (constitute_semaphore == (SemaphoreInfo *) NULL) AcquireSemaphoreInfo(&constitute_semaphore); if ((magick_info != (const MagickInfo *) NULL) && (GetImageDecoder(magick_info) != (DecodeImageHandler *) NULL)) { thread_support=GetMagickThreadSupport(magick_info); if ((thread_support & DecoderThreadSupport) == 0) LockSemaphoreInfo(constitute_semaphore); image=GetImageDecoder(magick_info)(read_info,exception); if ((thread_support & DecoderThreadSupport) == 0) UnlockSemaphoreInfo(constitute_semaphore); } else { delegate_info=GetDelegateInfo(read_info->magick,(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'", read_info->filename); if (read_info->temporary != MagickFalse) (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } /* Let our decoding delegate process the image. */ image=AcquireImage(read_info,exception); if (image == (Image *) NULL) { read_info=DestroyImageInfo(read_info); return((Image *) NULL); } (void) CopyMagickString(image->filename,read_info->filename, MaxTextExtent); *read_info->filename='\0'; if (GetDelegateThreadSupport(delegate_info) == MagickFalse) LockSemaphoreInfo(constitute_semaphore); (void) InvokeDelegate(read_info,image,read_info->magick,(char *) NULL, exception); if (GetDelegateThreadSupport(delegate_info) == MagickFalse) UnlockSemaphoreInfo(constitute_semaphore); image=DestroyImageList(image); read_info->temporary=MagickTrue; (void) SetImageInfo(read_info,0,exception); magick_info=GetMagickInfo(read_info->magick,exception); if ((magick_info == (const MagickInfo *) NULL) || (GetImageDecoder(magick_info) == (DecodeImageHandler *) NULL)) { if (IsPathAccessible(read_info->filename) != MagickFalse) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"NoDecodeDelegateForThisImageFormat","`%s'", read_info->filename); else ThrowFileException(exception,FileOpenError,"UnableToOpenFile", read_info->filename); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } thread_support=GetMagickThreadSupport(magick_info); if ((thread_support & DecoderThreadSupport) == 0) LockSemaphoreInfo(constitute_semaphore); image=(Image *) (GetImageDecoder(magick_info))(read_info,exception); if ((thread_support & DecoderThreadSupport) == 0) UnlockSemaphoreInfo(constitute_semaphore); } if (read_info->temporary != MagickFalse) { (void) RelinquishUniqueFileResource(read_info->filename); read_info->temporary=MagickFalse; if (image != (Image *) NULL) (void) CopyMagickString(image->filename,filename,MaxTextExtent); } if (image == (Image *) NULL) { read_info=DestroyImageInfo(read_info); return(image); } if (exception->severity >= ErrorException) (void) LogMagickEvent(ExceptionEvent,GetMagickModule(), "Coder (%s) generated an image despite an error (%d), " "notify the developers",image->magick,exception->severity); if (IsBlobTemporary(image) != MagickFalse) (void) RelinquishUniqueFileResource(read_info->filename); if ((GetNextImageInList(image) != (Image *) NULL) && (IsSceneGeometry(read_info->scenes,MagickFalse) != MagickFalse)) { Image *clones; clones=CloneImages(image,read_info->scenes,exception); if (clones == (Image *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SubimageSpecificationReturnsNoImages","`%s'",read_info->filename); else { image=DestroyImageList(image); image=GetFirstImageInList(clones); } } if (GetBlobError(image) != MagickFalse) { ThrowFileException(exception,FileOpenError, "AnErrorHasOccurredReadingFromFile",read_info->filename); image=DestroyImageList(image); read_info=DestroyImageInfo(read_info); return((Image *) NULL); } for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { char magick_path[MaxTextExtent], *property, timestamp[MaxTextExtent]; const char *option; const StringInfo *profile; next->taint=MagickFalse; GetPathComponent(magick_filename,MagickPath,magick_path); if (*magick_path == '\0') (void) CopyMagickString(next->magick,magick,MaxTextExtent); (void) CopyMagickString(next->magick_filename,magick_filename, MaxTextExtent); if (IsBlobTemporary(image) != MagickFalse) (void) CopyMagickString(next->filename,filename,MaxTextExtent); if (next->magick_columns == 0) next->magick_columns=next->columns; if (next->magick_rows == 0) next->magick_rows=next->rows; value=GetImageProperty(next,"tiff:Orientation",exception); if (value == (char *) NULL) value=GetImageProperty(next,"exif:Orientation",exception); if (value != (char *) NULL) { next->orientation=(OrientationType) StringToLong(value); (void) DeleteImageProperty(next,"tiff:Orientation"); (void) DeleteImageProperty(next,"exif:Orientation"); } value=GetImageProperty(next,"exif:XResolution",exception); if (value != (char *) NULL) { geometry_info.rho=next->resolution.x; geometry_info.sigma=1.0; flags=ParseGeometry(value,&geometry_info); if (geometry_info.sigma != 0) next->resolution.x=geometry_info.rho/geometry_info.sigma; (void) DeleteImageProperty(next,"exif:XResolution"); } value=GetImageProperty(next,"exif:YResolution",exception); if (value != (char *) NULL) { geometry_info.rho=next->resolution.y; geometry_info.sigma=1.0; flags=ParseGeometry(value,&geometry_info); if (geometry_info.sigma != 0) next->resolution.y=geometry_info.rho/geometry_info.sigma; (void) DeleteImageProperty(next,"exif:YResolution"); } value=GetImageProperty(next,"tiff:ResolutionUnit",exception); if (value == (char *) NULL) value=GetImageProperty(next,"exif:ResolutionUnit",exception); if (value != (char *) NULL) { next->units=(ResolutionType) (StringToLong(value)-1); (void) DeleteImageProperty(next,"exif:ResolutionUnit"); (void) DeleteImageProperty(next,"tiff:ResolutionUnit"); } if (next->page.width == 0) next->page.width=next->columns; if (next->page.height == 0) next->page.height=next->rows; option=GetImageOption(read_info,"caption"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"caption",property,exception); property=DestroyString(property); } option=GetImageOption(read_info,"comment"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"comment",property,exception); property=DestroyString(property); } option=GetImageOption(read_info,"label"); if (option != (const char *) NULL) { property=InterpretImageProperties(read_info,next,option,exception); (void) SetImageProperty(next,"label",property,exception); property=DestroyString(property); } if (LocaleCompare(next->magick,"TEXT") == 0) (void) ParseAbsoluteGeometry("0x0+0+0",&next->page); if ((read_info->extract != (char *) NULL) && (read_info->stream == (StreamHandler) NULL)) { RectangleInfo geometry; flags=ParseAbsoluteGeometry(read_info->extract,&geometry); if ((next->columns != geometry.width) || (next->rows != geometry.height)) { if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { Image *crop_image; crop_image=CropImage(next,&geometry,exception); if (crop_image != (Image *) NULL) ReplaceImageInList(&next,crop_image); } else if (((flags & WidthValue) != 0) || ((flags & HeightValue) != 0)) { Image *size_image; flags=ParseRegionGeometry(next,read_info->extract,&geometry, exception); size_image=ResizeImage(next,geometry.width,geometry.height, next->filter,next->blur,exception); if (size_image != (Image *) NULL) ReplaceImageInList(&next,size_image); } } } profile=GetImageProfile(next,"icc"); if (profile == (const StringInfo *) NULL) profile=GetImageProfile(next,"icm"); profile=GetImageProfile(next,"iptc"); if (profile == (const StringInfo *) NULL) profile=GetImageProfile(next,"8bim"); (void) FormatMagickTime(GetBlobProperties(next)->st_mtime,MaxTextExtent, timestamp); (void) SetImageProperty(next,"date:modify",timestamp,exception); (void) FormatMagickTime(GetBlobProperties(next)->st_ctime,MaxTextExtent, timestamp); (void) SetImageProperty(next,"date:create",timestamp,exception); option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if (next->delay > (size_t) floor(geometry_info.rho+0.5)) next->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (next->delay < (size_t) floor(geometry_info.rho+0.5)) next->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } else next->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) next->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) next->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); if (read_info->verbose != MagickFalse) (void) IdentifyImage(next,stderr,MagickFalse,exception); image=next; } read_info=DestroyImageInfo(read_info); return(GetFirstImageInList(image)); }
static MagickBooleanType WriteMPEGParameterFiles(const ImageInfo *image_info, Image *image,const char *basename) { char filename[MaxTextExtent]; double q; FILE *file, *parameter_file; long quant, vertical_factor; MagickBooleanType mpeg; register Image *p; register long i; ssize_t count; static int q_matrix[]= { 8, 16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22, 22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26, 27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83 }; unsigned long delay; /* Write parameter file (see mpeg2encode documentation for details). */ file=fopen(basename,"w"); if (file == (FILE *) NULL) return(MagickFalse); (void) fprintf(file,"MPEG\n"); /* comment */ (void) fprintf(file,"%s.%%d\n",image->filename); /* source frame file */ (void) fprintf(file,"-\n"); /* reconstructed frame file */ if (image->quality == UndefinedCompressionQuality) (void) fprintf(file,"-\n"); /* default intra quant matrix */ else { /* Write intra quant matrix file. */ (void) FormatMagickString(filename,MaxTextExtent,"%s.iqm",basename); (void) fprintf(file,"%s\n",filename); parameter_file=fopen(filename,"w"); if (parameter_file == (FILE *) NULL) return(MagickFalse); if (image->quality >= 75) { q=(double) Max((image->quality-75)*2,1); for (i=0; i < 64; i++) { quant=(long) Min(Max(q_matrix[i]/q,1.0),255.0); (void) fprintf(parameter_file," %ld",quant); if ((i % 8) == 7) (void) fprintf(parameter_file,"\n"); } } else { q=(double) Max((75-image->quality)/8,1); for (i=0; i < 64; i++) { quant=(long) Min(Max(q*q_matrix[i]+0.5,1.0),255.0); (void) fprintf(parameter_file," %ld",quant); if ((i % 8) == 7) (void) fprintf(parameter_file,"\n"); } } (void) fclose(parameter_file); } if (image->quality == UndefinedCompressionQuality) (void) fprintf(file,"-\n"); /* default non intra quant matrix */ else { /* Write non intra quant matrix file. */ (void) FormatMagickString(filename,MaxTextExtent,"%s.niq",basename); (void) fprintf(file,"%s\n",filename); parameter_file=fopen(filename,"w"); if (parameter_file == (FILE *) NULL) return(MagickFalse); q=Min(Max(66.0-(2*image->quality)/3.0,1.0),255); for (i=0; i < 64; i++) { (void) fprintf(parameter_file," %d",(int) q); if ((i % 8) == 7) (void) fprintf(parameter_file,"\n"); } (void) fclose(parameter_file); } (void) fprintf(file,"%s.log\n",basename); /* statistics log */ (void) fprintf(file,"1\n"); /* input picture file format */ count=0; for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { delay=100*p->delay/Max(p->ticks_per_second,1); count+=Max((delay+1)/3,1); } (void) fprintf(file,"%lu\n",(unsigned long) count); /* number of frames */ (void) fprintf(file,"0\n"); /* number of first frame */ (void) fprintf(file,"00:00:00:00\n"); /* timecode of first frame */ mpeg=(MagickBooleanType) (LocaleCompare(image_info->magick,"M2V") != 0); if (image->quality > 98) (void) fprintf(file,"1\n"); else (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 12 : 15); if (image->quality > 98) (void) fprintf(file,"1\n"); else (void) fprintf(file,"3\n"); (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 1 : 0); /* ISO/IEC 11172-2 stream */ (void) fprintf(file,"0\n"); /* select frame picture coding */ (void) fprintf(file,"%lu\n",image->columns+ ((image->columns & 0x01) != 0 ? 1 : 0)); (void) fprintf(file,"%lu\n",image->rows+((image->rows & 0x01) != 0 ? 1 : 0)); (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 8 : 2); /* aspect ratio */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 3 : 5); /* frame rate code */ (void) fprintf(file,"%g\n",mpeg != MagickFalse ? 1152000.0 : 5000000.0); /* bit rate */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 20 : 112); /* vbv buffer size */ (void) fprintf(file,"0\n"); /* low delay */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 1 : 0); /* constrained parameter */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 4 : 1); /* profile ID */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 8 : 4); /* level ID */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 1 : 0); /* progressive sequence */ vertical_factor=2; if (image_info->sampling_factor != (char *) NULL) { GeometryInfo geometry_info; long horizontal_factor; MagickStatusType flags; flags=ParseGeometry(image_info->sampling_factor,&geometry_info); horizontal_factor=(long) geometry_info.rho; vertical_factor=(long) geometry_info.sigma; if ((flags & SigmaValue) == 0) vertical_factor=horizontal_factor; if (mpeg != MagickFalse) { if ((horizontal_factor != 2) || (vertical_factor != 2)) { (void) fclose(file); return(MagickFalse); } } else if ((horizontal_factor != 2) || ((vertical_factor != 1) && (vertical_factor != 2))) { (void) fclose(file); return(MagickFalse); } } (void) fprintf(file,"%d\n",vertical_factor == 2 ? 1 : 2); /* chroma format */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 1 : 2); /* video format */ (void) fprintf(file,"5\n"); /* color primaries */ (void) fprintf(file,"5\n"); /* transfer characteristics */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 5 : 4); /* matrix coefficients */ (void) fprintf(file,"%lu\n",image->columns+ ((image->columns & 0x01) != 0 ? 1 : 0)); (void) fprintf(file,"%lu\n",image->rows+((image->rows & 0x01) != 0 ? 1 : 0)); (void) fprintf(file,"0\n"); /* intra dc precision */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 0 : 1); /* top field */ (void) fprintf(file,"%d %d %d\n",mpeg != MagickFalse ? 1 : 0, mpeg != MagickFalse ? 1 : 0, mpeg != MagickFalse ? 1 : 0); (void) fprintf(file,"0 0 0\n"); /* concealment motion vector */ (void) fprintf(file,"%d %d %d\n",mpeg != MagickFalse ? 0 : 1, mpeg != MagickFalse ? 0 : 1,mpeg != MagickFalse ? 0 : 1); (void) fprintf(file,"%d 0 0\n",mpeg != MagickFalse ? 0 : 1); /* intra vlc format */ (void) fprintf(file,"0 0 0\n"); /* alternate scan */ (void) fprintf(file,"0\n"); /* repeat first field */ (void) fprintf(file,"%d\n",mpeg != MagickFalse ? 1 : 0); /* progressive frame */ (void) fprintf(file,"0\n"); /* intra slice refresh period */ (void) fprintf(file,"0\n"); /* reaction parameter */ (void) fprintf(file,"0\n"); /* initial average activity */ (void) fprintf(file,"0\n"); (void) fprintf(file,"0\n"); (void) fprintf(file,"0\n"); (void) fprintf(file,"0\n"); (void) fprintf(file,"0\n"); (void) fprintf(file,"0\n"); (void) fprintf(file,"2 2 11 11\n"); (void) fprintf(file,"1 1 3 3\n"); (void) fprintf(file,"1 1 7 7\n"); (void) fprintf(file,"1 1 7 7\n"); (void) fprintf(file,"1 1 3 3\n"); (void) fclose(file); return(MagickTrue); }
CMiniMap::CMiniMap() : CInputReceiver(BACK), fullProxy(false), proxyMode(false), selecting(false), mouseMove(false), mouseResize(false), mouseLook(false), maxspect(false), maximized(false), minimized(false), showButtons(false), useIcons(true), slaveDrawMode(false) { lastWindowSizeX = gu->viewSizeX; lastWindowSizeY = gu->viewSizeY; if (gu->dualScreenMode) { width = gu->viewSizeX; height = gu->viewSizeY; xpos = (gu->viewSizeX - gu->viewPosX); ypos = 0; } else { const std::string geodef = "2 2 200 200"; const std::string geo = configHandler.GetString("MiniMapGeometry", geodef); ParseGeometry(geo); } fullProxy = !!configHandler.GetInt("MiniMapFullProxy", 1); buttonSize = configHandler.GetInt("MiniMapButtonSize", 16); unitBaseSize = atof(configHandler.GetString("MiniMapUnitSize", "2.5").c_str()); unitBaseSize = std::max(0.0f, unitBaseSize); unitExponent = atof(configHandler.GetString("MiniMapUnitExp", "0.25").c_str()); cursorScale = atof(configHandler.GetString("MiniMapCursorScale", "-0.5").c_str()); useIcons = !!configHandler.GetInt("MiniMapIcons", 1); drawCommands = std::max(0, configHandler.GetInt("MiniMapDrawCommands", 1)); drawProjectiles = !!configHandler.GetInt("MiniMapDrawProjectiles", 1); simpleColors = !!configHandler.GetInt("SimpleMiniMapColors", 0); myColor[0] = (unsigned char)(0.2f * 255); myColor[1] = (unsigned char)(0.9f * 255); myColor[2] = (unsigned char)(0.2f * 255); myColor[3] = (unsigned char)(1.0f * 255); allyColor[0] = (unsigned char)(0.3f * 255); allyColor[1] = (unsigned char)(0.3f * 255); allyColor[2] = (unsigned char)(0.9f * 255); allyColor[3] = (unsigned char)(1.0f * 255); enemyColor[0] = (unsigned char)(0.9f * 255); enemyColor[1] = (unsigned char)(0.2f * 255); enemyColor[2] = (unsigned char)(0.2f * 255); enemyColor[3] = (unsigned char)(1.0f * 255); UpdateGeometry(); circleLists = glGenLists(circleListsCount); for (int cl = 0; cl < circleListsCount; cl++) { glNewList(circleLists + cl, GL_COMPILE); glBegin(GL_LINE_LOOP); const int divs = (1 << (cl + 3)); for (int d = 0; d < divs; d++) { const float rads = float(2.0 * PI) * float(d) / float(divs); glVertex3f(sin(rads), 0.0f, cos(rads)); } glEnd(); glEndList(); } // setup the buttons' texture and texture coordinates buttonsTexture = 0; CBitmap bitmap; bool unfiltered = false; if (bitmap.Load("bitmaps/minimapbuttons.png")) { if ((bitmap.ysize == buttonSize) && (bitmap.xsize == (buttonSize * 4))) { unfiltered = true; } glGenTextures(1, &buttonsTexture); glBindTexture(GL_TEXTURE_2D, buttonsTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, bitmap.xsize, bitmap.ysize, 0, GL_RGBA, GL_UNSIGNED_BYTE, bitmap.mem); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); if (unfiltered) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glBindTexture(GL_TEXTURE_2D, 0); } const float xshift = unfiltered ? 0.0f : (0.5f / bitmap.xsize); const float yshift = unfiltered ? 0.0f : (0.5f / bitmap.ysize); moveBox.xminTx = 0.50f + xshift; moveBox.xmaxTx = 0.75f - xshift; resizeBox.xminTx = 0.75f + xshift; resizeBox.xmaxTx = 1.00f - xshift; minimizeBox.xminTx = 0.00f + xshift; minimizeBox.xmaxTx = 0.25f - xshift; maximizeBox.xminTx = 0.25f + xshift; maximizeBox.xmaxTx = 0.50f - xshift; moveBox.yminTx = 1.00f - yshift; resizeBox.yminTx = 1.00f - yshift; minimizeBox.yminTx = 1.00f - yshift; maximizeBox.yminTx = 1.00f - yshift; moveBox.ymaxTx = 0.00f + yshift; resizeBox.ymaxTx = 0.00f + yshift; minimizeBox.ymaxTx = 0.00f + yshift; maximizeBox.ymaxTx = 0.00f + yshift; }
static MagickBooleanType WriteJBIGImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { double version; MagickBooleanType status; MagickOffsetType scene; register const Quantum *p; register ssize_t x; register unsigned char *q; size_t number_packets; ssize_t y; struct jbg_enc_state jbig_info; unsigned char bit, byte, *pixels; /* 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); version=StringToDouble(JBG_VERSION,(char **) NULL); scene=0; do { /* Allocate pixel data. */ if (IsRGBColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,RGBColorspace,exception); number_packets=(image->columns+7)/8; pixels=(unsigned char *) AcquireQuantumMemory(number_packets, image->rows*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert pixels to a bitmap. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (GetPixelIntensity(image,p) < (QuantumRange/2.0)) byte|=0x01; bit++; if (bit == 8) { *q++=byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) *q++=byte << (8-bit); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } /* Initialize JBIG info structure. */ jbg_enc_init(&jbig_info,(unsigned long) image->columns,(unsigned long) image->rows,1,&pixels,(void (*)(unsigned char *,size_t,void *)) JBIGEncode,image); if (image_info->scene != 0) jbg_enc_layers(&jbig_info,(int) image_info->scene); else { size_t x_resolution, y_resolution; x_resolution=640; y_resolution=480; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->density,&geometry_info); x_resolution=geometry_info.rho; y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) y_resolution=x_resolution; } if (image->units == PixelsPerCentimeterResolution) { x_resolution=(size_t) (100.0*2.54*x_resolution+0.5)/100.0; y_resolution=(size_t) (100.0*2.54*y_resolution+0.5)/100.0; } (void) jbg_enc_lrlmax(&jbig_info,(unsigned long) x_resolution, (unsigned long) y_resolution); } (void) jbg_enc_lrange(&jbig_info,-1,-1); jbg_enc_options(&jbig_info,JBG_ILEAVE | JBG_SMID,JBG_TPDON | JBG_TPBON | JBG_DPON,version < 1.6 ? -1 : 0,-1,-1); /* Write JBIG image. */ jbg_enc_out(&jbig_info); jbg_enc_free(&jbig_info); pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a r s e G r a v i t y G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ParseGravityGeometry() returns a region as defined by the geometry string % with respect to the image dimensions and its gravity. % % The format of the ParseGravityGeometry method is: % % MagickStatusType ParseGravityGeometry(Image *image,const char *geometry, % RectangeInfo *region_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o geometry: The geometry (e.g. 100x100+10+10). % % o region_info: the region as defined by the geometry string with % respect to the image dimensions and its gravity. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickStatusType ParseGravityGeometry(const Image *image, const char *geometry,RectangleInfo *region_info,ExceptionInfo *exception) { MagickStatusType flags; size_t height, width; SetGeometry(image,region_info); if (image->page.width != 0) region_info->width=image->page.width; if (image->page.height != 0) region_info->height=image->page.height; flags=ParseAbsoluteGeometry(geometry,region_info); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",geometry); return(flags); } if ((flags & PercentValue) != 0) { GeometryInfo geometry_info; MagickStatusType status; PointInfo scale; /* Geometry is a percentage of the image size. */ if (image->gravity != UndefinedGravity) flags|=XValue | YValue; status=ParseGeometry(geometry,&geometry_info); scale.x=geometry_info.rho; if ((status & RhoValue) == 0) scale.x=100.0; scale.y=geometry_info.sigma; if ((status & SigmaValue) == 0) scale.y=scale.x; region_info->width=(size_t) floor((scale.x*image->columns/100.0)+ 0.5); region_info->height=(size_t) floor((scale.y*image->rows/100.0)+ 0.5); } /* Adjust offset according to gravity setting. */ width=region_info->width; height=region_info->height; if (width == 0) region_info->width=image->page.width | image->columns; if (height == 0) region_info->height=image->page.height | image->rows; GravityAdjustGeometry(image->columns,image->rows,image->gravity,region_info); region_info->width=width; region_info->height=height; return(flags); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e Y U V I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteYUVImage() writes an image to a file in the digital YUV % (CCIR 601 4:1:1, plane or partition interlaced, or 4:2:2 plane, partition % interlaced or noninterlaced) bytes and returns it. % % The format of the WriteYUVImage method is: % % MagickBooleanType WriteYUVImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteYUVImage(const ImageInfo *image_info,Image *image) { Image *chroma_image, *yuv_image; InterlaceType interlace; MagickBooleanType status; MagickOffsetType scene; register const PixelPacket *p, *s; register ssize_t x; size_t height, quantum, width; ssize_t horizontal_factor, vertical_factor, y; 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); quantum=(size_t) (image->depth <= 8 ? 1 : 2); interlace=image->interlace; horizontal_factor=2; vertical_factor=2; if (image_info->sampling_factor != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->sampling_factor,&geometry_info); horizontal_factor=(ssize_t) geometry_info.rho; vertical_factor=(ssize_t) geometry_info.sigma; if ((flags & SigmaValue) == 0) vertical_factor=horizontal_factor; if ((horizontal_factor != 1) && (horizontal_factor != 2) && (vertical_factor != 1) && (vertical_factor != 2)) ThrowWriterException(CorruptImageError,"UnexpectedSamplingFactor"); } if ((interlace == UndefinedInterlace) || ((interlace == NoInterlace) && (vertical_factor == 2))) { interlace=NoInterlace; /* CCIR 4:2:2 */ if (vertical_factor == 2) interlace=PlaneInterlace; /* CCIR 4:1:1 */ } if (interlace != PartitionInterlace) { /* Open output image file. */ status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); } else { AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); } scene=0; do { /* Sample image to an even width and height, if necessary. */ image->depth=(size_t) (quantum == 1 ? 8 : 16); width=image->columns+(image->columns & (horizontal_factor-1)); height=image->rows+(image->rows & (vertical_factor-1)); yuv_image=ResizeImage(image,width,height,TriangleFilter,1.0, &image->exception); if (yuv_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,image->exception.reason); (void) TransformImageColorspace(yuv_image,YCbCrColorspace); /* Downsample image. */ chroma_image=ResizeImage(image,width/horizontal_factor, height/vertical_factor,TriangleFilter,1.0,&image->exception); if (chroma_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,image->exception.reason); (void) TransformImageColorspace(chroma_image,YCbCrColorspace); if (interlace == NoInterlace) { /* Write noninterlaced YUV. */ for (y=0; y < (ssize_t) yuv_image->rows; y++) { p=GetVirtualPixels(yuv_image,0,y,yuv_image->columns,1, &yuv_image->exception); if (p == (const PixelPacket *) NULL) break; s=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1, &chroma_image->exception); if (s == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) yuv_image->columns; x++) { if (quantum == 1) { (void) WriteBlobByte(image,ScaleQuantumToChar( GetPixelGreen(s))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p))); p++; (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(s))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p))); } else { (void) WriteBlobByte(image,ScaleQuantumToChar( GetPixelGreen(s))); (void) WriteBlobShort(image,ScaleQuantumToShort( GetPixelRed(p))); p++; (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(s))); (void) WriteBlobShort(image,ScaleQuantumToShort( GetPixelRed(p))); } p++; s++; x++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } yuv_image=DestroyImage(yuv_image); } else { /* Initialize Y channel. */ for (y=0; y < (ssize_t) yuv_image->rows; y++) { p=GetVirtualPixels(yuv_image,0,y,yuv_image->columns,1, &yuv_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) yuv_image->columns; x++) { if (quantum == 1) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p))); else (void) WriteBlobShort(image,ScaleQuantumToShort(GetPixelRed(p))); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } yuv_image=DestroyImage(yuv_image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,1,3); if (status == MagickFalse) break; } /* Initialize U channel. */ if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("U",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) return(status); } for (y=0; y < (ssize_t) chroma_image->rows; y++) { p=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1, &chroma_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { if (quantum == 1) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p))); else (void) WriteBlobShort(image,ScaleQuantumToShort( GetPixelGreen(p))); p++; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,3); if (status == MagickFalse) break; } /* Initialize V channel. */ if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("V",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode, &image->exception); if (status == MagickFalse) return(status); } for (y=0; y < (ssize_t) chroma_image->rows; y++) { p=GetVirtualPixels(chroma_image,0,y,chroma_image->columns,1, &chroma_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { if (quantum == 1) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p))); else (void) WriteBlobShort(image,ScaleQuantumToShort(GetPixelBlue(p))); p++; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,2,3); if (status == MagickFalse) break; } } chroma_image=DestroyImage(chroma_image); if (interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXPSImage() reads a Printer Control Language image file and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadXPSImage method is: % % Image *ReadXPSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadXPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CropBox "CropBox" #define DeviceCMYK "DeviceCMYK" #define MediaBox "MediaBox" #define RenderXPSText " Rendering XPS... " char command[MaxTextExtent], density[MaxTextExtent], filename[MaxTextExtent], geometry[MaxTextExtent], options[MaxTextExtent], input_filename[MaxTextExtent]; const DelegateInfo *delegate_info; Image *image, *next_image; ImageInfo *read_info; MagickBooleanType cmyk, status; PointInfo delta; RectangleInfo bounding_box, page; register char *p; register ssize_t c; SegmentInfo bounds; size_t height, width; ssize_t count; 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); /* Open image file. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) FormatLocaleString(density,MaxTextExtent,"%gx%g", image->x_resolution,image->y_resolution); /* Determine page geometry from the XPS media box. */ cmyk=image->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; count=0; (void) ResetMagickMemory(&bounding_box,0,sizeof(bounding_box)); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(&page,0,sizeof(page)); (void) ResetMagickMemory(command,0,sizeof(command)); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if (image_info->page != (char *) NULL) continue; /* Note XPS elements. */ *p++=(char) c; if ((c != (int) '/') && (c != '\n') && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; /* Is this a CMYK document? */ if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; /* Set XPS render geometry. */ width=(size_t) (floor(bounds.x2+0.5)-ceil(bounds.x1-0.5)); height=(size_t) (floor(bounds.y2+0.5)-ceil(bounds.y1-0.5)); if (width > page.width) page.width=width; if (height > page.height) page.height=height; } (void) CloseBlob(image); /* Render XPS with the GhostXPS delegate. */ if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); (void) FormatLocaleString(geometry,MaxTextExtent,"%.20gx%.20g",(double) page.width,(double) page.height); if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("xps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("xps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("xps:color",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) return((Image *) NULL); *options='\0'; if ((page.width == 0) || (page.height == 0)) (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); page.width=(size_t) floor(page.width*image->y_resolution/delta.x+0.5); page.height=(size_t) floor(page.height*image->y_resolution/delta.y+0.5); (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); image=DestroyImage(image); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { if (read_info->number_scenes != 1) (void) FormatLocaleString(options,MaxTextExtent,"-dLastPage=%.20g", (double) (read_info->scene+read_info->number_scenes)); else (void) FormatLocaleString(options,MaxTextExtent, "-dFirstPage=%.20g -dLastPage=%.20g",(double) read_info->scene+1, (double) (read_info->scene+read_info->number_scenes)); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (read_info->authenticate != (char *) NULL) (void) FormatLocaleString(options+strlen(options),MaxTextExtent, " -sXPSPassword=%s",read_info->authenticate); (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(read_info->filename); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options, read_info->filename,input_filename); status=SystemCommand(MagickFalse,read_info->verbose,command,exception) != 0 ? MagickTrue : MagickFalse; image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); (void) RelinquishUniqueFileResource(input_filename); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) ThrowReaderException(DelegateError,"XPSDelegateFailed"); if (LocaleCompare(image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(image,&image->exception); if (cmyk_image != (Image *) NULL) { image=DestroyImageList(image); image=cmyk_image; } } do { (void) CopyMagickString(image->filename,filename,MaxTextExtent); image->page=page; next_image=SyncNextImageInList(image); if (next_image != (Image *) NULL) image=next_image; } while (next_image != (Image *) NULL); return(GetFirstImageInList(image)); }
ngx_int_t ngx_http_small_light_imagemagick_process(ngx_http_request_t *r, ngx_http_small_light_ctx_t *ctx) { ngx_http_small_light_imagemagick_ctx_t *ictx; ngx_http_small_light_image_size_t sz; MagickBooleanType status; int rmprof_flg, progressive_flg; double iw, ih, q; char *jpeg_size_opt, *of_orig, *crop_geo, *size_geo; char *unsharp, *sharpen, *blur, *dealpha, *of; MagickWand *trans_wand, *canvas_wand; DrawingWand *border_wand; PixelWand *bg_color, *canvas_color, *border_color; GeometryInfo geo; ngx_fd_t fd; MagickWand *icon_wand; u_char *p, *embedicon, *embedicon_path; size_t embedicon_path_len, embedicon_len, sled_image_size; ngx_int_t type; status = MagickFalse; ictx = (ngx_http_small_light_imagemagick_ctx_t *)ctx->ictx; /* adjust image size */ ngx_http_small_light_calc_image_size(r, ctx, &sz, 10000.0, 10000.0); /* init */ ictx->wand = NewMagickWand(); /* prepare */ if (sz.jpeghint_flg != 0) { jpeg_size_opt = ngx_pcalloc(r->pool, 32 + 1); if (jpeg_size_opt == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to allocate memory from r->pool %s:%d", __FUNCTION__, __LINE__); return NGX_ERROR; } ngx_snprintf((u_char *)jpeg_size_opt, 32 + 1, "%dx%d", (ngx_int_t)sz.dw, (ngx_int_t)sz.dh); MagickSetOption(ictx->wand, "jpeg:size", jpeg_size_opt); } /* load image. */ status = MagickReadImageBlob(ictx->wand, (void *)ictx->image, ictx->image_len); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "couldn't read image %s:%d", __FUNCTION__, __LINE__); return NGX_ERROR; } /* remove all profiles */ rmprof_flg = ngx_http_small_light_parse_flag(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "rmprof")); if (rmprof_flg != 0) { status = MagickProfileImage(ictx->wand, "*", NULL, 0); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "couldn't profiling image %s:%d", __FUNCTION__, __LINE__); } } /* calc size. */ iw = (double)MagickGetImageWidth(ictx->wand); ih = (double)MagickGetImageHeight(ictx->wand); ngx_http_small_light_calc_image_size(r, ctx, &sz, iw, ih); /* pass through. */ if (sz.pt_flg != 0) { return NGX_OK; } of_orig = MagickGetImageFormat(ictx->wand); /* crop, scale. */ status = MagickTrue; if (sz.scale_flg != 0) { crop_geo = ngx_pcalloc(r->pool, 128 + 1); if (crop_geo == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to allocate memory from r->pool %s:%d", __FUNCTION__, __LINE__); return NGX_ERROR; } size_geo = ngx_pcalloc(r->pool, 128 + 1); if (size_geo == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to allocate memory from r->pool %s:%d", __FUNCTION__, __LINE__); return NGX_ERROR; } ngx_snprintf((u_char *)crop_geo, 128 + 1, "%f!x%f!+%f+%f", sz.sw, sz.sh, sz.sx, sz.sy); ngx_snprintf((u_char *)size_geo, 128 + 1, "%f!x%f!", sz.dw, sz.dh); trans_wand = MagickTransformImage(ictx->wand, crop_geo, size_geo); if (trans_wand == NULL || trans_wand == ictx->wand) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; return NGX_ERROR; } DestroyMagickWand(ictx->wand); ictx->wand = trans_wand; } /* rotate */ if (sz.angle) { bg_color = NewPixelWand(); PixelSetRed(bg_color, sz.cc.r / 255.0); PixelSetGreen(bg_color, sz.cc.g / 255.0); PixelSetBlue(bg_color, sz.cc.b / 255.0); PixelSetAlpha(bg_color, sz.cc.a / 255.0); switch (sz.angle) { case 90: case 180: case 270: MagickRotateImage(ictx->wand, bg_color, sz.angle); break; } DestroyPixelWand(bg_color); } /* create canvas then draw image to the canvas. */ if (sz.cw > 0.0 && sz.ch > 0.0) { canvas_wand = NewMagickWand(); canvas_color = NewPixelWand(); PixelSetRed(canvas_color, sz.cc.r / 255.0); PixelSetGreen(canvas_color, sz.cc.g / 255.0); PixelSetBlue(canvas_color, sz.cc.b / 255.0); PixelSetAlpha(canvas_color, sz.cc.a / 255.0); status = MagickNewImage(canvas_wand, sz.cw, sz.ch, canvas_color); DestroyPixelWand(canvas_color); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; return NGX_ERROR; } status = MagickCompositeImage(canvas_wand, ictx->wand, AtopCompositeOp, sz.dx, sz.dy); if (status == MagickFalse) { r->err_status = NGX_HTTP_INTERNAL_SERVER_ERROR; return NGX_ERROR; } DestroyMagickWand(ictx->wand); ictx->wand = canvas_wand; } /* effects. */ unsharp = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "unsharp"); if (unsharp != NULL) { ParseGeometry(unsharp, &geo); status = MagickUnsharpMaskImage(ictx->wand, geo.rho, geo.sigma, geo.xi, geo.psi); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "unsharp failed %s:%d", __FUNCTION__, __LINE__); } } sharpen = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "sharpen"); if (sharpen != NULL) { ParseGeometry(sharpen, &geo); status = MagickSharpenImage(ictx->wand, geo.rho, geo.sigma); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "sharpen failed %s:%d", __FUNCTION__, __LINE__); } } blur = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "blur"); if (blur) { ParseGeometry(blur, &geo); status = MagickBlurImage(ictx->wand, geo.rho, geo.sigma); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "blur failed %s:%d", __FUNCTION__, __LINE__); } } dealpha = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "dealpha"); if (dealpha != NULL) { status = MagickSetImageAlphaChannel(ictx->wand, DeactivateAlphaChannel); if (status == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "dealpha failed %s:%d", __FUNCTION__, __LINE__); } } /* border. */ if (sz.bw > 0.0 || sz.bh > 0.0) { border_wand = NewDrawingWand(); border_color = NewPixelWand(); PixelSetRed(border_color, sz.bc.r / 255.0); PixelSetGreen(border_color, sz.bc.g / 255.0); PixelSetBlue(border_color, sz.bc.b / 255.0); PixelSetAlpha(border_color, sz.bc.a / 255.0); DrawSetFillColor(border_wand, border_color); DrawSetStrokeColor(border_wand, border_color); DrawSetStrokeWidth(border_wand, 1); if (sz.cw > 0.0 && sz.ch > 0.0) { DrawRectangle(border_wand, 0, 0, sz.cw - 1, sz.bh - 1); DrawRectangle(border_wand, 0, 0, sz.bw - 1, sz.ch - 1); DrawRectangle(border_wand, 0, sz.ch - sz.bh, sz.cw - 1, sz.ch - 1); DrawRectangle(border_wand, sz.cw - sz.bw, 0, sz.cw - 1, sz.ch - 1); } else { DrawRectangle(border_wand, 0, 0, sz.dw - 1, sz.bh - 1); DrawRectangle(border_wand, 0, 0, sz.bw - 1, sz.dh - 1); DrawRectangle(border_wand, 0, sz.dh - sz.bh, sz.dw - 1, sz.dh - 1); DrawRectangle(border_wand, sz.dw - sz.bw, 0, sz.dw - 1, sz.dh - 1); } MagickDrawImage(ictx->wand, border_wand); DestroyPixelWand(border_color); DestroyDrawingWand(border_wand); } /* embed icon */ embedicon = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "embedicon"); if (ngx_strlen(ctx->material_dir) > 0 && ngx_strlen(embedicon) > 0) { if (ngx_strstrn((u_char *)embedicon, "/", 1 - 1)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "invalid parameter 'embedicon':%s %s:%d", embedicon, __FUNCTION__, __LINE__); return NGX_ERROR; } icon_wand = NewMagickWand(); embedicon_len = ngx_strlen(embedicon); embedicon_path_len = ctx->material_dir->len + ngx_strlen("/") + embedicon_len; embedicon_path = ngx_palloc(r->pool, embedicon_path_len + 1); if (embedicon_path == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to allocate memory from r->pool %s:%d", __FUNCTION__, __LINE__); return NGX_ERROR; } p = embedicon_path; p = ngx_cpystrn(p, ctx->material_dir->data, ctx->material_dir->len + 1); p = ngx_cpystrn(p, (u_char *)"/", 1 + 1); p = ngx_cpystrn(p, embedicon, embedicon_len + 1); if ((fd = ngx_open_file(embedicon_path, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0)) == NGX_INVALID_FILE) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to open embeddedicon file:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); return NGX_ERROR; } if (ngx_close_file(fd) == NGX_FILE_ERROR) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to close:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); return NGX_ERROR; } if (ngx_strstrn(embedicon_path, "..", 2 - 1)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "invalid embeddedicon_path:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); return NGX_ERROR; } if (MagickReadImage(icon_wand, (char *)embedicon_path) == MagickFalse) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to read embed icon image file:%s %s:%d", embedicon_path, __FUNCTION__, __LINE__); return NGX_ERROR; } MagickCompositeImageChannel(ictx->wand, AllChannels, icon_wand, OverCompositeOp, sz.ix, sz.iy); ClearMagickWand(icon_wand); } /* set params. */ q = ngx_http_small_light_parse_double(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "q")); if (q > 0.0) { MagickSetImageCompressionQuality(ictx->wand, q); } progressive_flg = ngx_http_small_light_parse_flag(NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "progressive")); if (progressive_flg != 0) { MagickSetInterlaceScheme(ictx->wand, LineInterlace); } of = NGX_HTTP_SMALL_LIGHT_PARAM_GET_LIT(&ctx->hash, "of"); if (ngx_strlen(of) > 0) { type = ngx_http_small_light_type(of); if (type == NGX_HTTP_SMALL_LIGHT_IMAGE_NONE) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "of is invalid(%s) %s:%d", of, __FUNCTION__, __LINE__); of = (char *)ngx_http_small_light_image_exts[ictx->type - 1]; } else if (type == NGX_HTTP_SMALL_LIGHT_IMAGE_WEBP) { #if defined(MAGICKCORE_WEBP_DELEGATE) ictx->type = type; #else ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "WebP is not supported %s:%d", __FUNCTION__, __LINE__); of = (char *)ngx_http_small_light_image_exts[ictx->type - 1]; #endif } else { ictx->type = type; } MagickSetFormat(ictx->wand, of); ctx->of = ngx_http_small_light_image_types[ictx->type - 1]; } else { MagickSetFormat(ictx->wand, of_orig); ctx->of = ctx->inf; } ctx->content = MagickGetImageBlob(ictx->wand, &sled_image_size); ctx->content_length = sled_image_size; ictx->complete = 1; return NGX_OK; }