]> granicus.if.org Git - imagemagick/blob - MagickCore/paint.c
175a29da526161d124182f096c592dc6874c0f6d
[imagemagick] / MagickCore / paint.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                      PPPP    AAA   IIIII  N   N  TTTTT                      %
7 %                      P   P  A   A    I    NN  N    T                        %
8 %                      PPPP   AAAAA    I    N N N    T                        %
9 %                      P      A   A    I    N  NN    T                        %
10 %                      P      A   A  IIIII  N   N    T                        %
11 %                                                                             %
12 %                                                                             %
13 %                        Methods to Paint on an Image                         %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                                 July 1998                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40  Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/artifact.h"
44 #include "MagickCore/channel.h"
45 #include "MagickCore/color.h"
46 #include "MagickCore/color-private.h"
47 #include "MagickCore/colorspace-private.h"
48 #include "MagickCore/composite.h"
49 #include "MagickCore/composite-private.h"
50 #include "MagickCore/draw.h"
51 #include "MagickCore/draw-private.h"
52 #include "MagickCore/exception.h"
53 #include "MagickCore/exception-private.h"
54 #include "MagickCore/gem.h"
55 #include "MagickCore/gem-private.h"
56 #include "MagickCore/monitor.h"
57 #include "MagickCore/monitor-private.h"
58 #include "MagickCore/option.h"
59 #include "MagickCore/paint.h"
60 #include "MagickCore/pixel-accessor.h"
61 #include "MagickCore/resource_.h"
62 #include "MagickCore/statistic.h"
63 #include "MagickCore/string_.h"
64 #include "MagickCore/string-private.h"
65 #include "MagickCore/thread-private.h"
66 \f
67 /*
68 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
69 %                                                                             %
70 %                                                                             %
71 %                                                                             %
72 %   F l o o d f i l l P a i n t I m a g e                                     %
73 %                                                                             %
74 %                                                                             %
75 %                                                                             %
76 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
77 %
78 %  FloodfillPaintImage() changes the color value of any pixel that matches
79 %  target and is an immediate neighbor.  If the method FillToBorderMethod is
80 %  specified, the color value is changed for any neighbor pixel that does not
81 %  match the bordercolor member of image.
82 %
83 %  By default target must match a particular pixel color exactly.  However,
84 %  in many cases two colors may differ by a small amount.  The fuzz member of
85 %  image defines how much tolerance is acceptable to consider two colors as
86 %  the same.  For example, set fuzz to 10 and the color red at intensities of
87 %  100 and 102 respectively are now interpreted as the same color for the
88 %  purposes of the floodfill.
89 %
90 %  The format of the FloodfillPaintImage method is:
91 %
92 %      MagickBooleanType FloodfillPaintImage(Image *image,
93 %        const DrawInfo *draw_info,const PixelInfo target,
94 %        const ssize_t x_offset,const ssize_t y_offset,
95 %        const MagickBooleanType invert,ExceptionInfo *exception)
96 %
97 %  A description of each parameter follows:
98 %
99 %    o image: the image.
100 %
101 %    o draw_info: the draw info.
102 %
103 %    o target: the RGB value of the target color.
104 %
105 %    o x_offset,y_offset: the starting location of the operation.
106 %
107 %    o invert: paint any pixel that does not match the target color.
108 %
109 %    o exception: return any errors or warnings in this structure.
110 %
111 */
112 MagickExport MagickBooleanType FloodfillPaintImage(Image *image,
113   const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset,
114   const ssize_t y_offset,const MagickBooleanType invert,
115   ExceptionInfo *exception)
116 {
117 #define MaxStacksize  524288UL
118 #define PushSegmentStack(up,left,right,delta) \
119 { \
120   if (s >= (segment_stack+MaxStacksize)) \
121     ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \
122   else \
123     { \
124       if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \
125         { \
126           s->x1=(double) (left); \
127           s->y1=(double) (up); \
128           s->x2=(double) (right); \
129           s->y2=(double) (delta); \
130           s++; \
131         } \
132     } \
133 }
134
135   CacheView
136     *floodplane_view,
137     *image_view;
138
139   Image
140     *floodplane_image;
141
142   MagickBooleanType
143     skip,
144     status;
145
146   MemoryInfo
147     *segment_info;
148
149   PixelInfo
150     fill_color,
151     pixel;
152
153   register SegmentInfo
154     *s;
155
156   SegmentInfo
157     *segment_stack;
158
159   ssize_t
160     offset,
161     start,
162     x1,
163     x2,
164     y;
165
166   /*
167     Check boundary conditions.
168   */
169   assert(image != (Image *) NULL);
170   assert(image->signature == MagickCoreSignature);
171   if (image->debug != MagickFalse)
172     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
173   assert(draw_info != (DrawInfo *) NULL);
174   assert(draw_info->signature == MagickCoreSignature);
175   if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
176     return(MagickFalse);
177   if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
178     return(MagickFalse);
179   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
180     return(MagickFalse);
181   if (IsGrayColorspace(image->colorspace) != MagickFalse)
182     (void) SetImageColorspace(image,sRGBColorspace,exception);
183   if ((image->alpha_trait == UndefinedPixelTrait) &&
184       (draw_info->fill.alpha_trait != UndefinedPixelTrait))
185     (void) SetImageAlpha(image,OpaqueAlpha,exception);
186   /*
187     Set floodfill state.
188   */
189   floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue,
190     exception);
191   if (floodplane_image == (Image *) NULL)
192     return(MagickFalse);
193   floodplane_image->alpha_trait=UndefinedPixelTrait;
194   floodplane_image->colorspace=GRAYColorspace;
195   (void) QueryColorCompliance("#000",AllCompliance,
196     &floodplane_image->background_color,exception);
197   (void) SetImageBackgroundColor(floodplane_image,exception);
198   segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack));
199   if (segment_info == (MemoryInfo *) NULL)
200     {
201       floodplane_image=DestroyImage(floodplane_image);
202       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
203         image->filename);
204     }
205   segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info);
206   /*
207     Push initial segment on stack.
208   */
209   status=MagickTrue;
210   start=0;
211   s=segment_stack;
212   PushSegmentStack(y_offset,x_offset,x_offset,1);
213   PushSegmentStack(y_offset+1,x_offset,x_offset,-1);
214   GetPixelInfo(image,&pixel);
215   image_view=AcquireVirtualCacheView(image,exception);
216   floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception);
217   while (s > segment_stack)
218   {
219     register const Quantum
220       *magick_restrict p;
221
222     register Quantum
223       *magick_restrict q;
224
225     register ssize_t
226       x;
227
228     /*
229       Pop segment off stack.
230     */
231     s--;
232     x1=(ssize_t) s->x1;
233     x2=(ssize_t) s->x2;
234     offset=(ssize_t) s->y2;
235     y=(ssize_t) s->y1+offset;
236     /*
237       Recolor neighboring pixels.
238     */
239     p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception);
240     q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1,
241       exception);
242     if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
243       break;
244     p+=x1*GetPixelChannels(image);
245     q+=x1*GetPixelChannels(floodplane_image);
246     for (x=x1; x >= 0; x--)
247     {
248       if (GetPixelGray(floodplane_image,q) != 0)
249         break;
250       GetPixelInfoPixel(image,p,&pixel);
251       if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
252         break;
253       SetPixelGray(floodplane_image,QuantumRange,q);
254       p-=GetPixelChannels(image);
255       q-=GetPixelChannels(floodplane_image);
256     }
257     if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse)
258       break;
259     skip=x >= x1 ? MagickTrue : MagickFalse;
260     if (skip == MagickFalse)
261       {
262         start=x+1;
263         if (start < x1)
264           PushSegmentStack(y,start,x1-1,-offset);
265         x=x1+1;
266       }
267     do
268     {
269       if (skip == MagickFalse)
270         {
271           if (x < (ssize_t) image->columns)
272             {
273               p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1,
274                 exception);
275               q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns-
276                 x,1,exception);
277               if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
278                 break;
279               for ( ; x < (ssize_t) image->columns; x++)
280               {
281                 if (GetPixelGray(floodplane_image,q) != 0)
282                   break;
283                 GetPixelInfoPixel(image,p,&pixel);
284                 if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
285                   break;
286                 SetPixelGray(floodplane_image,QuantumRange,q);
287                 p+=GetPixelChannels(image);
288                 q+=GetPixelChannels(floodplane_image);
289               }
290               status=SyncCacheViewAuthenticPixels(floodplane_view,exception);
291               if (status == MagickFalse)
292                 break;
293             }
294           PushSegmentStack(y,start,x-1,offset);
295           if (x > (x2+1))
296             PushSegmentStack(y,x2+1,x-1,-offset);
297         }
298       skip=MagickFalse;
299       x++;
300       if (x <= x2)
301         {
302           p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1,
303             exception);
304           q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1,
305             exception);
306           if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
307             break;
308           for ( ; x <= x2; x++)
309           {
310             if (GetPixelGray(floodplane_image,q) != 0)
311               break;
312             GetPixelInfoPixel(image,p,&pixel);
313             if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
314               break;
315             p+=GetPixelChannels(image);
316             q+=GetPixelChannels(floodplane_image);
317           }
318         }
319       start=x;
320     } while (x <= x2);
321   }
322   status=MagickTrue;
323 #if defined(MAGICKCORE_OPENMP_SUPPORT)
324   #pragma omp parallel for schedule(static,4) shared(status) \
325     magick_threads(floodplane_image,image,floodplane_image->rows,1)
326 #endif
327   for (y=0; y < (ssize_t) image->rows; y++)
328   {
329     register const Quantum
330       *magick_restrict p;
331
332     register Quantum
333       *magick_restrict q;
334
335     register ssize_t
336       x;
337
338     /*
339       Tile fill color onto floodplane.
340     */
341     if (status == MagickFalse)
342       continue;
343     p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception);
344     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
345     if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
346       {
347         status=MagickFalse;
348         continue;
349       }
350     for (x=0; x < (ssize_t) image->columns; x++)
351     {
352       if (GetPixelGray(floodplane_image,p) != 0)
353         {
354           GetFillColor(draw_info,x,y,&fill_color,exception);
355           SetPixelViaPixelInfo(image,&fill_color,q);
356         }
357       p+=GetPixelChannels(floodplane_image);
358       q+=GetPixelChannels(image);
359     }
360     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
361       status=MagickFalse;
362   }
363   floodplane_view=DestroyCacheView(floodplane_view);
364   image_view=DestroyCacheView(image_view);
365   segment_info=RelinquishVirtualMemory(segment_info);
366   floodplane_image=DestroyImage(floodplane_image);
367   return(status);
368 }
369 \f
370 /*
371 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
372 %                                                                             %
373 %                                                                             %
374 %                                                                             %
375 +     G r a d i e n t I m a g e                                               %
376 %                                                                             %
377 %                                                                             %
378 %                                                                             %
379 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
380 %
381 %  GradientImage() applies a continuously smooth color transitions along a
382 %  vector from one color to another.
383 %
384 %  Note, the interface of this method will change in the future to support
385 %  more than one transistion.
386 %
387 %  The format of the GradientImage method is:
388 %
389 %      MagickBooleanType GradientImage(Image *image,const GradientType type,
390 %        const SpreadMethod method,const PixelInfo *start_color,
391 %        const PixelInfo *stop_color,ExceptionInfo *exception)
392 %
393 %  A description of each parameter follows:
394 %
395 %    o image: the image.
396 %
397 %    o type: the gradient type: linear or radial.
398 %
399 %    o spread: the gradient spread meathod: pad, reflect, or repeat.
400 %
401 %    o start_color: the start color.
402 %
403 %    o stop_color: the stop color.
404 %
405 %    o exception: return any errors or warnings in this structure.
406 %
407 */
408 MagickExport MagickBooleanType GradientImage(Image *image,
409   const GradientType type,const SpreadMethod method,const StopInfo *stops,
410   const size_t number_stops,ExceptionInfo *exception)
411 {
412   const char
413     *artifact;
414
415   DrawInfo
416     *draw_info;
417
418   GradientInfo
419     *gradient;
420
421   MagickBooleanType
422     status;
423
424   /*
425     Set gradient start-stop end points.
426   */
427   assert(image != (const Image *) NULL);
428   assert(image->signature == MagickCoreSignature);
429   if (image->debug != MagickFalse)
430     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
431   assert(stops != (const StopInfo *) NULL);
432   assert(number_stops > 0);
433   draw_info=AcquireDrawInfo();
434   gradient=(&draw_info->gradient);
435   gradient->type=type;
436   gradient->bounding_box.width=image->columns;
437   gradient->bounding_box.height=image->rows;
438   artifact=GetImageArtifact(image,"gradient:bounding-box");
439   if (artifact != (const char *) NULL)
440     (void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box);
441   gradient->gradient_vector.x2=(double) image->columns;
442   gradient->gradient_vector.y2=(double) image->rows;
443   artifact=GetImageArtifact(image,"gradient:direction");
444   if (artifact != (const char *) NULL)
445     {
446       GravityType
447         direction;
448
449       direction=(GravityType) ParseCommandOption(MagickGravityOptions,
450         MagickFalse,artifact);
451       switch (direction)
452       {
453         case NorthWestGravity:
454         {
455           gradient->gradient_vector.x1=(double) image->columns;
456           gradient->gradient_vector.y1=(double) image->rows;
457           gradient->gradient_vector.x2=0.0;
458           gradient->gradient_vector.y2=0.0;
459           break;
460         }
461         case NorthGravity:
462         {
463           gradient->gradient_vector.x1=0.0;
464           gradient->gradient_vector.y1=(double) image->rows;
465           gradient->gradient_vector.x2=0.0;
466           gradient->gradient_vector.y2=0.0;
467           break;
468         }
469         case NorthEastGravity:
470         {
471           gradient->gradient_vector.x1=0.0;
472           gradient->gradient_vector.y1=(double) image->rows;
473           gradient->gradient_vector.x2=(double) image->columns;
474           gradient->gradient_vector.y2=0.0;
475           break;
476         }
477         case WestGravity:
478         {
479           gradient->gradient_vector.x1=(double) image->columns;
480           gradient->gradient_vector.y1=0.0;
481           gradient->gradient_vector.x2=0.0;
482           gradient->gradient_vector.y2=0.0;
483           break;
484         }
485         case EastGravity:
486         {
487           gradient->gradient_vector.x1=0.0;
488           gradient->gradient_vector.y1=0.0;
489           gradient->gradient_vector.x2=(double) image->columns;
490           gradient->gradient_vector.y2=0.0;
491           break;
492         }
493         case SouthWestGravity:
494         {
495           gradient->gradient_vector.x1=(double) image->columns;
496           gradient->gradient_vector.y1=0.0;
497           gradient->gradient_vector.x2=0.0;
498           gradient->gradient_vector.y2=(double) image->rows;
499           break;
500         }
501         case SouthGravity:
502         {
503           gradient->gradient_vector.x1=0.0;
504           gradient->gradient_vector.y1=0.0;
505           gradient->gradient_vector.x2=0.0;
506           gradient->gradient_vector.y2=(double) image->columns;
507           break;
508         }
509         case SouthEastGravity:
510         {
511           gradient->gradient_vector.x1=0.0;
512           gradient->gradient_vector.y1=0.0;
513           gradient->gradient_vector.x2=(double) image->columns;
514           gradient->gradient_vector.y2=(double) image->rows;
515           break;
516         }
517         default:
518           break;
519       }
520     }
521   artifact=GetImageArtifact(image,"gradient:angle");
522   if (artifact != (const char *) NULL)
523     gradient->angle=StringToDouble(artifact,(char **) NULL);
524   artifact=GetImageArtifact(image,"gradient:vector");
525   if (artifact != (const char *) NULL)
526     (void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf",
527       &gradient->gradient_vector.x1,&gradient->gradient_vector.y1,
528       &gradient->gradient_vector.x2,&gradient->gradient_vector.y2);
529   if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) &&
530       (GetImageArtifact(image,"gradient:direction") == (const char *) NULL) &&
531       (GetImageArtifact(image,"gradient:extent") == (const char *) NULL) &&
532       (GetImageArtifact(image,"gradient:vector") == (const char *) NULL))
533     if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0))
534       gradient->gradient_vector.x2=0.0;
535   gradient->center.x=(double) gradient->gradient_vector.x2/2.0;
536   gradient->center.y=(double) gradient->gradient_vector.y2/2.0;
537   artifact=GetImageArtifact(image,"gradient:center");
538   if (artifact != (const char *) NULL)
539     (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x,
540       &gradient->center.y);
541   artifact=GetImageArtifact(image,"gradient:angle");
542   if ((type == LinearGradient) && (artifact != (const char *) NULL))
543     {
544       double
545         sine,
546         cosine,
547         distance;
548
549       /*
550         Reference https://drafts.csswg.org/css-images-3/#linear-gradients.
551       */
552       sine=sin((double) DegreesToRadians(gradient->angle-90.0));
553       cosine=cos((double) DegreesToRadians(gradient->angle-90.0));
554       distance=fabs((double) image->columns*cosine)+
555         fabs((double) image->rows*sine);
556       gradient->gradient_vector.x1=0.5*(image->columns-distance*cosine);
557       gradient->gradient_vector.y1=0.5*(image->rows-distance*sine);
558       gradient->gradient_vector.x2=0.5*(image->columns+distance*cosine);
559       gradient->gradient_vector.y2=0.5*(image->rows+distance*sine);
560     }
561   gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
562   gradient->radii.y=gradient->radii.x;
563   artifact=GetImageArtifact(image,"gradient:extent");
564   if (artifact != (const char *) NULL)
565     {
566       if (LocaleCompare(artifact,"Circle") == 0)
567         {
568           gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
569           gradient->radii.y=gradient->radii.x;
570         }
571       if (LocaleCompare(artifact,"Diagonal") == 0)
572         {
573           gradient->radii.x=(double) (sqrt(image->columns*image->columns+
574             image->rows*image->rows))/2.0;
575           gradient->radii.y=gradient->radii.x;
576         }
577       if (LocaleCompare(artifact,"Ellipse") == 0)
578         {
579           gradient->radii.x=(double) image->columns/2.0;
580           gradient->radii.y=(double) image->rows/2.0;
581         }
582       if (LocaleCompare(artifact,"Maximum") == 0)
583         {
584           gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
585           gradient->radii.y=gradient->radii.x;
586         }
587       if (LocaleCompare(artifact,"Minimum") == 0)
588         {
589           gradient->radii.x=(double) (MagickMin(image->columns,image->rows))/
590             2.0;
591           gradient->radii.y=gradient->radii.x;
592         }
593     }
594   artifact=GetImageArtifact(image,"gradient:radii");
595   if (artifact != (const char *) NULL)
596     (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x,
597       &gradient->radii.y);
598   gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y);
599   gradient->spread=method;
600   /*
601     Define the gradient to fill between the stops.
602   */
603   gradient->number_stops=number_stops;
604   gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops,
605     sizeof(*gradient->stops));
606   if (gradient->stops == (StopInfo *) NULL)
607     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
608       image->filename);
609   (void) CopyMagickMemory(gradient->stops,stops,(size_t) number_stops*
610     sizeof(*stops));
611   /*
612     Draw a gradient on the image.
613   */
614   status=DrawGradientImage(image,draw_info,exception);
615   draw_info=DestroyDrawInfo(draw_info);
616   return(status);
617 }
618 \f
619 /*
620 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
621 %                                                                             %
622 %                                                                             %
623 %                                                                             %
624 %     O i l P a i n t I m a g e                                               %
625 %                                                                             %
626 %                                                                             %
627 %                                                                             %
628 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
629 %
630 %  OilPaintImage() applies a special effect filter that simulates an oil
631 %  painting.  Each pixel is replaced by the most frequent color occurring
632 %  in a circular region defined by radius.
633 %
634 %  The format of the OilPaintImage method is:
635 %
636 %      Image *OilPaintImage(const Image *image,const double radius,
637 %        const double sigma,ExceptionInfo *exception)
638 %
639 %  A description of each parameter follows:
640 %
641 %    o image: the image.
642 %
643 %    o radius: the radius of the circular neighborhood.
644 %
645 %    o sigma: the standard deviation of the Gaussian, in pixels.
646 %
647 %    o exception: return any errors or warnings in this structure.
648 %
649 */
650
651 static size_t **DestroyHistogramThreadSet(size_t **histogram)
652 {
653   register ssize_t
654     i;
655
656   assert(histogram != (size_t **) NULL);
657   for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
658     if (histogram[i] != (size_t *) NULL)
659       histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]);
660   histogram=(size_t **) RelinquishMagickMemory(histogram);
661   return(histogram);
662 }
663
664 static size_t **AcquireHistogramThreadSet(const size_t count)
665 {
666   register ssize_t
667     i;
668
669   size_t
670     **histogram,
671     number_threads;
672
673   number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
674   histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram));
675   if (histogram == (size_t **) NULL)
676     return((size_t **) NULL);
677   (void) ResetMagickMemory(histogram,0,number_threads*sizeof(*histogram));
678   for (i=0; i < (ssize_t) number_threads; i++)
679   {
680     histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram));
681     if (histogram[i] == (size_t *) NULL)
682       return(DestroyHistogramThreadSet(histogram));
683   }
684   return(histogram);
685 }
686
687 MagickExport Image *OilPaintImage(const Image *image,const double radius,
688   const double sigma,ExceptionInfo *exception)
689 {
690 #define NumberPaintBins  256
691 #define OilPaintImageTag  "OilPaint/Image"
692
693   CacheView
694     *image_view,
695     *paint_view;
696
697   Image
698     *linear_image,
699     *paint_image;
700
701   MagickBooleanType
702     status;
703
704   MagickOffsetType
705     progress;
706
707   size_t
708     **histograms,
709     width;
710
711   ssize_t
712     center,
713     y;
714
715   /*
716     Initialize painted image attributes.
717   */
718   assert(image != (const Image *) NULL);
719   assert(image->signature == MagickCoreSignature);
720   if (image->debug != MagickFalse)
721     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
722   assert(exception != (ExceptionInfo *) NULL);
723   assert(exception->signature == MagickCoreSignature);
724   width=GetOptimalKernelWidth2D(radius,sigma);
725   linear_image=CloneImage(image,0,0,MagickTrue,exception);
726   paint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
727   if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL))
728     {
729       if (linear_image != (Image *) NULL)
730         linear_image=DestroyImage(linear_image);
731       if (paint_image != (Image *) NULL)
732         linear_image=DestroyImage(paint_image);
733       return((Image *) NULL);
734     }
735   if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse)
736     {
737       linear_image=DestroyImage(linear_image);
738       paint_image=DestroyImage(paint_image);
739       return((Image *) NULL);
740     }
741   histograms=AcquireHistogramThreadSet(NumberPaintBins);
742   if (histograms == (size_t **) NULL)
743     {
744       linear_image=DestroyImage(linear_image);
745       paint_image=DestroyImage(paint_image);
746       ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
747     }
748   /*
749     Oil paint image.
750   */
751   status=MagickTrue;
752   progress=0;
753   center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)*
754     (width/2L)+GetPixelChannels(linear_image)*(width/2L);
755   image_view=AcquireVirtualCacheView(linear_image,exception);
756   paint_view=AcquireAuthenticCacheView(paint_image,exception);
757 #if defined(MAGICKCORE_OPENMP_SUPPORT)
758   #pragma omp parallel for schedule(static,4) shared(progress,status) \
759     magick_threads(linear_image,paint_image,linear_image->rows,1)
760 #endif
761   for (y=0; y < (ssize_t) linear_image->rows; y++)
762   {
763     register const Quantum
764       *magick_restrict p;
765
766     register Quantum
767       *magick_restrict q;
768
769     register size_t
770       *histogram;
771
772     register ssize_t
773       x;
774
775     if (status == MagickFalse)
776       continue;
777     p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
778       (width/2L),linear_image->columns+width,width,exception);
779     q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1,
780       exception);
781     if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
782       {
783         status=MagickFalse;
784         continue;
785       }
786     histogram=histograms[GetOpenMPThreadId()];
787     for (x=0; x < (ssize_t) linear_image->columns; x++)
788     {
789       register ssize_t
790         i,
791         u;
792
793       size_t
794         count;
795
796       ssize_t
797         j,
798         k,
799         n,
800         v;
801
802       /*
803         Assign most frequent color.
804       */
805       k=0;
806       j=0;
807       count=0;
808       (void) ResetMagickMemory(histogram,0,NumberPaintBins* sizeof(*histogram));
809       for (v=0; v < (ssize_t) width; v++)
810       {
811         for (u=0; u < (ssize_t) width; u++)
812         {
813           n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(
814             linear_image,p+GetPixelChannels(linear_image)*(u+k))));
815           histogram[n]++;
816           if (histogram[n] > count)
817             {
818               j=k+u;
819               count=histogram[n];
820             }
821         }
822         k+=(ssize_t) (linear_image->columns+width);
823       }
824       for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++)
825       {
826         PixelChannel channel=GetPixelChannelChannel(linear_image,i);
827         PixelTrait traits=GetPixelChannelTraits(linear_image,channel);
828         PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel);
829         if ((traits == UndefinedPixelTrait) ||
830             (paint_traits == UndefinedPixelTrait))
831           continue;
832         if (((paint_traits & CopyPixelTrait) != 0) ||
833             (GetPixelWriteMask(linear_image,p) == 0))
834           {
835             SetPixelChannel(paint_image,channel,p[center+i],q);
836             continue;
837           }
838         SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+
839           i],q);
840       }
841       p+=GetPixelChannels(linear_image);
842       q+=GetPixelChannels(paint_image);
843     }
844     if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse)
845       status=MagickFalse;
846     if (linear_image->progress_monitor != (MagickProgressMonitor) NULL)
847       {
848         MagickBooleanType
849           proceed;
850
851 #if defined(MAGICKCORE_OPENMP_SUPPORT)
852         #pragma omp critical (MagickCore_OilPaintImage)
853 #endif
854         proceed=SetImageProgress(linear_image,OilPaintImageTag,progress++,
855           linear_image->rows);
856         if (proceed == MagickFalse)
857           status=MagickFalse;
858       }
859   }
860   paint_view=DestroyCacheView(paint_view);
861   image_view=DestroyCacheView(image_view);
862   histograms=DestroyHistogramThreadSet(histograms);
863   linear_image=DestroyImage(linear_image);
864   if (status == MagickFalse)
865     paint_image=DestroyImage(paint_image);
866   return(paint_image);
867 }
868 \f
869 /*
870 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
871 %                                                                             %
872 %                                                                             %
873 %                                                                             %
874 %     O p a q u e P a i n t I m a g e                                         %
875 %                                                                             %
876 %                                                                             %
877 %                                                                             %
878 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
879 %
880 %  OpaquePaintImage() changes any pixel that matches color with the color
881 %  defined by fill argument.
882 %
883 %  By default color must match a particular pixel color exactly.  However, in
884 %  many cases two colors may differ by a small amount.  Fuzz defines how much
885 %  tolerance is acceptable to consider two colors as the same.  For example,
886 %  set fuzz to 10 and the color red at intensities of 100 and 102 respectively
887 %  are now interpreted as the same color.
888 %
889 %  The format of the OpaquePaintImage method is:
890 %
891 %      MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target,
892 %        const PixelInfo *fill,const MagickBooleanType invert,
893 %        ExceptionInfo *exception)
894 %
895 %  A description of each parameter follows:
896 %
897 %    o image: the image.
898 %
899 %    o target: the RGB value of the target color.
900 %
901 %    o fill: the replacement color.
902 %
903 %    o invert: paint any pixel that does not match the target color.
904 %
905 %    o exception: return any errors or warnings in this structure.
906 %
907 */
908 MagickExport MagickBooleanType OpaquePaintImage(Image *image,
909   const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert,
910   ExceptionInfo *exception)
911 {
912 #define OpaquePaintImageTag  "Opaque/Image"
913
914   CacheView
915     *image_view;
916
917   MagickBooleanType
918     status;
919
920   MagickOffsetType
921     progress;
922
923   PixelInfo
924     conform_fill,
925     conform_target,
926     zero;
927
928   ssize_t
929     y;
930
931   assert(image != (Image *) NULL);
932   assert(image->signature == MagickCoreSignature);
933   assert(target != (PixelInfo *) NULL);
934   assert(fill != (PixelInfo *) NULL);
935   if (image->debug != MagickFalse)
936     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
937   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
938     return(MagickFalse);
939   ConformPixelInfo(image,fill,&conform_fill,exception);
940   ConformPixelInfo(image,target,&conform_target,exception);
941   /*
942     Make image color opaque.
943   */
944   status=MagickTrue;
945   progress=0;
946   GetPixelInfo(image,&zero);
947   image_view=AcquireAuthenticCacheView(image,exception);
948 #if defined(MAGICKCORE_OPENMP_SUPPORT)
949   #pragma omp parallel for schedule(static,4) shared(progress,status) \
950     magick_threads(image,image,image->rows,1)
951 #endif
952   for (y=0; y < (ssize_t) image->rows; y++)
953   {
954     PixelInfo
955       pixel;
956
957     register Quantum
958       *magick_restrict q;
959
960     register ssize_t
961       x;
962
963     if (status == MagickFalse)
964       continue;
965     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
966     if (q == (Quantum *) NULL)
967       {
968         status=MagickFalse;
969         continue;
970       }
971     pixel=zero;
972     for (x=0; x < (ssize_t) image->columns; x++)
973     {
974       if (GetPixelWriteMask(image,q) == 0)
975         {
976           q+=GetPixelChannels(image);
977           continue;
978         }
979       GetPixelInfoPixel(image,q,&pixel);
980       if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert)
981         SetPixelViaPixelInfo(image,&conform_fill,q);
982       q+=GetPixelChannels(image);
983     }
984     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
985       status=MagickFalse;
986     if (image->progress_monitor != (MagickProgressMonitor) NULL)
987       {
988         MagickBooleanType
989           proceed;
990
991 #if defined(MAGICKCORE_OPENMP_SUPPORT)
992         #pragma omp critical (MagickCore_OpaquePaintImage)
993 #endif
994         proceed=SetImageProgress(image,OpaquePaintImageTag,progress++,
995           image->rows);
996         if (proceed == MagickFalse)
997           status=MagickFalse;
998       }
999   }
1000   image_view=DestroyCacheView(image_view);
1001   return(status);
1002 }
1003 \f
1004 /*
1005 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1006 %                                                                             %
1007 %                                                                             %
1008 %                                                                             %
1009 %     T r a n s p a r e n t P a i n t I m a g e                               %
1010 %                                                                             %
1011 %                                                                             %
1012 %                                                                             %
1013 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1014 %
1015 %  TransparentPaintImage() changes the opacity value associated with any pixel
1016 %  that matches color to the value defined by opacity.
1017 %
1018 %  By default color must match a particular pixel color exactly.  However, in
1019 %  many cases two colors may differ by a small amount.  Fuzz defines how much
1020 %  tolerance is acceptable to consider two colors as the same.  For example,
1021 %  set fuzz to 10 and the color red at intensities of 100 and 102 respectively
1022 %  are now interpreted as the same color.
1023 %
1024 %  The format of the TransparentPaintImage method is:
1025 %
1026 %      MagickBooleanType TransparentPaintImage(Image *image,
1027 %        const PixelInfo *target,const Quantum opacity,
1028 %        const MagickBooleanType invert,ExceptionInfo *exception)
1029 %
1030 %  A description of each parameter follows:
1031 %
1032 %    o image: the image.
1033 %
1034 %    o target: the target color.
1035 %
1036 %    o opacity: the replacement opacity value.
1037 %
1038 %    o invert: paint any pixel that does not match the target color.
1039 %
1040 %    o exception: return any errors or warnings in this structure.
1041 %
1042 */
1043 MagickExport MagickBooleanType TransparentPaintImage(Image *image,
1044   const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert,
1045   ExceptionInfo *exception)
1046 {
1047 #define TransparentPaintImageTag  "Transparent/Image"
1048
1049   CacheView
1050     *image_view;
1051
1052   MagickBooleanType
1053     status;
1054
1055   MagickOffsetType
1056     progress;
1057
1058   PixelInfo
1059     zero;
1060
1061   ssize_t
1062     y;
1063
1064   assert(image != (Image *) NULL);
1065   assert(image->signature == MagickCoreSignature);
1066   assert(target != (PixelInfo *) NULL);
1067   if (image->debug != MagickFalse)
1068     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1069   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
1070     return(MagickFalse);
1071   if (image->alpha_trait == UndefinedPixelTrait)
1072     (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
1073   /*
1074     Make image color transparent.
1075   */
1076   status=MagickTrue;
1077   progress=0;
1078   GetPixelInfo(image,&zero);
1079   image_view=AcquireAuthenticCacheView(image,exception);
1080 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1081   #pragma omp parallel for schedule(static,4) shared(progress,status) \
1082     magick_threads(image,image,image->rows,1)
1083 #endif
1084   for (y=0; y < (ssize_t) image->rows; y++)
1085   {
1086     PixelInfo
1087       pixel;
1088
1089     register ssize_t
1090       x;
1091
1092     register Quantum
1093       *magick_restrict q;
1094
1095     if (status == MagickFalse)
1096       continue;
1097     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1098     if (q == (Quantum *) NULL)
1099       {
1100         status=MagickFalse;
1101         continue;
1102       }
1103     pixel=zero;
1104     for (x=0; x < (ssize_t) image->columns; x++)
1105     {
1106       if (GetPixelWriteMask(image,q) == 0)
1107         {
1108           q+=GetPixelChannels(image);
1109           continue;
1110         }
1111       GetPixelInfoPixel(image,q,&pixel);
1112       if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
1113         SetPixelAlpha(image,opacity,q);
1114       q+=GetPixelChannels(image);
1115     }
1116     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1117       status=MagickFalse;
1118     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1119       {
1120         MagickBooleanType
1121           proceed;
1122
1123 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1124         #pragma omp critical (MagickCore_TransparentPaintImage)
1125 #endif
1126         proceed=SetImageProgress(image,TransparentPaintImageTag,progress++,
1127           image->rows);
1128         if (proceed == MagickFalse)
1129           status=MagickFalse;
1130       }
1131   }
1132   image_view=DestroyCacheView(image_view);
1133   return(status);
1134 }
1135 \f
1136 /*
1137 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1138 %                                                                             %
1139 %                                                                             %
1140 %                                                                             %
1141 %     T r a n s p a r e n t P a i n t I m a g e C h r o m a                   %
1142 %                                                                             %
1143 %                                                                             %
1144 %                                                                             %
1145 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1146 %
1147 %  TransparentPaintImageChroma() changes the opacity value associated with any
1148 %  pixel that matches color to the value defined by opacity.
1149 %
1150 %  As there is one fuzz value for the all the channels, TransparentPaintImage()
1151 %  is not suitable for the operations like chroma, where the tolerance for
1152 %  similarity of two color component (RGB) can be different. Thus we define
1153 %  this method to take two target pixels (one low and one high) and all the
1154 %  pixels of an image which are lying between these two pixels are made
1155 %  transparent.
1156 %
1157 %  The format of the TransparentPaintImageChroma method is:
1158 %
1159 %      MagickBooleanType TransparentPaintImageChroma(Image *image,
1160 %        const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
1161 %        const MagickBooleanType invert,ExceptionInfo *exception)
1162 %
1163 %  A description of each parameter follows:
1164 %
1165 %    o image: the image.
1166 %
1167 %    o low: the low target color.
1168 %
1169 %    o high: the high target color.
1170 %
1171 %    o opacity: the replacement opacity value.
1172 %
1173 %    o invert: paint any pixel that does not match the target color.
1174 %
1175 %    o exception: return any errors or warnings in this structure.
1176 %
1177 */
1178 MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image,
1179   const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
1180   const MagickBooleanType invert,ExceptionInfo *exception)
1181 {
1182 #define TransparentPaintImageTag  "Transparent/Image"
1183
1184   CacheView
1185     *image_view;
1186
1187   MagickBooleanType
1188     status;
1189
1190   MagickOffsetType
1191     progress;
1192
1193   ssize_t
1194     y;
1195
1196   assert(image != (Image *) NULL);
1197   assert(image->signature == MagickCoreSignature);
1198   assert(high != (PixelInfo *) NULL);
1199   assert(low != (PixelInfo *) NULL);
1200   if (image->debug != MagickFalse)
1201     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1202   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
1203     return(MagickFalse);
1204   if (image->alpha_trait == UndefinedPixelTrait)
1205     (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
1206   /*
1207     Make image color transparent.
1208   */
1209   status=MagickTrue;
1210   progress=0;
1211   image_view=AcquireAuthenticCacheView(image,exception);
1212 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1213   #pragma omp parallel for schedule(static,4) shared(progress,status) \
1214     magick_threads(image,image,image->rows,1)
1215 #endif
1216   for (y=0; y < (ssize_t) image->rows; y++)
1217   {
1218     MagickBooleanType
1219       match;
1220
1221     PixelInfo
1222       pixel;
1223
1224     register Quantum
1225       *magick_restrict q;
1226
1227     register ssize_t
1228       x;
1229
1230     if (status == MagickFalse)
1231       continue;
1232     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1233     if (q == (Quantum *) NULL)
1234       {
1235         status=MagickFalse;
1236         continue;
1237       }
1238     GetPixelInfo(image,&pixel);
1239     for (x=0; x < (ssize_t) image->columns; x++)
1240     {
1241       if (GetPixelWriteMask(image,q) == 0)
1242         {
1243           q+=GetPixelChannels(image);
1244           continue;
1245         }
1246       GetPixelInfoPixel(image,q,&pixel);
1247       match=((pixel.red >= low->red) && (pixel.red <= high->red) &&
1248         (pixel.green >= low->green) && (pixel.green <= high->green) &&
1249         (pixel.blue  >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue :
1250         MagickFalse;
1251       if (match != invert)
1252         SetPixelAlpha(image,opacity,q);
1253       q+=GetPixelChannels(image);
1254     }
1255     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1256       status=MagickFalse;
1257     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1258       {
1259         MagickBooleanType
1260           proceed;
1261
1262 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1263         #pragma omp critical (MagickCore_TransparentPaintImageChroma)
1264 #endif
1265         proceed=SetImageProgress(image,TransparentPaintImageTag,progress++,
1266           image->rows);
1267         if (proceed == MagickFalse)
1268           status=MagickFalse;
1269       }
1270   }
1271   image_view=DestroyCacheView(image_view);
1272   return(status);
1273 }