• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                      SSSSS  H   H  EEEEE   AAA    RRRR                      %
7 %                      SS     H   H  E      A   A   R   R                     %
8 %                       SSS   HHHHH  EEE    AAAAA   RRRR                      %
9 %                         SS  H   H  E      A   A   R R                       %
10 %                      SSSSS  H   H  EEEEE  A   A   R  R                      %
11 %                                                                             %
12 %                                                                             %
13 %    MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle     %
14 %                                                                             %
15 %                               Software Design                               %
16 %                                    Cristy                                   %
17 %                                  July 1992                                  %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2021 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 %    https://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 %  The XShearImage() and YShearImage() methods are based on the paper "A Fast
37 %  Algorithm for General Raster Rotation" by Alan W. Paeth, Graphics
38 %  Interface '86 (Vancouver).  ShearRotateImage() is adapted from a similar
39 %  method based on the Paeth paper written by Michael Halle of the Spatial
40 %  Imaging Group, MIT Media Lab.
41 %
42 */
43 
44 /*
45   Include declarations.
46 */
47 #include "MagickCore/studio.h"
48 #include "MagickCore/artifact.h"
49 #include "MagickCore/attribute.h"
50 #include "MagickCore/blob-private.h"
51 #include "MagickCore/cache-private.h"
52 #include "MagickCore/channel.h"
53 #include "MagickCore/color-private.h"
54 #include "MagickCore/colorspace-private.h"
55 #include "MagickCore/composite.h"
56 #include "MagickCore/composite-private.h"
57 #include "MagickCore/decorate.h"
58 #include "MagickCore/distort.h"
59 #include "MagickCore/draw.h"
60 #include "MagickCore/exception.h"
61 #include "MagickCore/exception-private.h"
62 #include "MagickCore/gem.h"
63 #include "MagickCore/geometry.h"
64 #include "MagickCore/image.h"
65 #include "MagickCore/image-private.h"
66 #include "MagickCore/matrix.h"
67 #include "MagickCore/memory_.h"
68 #include "MagickCore/list.h"
69 #include "MagickCore/monitor.h"
70 #include "MagickCore/monitor-private.h"
71 #include "MagickCore/nt-base-private.h"
72 #include "MagickCore/pixel-accessor.h"
73 #include "MagickCore/quantum.h"
74 #include "MagickCore/resource_.h"
75 #include "MagickCore/shear.h"
76 #include "MagickCore/statistic.h"
77 #include "MagickCore/string_.h"
78 #include "MagickCore/string-private.h"
79 #include "MagickCore/thread-private.h"
80 #include "MagickCore/threshold.h"
81 #include "MagickCore/transform.h"
82 
83 /*
84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
85 %                                                                             %
86 %                                                                             %
87 %                                                                             %
88 +   C r o p T o F i t I m a g e                                               %
89 %                                                                             %
90 %                                                                             %
91 %                                                                             %
92 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
93 %
94 %  CropToFitImage() crops the sheared image as determined by the bounding box
95 %  as defined by width and height and shearing angles.
96 %
97 %  The format of the CropToFitImage method is:
98 %
99 %      MagickBooleanType CropToFitImage(Image **image,
100 %        const double x_shear,const double x_shear,
101 %        const double width,const double height,
102 %        const MagickBooleanType rotate,ExceptionInfo *exception)
103 %
104 %  A description of each parameter follows.
105 %
106 %    o image: the image.
107 %
108 %    o x_shear, y_shear, width, height: Defines a region of the image to crop.
109 %
110 %    o exception: return any errors or warnings in this structure.
111 %
112 */
CropToFitImage(Image ** image,const double x_shear,const double y_shear,const double width,const double height,const MagickBooleanType rotate,ExceptionInfo * exception)113 static MagickBooleanType CropToFitImage(Image **image,
114   const double x_shear,const double y_shear,
115   const double width,const double height,
116   const MagickBooleanType rotate,ExceptionInfo *exception)
117 {
118   Image
119     *crop_image;
120 
121   PointInfo
122     extent[4],
123     min,
124     max;
125 
126   RectangleInfo
127     geometry,
128     page;
129 
130   ssize_t
131     i;
132 
133   /*
134     Calculate the rotated image size.
135   */
136   extent[0].x=(double) (-width/2.0);
137   extent[0].y=(double) (-height/2.0);
138   extent[1].x=(double) width/2.0;
139   extent[1].y=(double) (-height/2.0);
140   extent[2].x=(double) (-width/2.0);
141   extent[2].y=(double) height/2.0;
142   extent[3].x=(double) width/2.0;
143   extent[3].y=(double) height/2.0;
144   for (i=0; i < 4; i++)
145   {
146     extent[i].x+=x_shear*extent[i].y;
147     extent[i].y+=y_shear*extent[i].x;
148     if (rotate != MagickFalse)
149       extent[i].x+=x_shear*extent[i].y;
150     extent[i].x+=(double) (*image)->columns/2.0;
151     extent[i].y+=(double) (*image)->rows/2.0;
152   }
153   min=extent[0];
154   max=extent[0];
155   for (i=1; i < 4; i++)
156   {
157     if (min.x > extent[i].x)
158       min.x=extent[i].x;
159     if (min.y > extent[i].y)
160       min.y=extent[i].y;
161     if (max.x < extent[i].x)
162       max.x=extent[i].x;
163     if (max.y < extent[i].y)
164       max.y=extent[i].y;
165   }
166   geometry.x=CastDoubleToLong(ceil(min.x-0.5));
167   geometry.y=CastDoubleToLong(ceil(min.y-0.5));
168   geometry.width=(size_t) CastDoubleToLong(floor(max.x-min.x+0.5));
169   geometry.height=(size_t) CastDoubleToLong(floor(max.y-min.y+0.5));
170   page=(*image)->page;
171   (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page);
172   crop_image=CropImage(*image,&geometry,exception);
173   if (crop_image == (Image *) NULL)
174     return(MagickFalse);
175   crop_image->page=page;
176   *image=DestroyImage(*image);
177   *image=crop_image;
178   return(MagickTrue);
179 }
180 
181 /*
182 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
183 %                                                                             %
184 %                                                                             %
185 %                                                                             %
186 %     D e s k e w I m a g e                                                   %
187 %                                                                             %
188 %                                                                             %
189 %                                                                             %
190 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
191 %
192 %  DeskewImage() removes skew from the image.  Skew is an artifact that
193 %  occurs in scanned images because of the camera being misaligned,
194 %  imperfections in the scanning or surface, or simply because the paper was
195 %  not placed completely flat when scanned.
196 %
197 %  The result will be auto-croped if the artifact "deskew:auto-crop" is
198 %  defined, while the amount the image is to be deskewed, in degrees is also
199 %  saved as the artifact "deskew:angle".
200 %
201 %  The format of the DeskewImage method is:
202 %
203 %      Image *DeskewImage(const Image *image,const double threshold,
204 %        ExceptionInfo *exception)
205 %
206 %  A description of each parameter follows:
207 %
208 %    o image: the image.
209 %
210 %    o threshold: separate background from foreground.
211 %
212 %    o exception: return any errors or warnings in this structure.
213 %
214 */
215 
RadonProjection(const Image * image,MatrixInfo * source_matrixs,MatrixInfo * destination_matrixs,const ssize_t sign,size_t * projection)216 static void RadonProjection(const Image *image,MatrixInfo *source_matrixs,
217   MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection)
218 {
219   MatrixInfo
220     *swap;
221 
222   MatrixInfo
223     *p,
224     *q;
225 
226   ssize_t
227     x;
228 
229   size_t
230     step;
231 
232   p=source_matrixs;
233   q=destination_matrixs;
234   for (step=1; step < GetMatrixColumns(p); step*=2)
235   {
236     for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step)
237     {
238       ssize_t
239         i;
240 
241       ssize_t
242         y;
243 
244       unsigned short
245         element,
246         neighbor;
247 
248       for (i=0; i < (ssize_t) step; i++)
249       {
250         for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++)
251         {
252           if (GetMatrixElement(p,x+i,y,&element) == MagickFalse)
253             continue;
254           if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse)
255             continue;
256           neighbor+=element;
257           if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse)
258             continue;
259           if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse)
260             continue;
261           neighbor+=element;
262           if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse)
263             continue;
264         }
265         for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++)
266         {
267           if (GetMatrixElement(p,x+i,y,&element) == MagickFalse)
268             continue;
269           if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse)
270             continue;
271           neighbor+=element;
272           if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse)
273             continue;
274           if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse)
275             continue;
276         }
277         for ( ; y < (ssize_t) GetMatrixRows(p); y++)
278         {
279           if (GetMatrixElement(p,x+i,y,&element) == MagickFalse)
280             continue;
281           if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse)
282             continue;
283           if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse)
284             continue;
285         }
286       }
287     }
288     swap=p;
289     p=q;
290     q=swap;
291   }
292 #if defined(MAGICKCORE_OPENMP_SUPPORT)
293   #pragma omp parallel for schedule(static) \
294     magick_number_threads(image,image,GetMatrixColumns(p),1)
295 #endif
296   for (x=0; x < (ssize_t) GetMatrixColumns(p); x++)
297   {
298     ssize_t
299       y;
300 
301     size_t
302       sum;
303 
304     sum=0;
305     for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++)
306     {
307       ssize_t
308         delta;
309 
310       unsigned short
311         element,
312         neighbor;
313 
314       if (GetMatrixElement(p,x,y,&element) == MagickFalse)
315         continue;
316       if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse)
317         continue;
318       delta=(ssize_t) element-(ssize_t) neighbor;
319       sum+=delta*delta;
320     }
321     projection[GetMatrixColumns(p)+sign*x-1]=sum;
322   }
323 }
324 
RadonTransform(const Image * image,const double threshold,size_t * projection,ExceptionInfo * exception)325 static MagickBooleanType RadonTransform(const Image *image,
326   const double threshold,size_t *projection,ExceptionInfo *exception)
327 {
328   CacheView
329     *image_view;
330 
331   MatrixInfo
332     *destination_matrixs,
333     *source_matrixs;
334 
335   MagickBooleanType
336     status;
337 
338   size_t
339     count,
340     width;
341 
342   ssize_t
343     j,
344     y;
345 
346   unsigned char
347     c;
348 
349   unsigned short
350     bits[256];
351 
352   for (width=1; width < ((image->columns+7)/8); width<<=1) ;
353   source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short),
354     exception);
355   destination_matrixs=AcquireMatrixInfo(width,image->rows,
356     sizeof(unsigned short),exception);
357   if ((source_matrixs == (MatrixInfo *) NULL) ||
358       (destination_matrixs == (MatrixInfo *) NULL))
359     {
360       if (destination_matrixs != (MatrixInfo *) NULL)
361         destination_matrixs=DestroyMatrixInfo(destination_matrixs);
362       if (source_matrixs != (MatrixInfo *) NULL)
363         source_matrixs=DestroyMatrixInfo(source_matrixs);
364       return(MagickFalse);
365     }
366   if (NullMatrix(source_matrixs) == MagickFalse)
367     {
368       destination_matrixs=DestroyMatrixInfo(destination_matrixs);
369       source_matrixs=DestroyMatrixInfo(source_matrixs);
370       return(MagickFalse);
371     }
372   for (j=0; j < 256; j++)
373   {
374     c=(unsigned char) j;
375     for (count=0; c != 0; c>>=1)
376       count+=c & 0x01;
377     bits[j]=(unsigned short) count;
378   }
379   status=MagickTrue;
380   image_view=AcquireVirtualCacheView(image,exception);
381 #if defined(MAGICKCORE_OPENMP_SUPPORT)
382   #pragma omp parallel for schedule(static) shared(status) \
383     magick_number_threads(image,image,image->rows,1)
384 #endif
385   for (y=0; y < (ssize_t) image->rows; y++)
386   {
387     const Quantum
388       *magick_restrict p;
389 
390     ssize_t
391       i,
392       x;
393 
394     size_t
395       bit,
396       byte;
397 
398     unsigned short
399       value;
400 
401     if (status == MagickFalse)
402       continue;
403     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
404     if (p == (const Quantum *) NULL)
405       {
406         status=MagickFalse;
407         continue;
408       }
409     bit=0;
410     byte=0;
411     i=(ssize_t) (image->columns+7)/8;
412     for (x=0; x < (ssize_t) image->columns; x++)
413     {
414       byte<<=1;
415       if (((MagickRealType) GetPixelRed(image,p) < threshold) ||
416           ((MagickRealType) GetPixelGreen(image,p) < threshold) ||
417           ((MagickRealType) GetPixelBlue(image,p) < threshold))
418         byte|=0x01;
419       bit++;
420       if (bit == 8)
421         {
422           value=bits[byte];
423           (void) SetMatrixElement(source_matrixs,--i,y,&value);
424           bit=0;
425           byte=0;
426         }
427       p+=GetPixelChannels(image);
428     }
429     if (bit != 0)
430       {
431         byte<<=(8-bit);
432         value=bits[byte];
433         (void) SetMatrixElement(source_matrixs,--i,y,&value);
434       }
435   }
436   RadonProjection(image,source_matrixs,destination_matrixs,-1,projection);
437   (void) NullMatrix(source_matrixs);
438 #if defined(MAGICKCORE_OPENMP_SUPPORT)
439   #pragma omp parallel for schedule(static) shared(status) \
440     magick_number_threads(image,image,image->rows,1)
441 #endif
442   for (y=0; y < (ssize_t) image->rows; y++)
443   {
444     const Quantum
445       *magick_restrict p;
446 
447     ssize_t
448       i,
449       x;
450 
451     size_t
452       bit,
453       byte;
454 
455     unsigned short
456      value;
457 
458     if (status == MagickFalse)
459       continue;
460     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
461     if (p == (const Quantum *) NULL)
462       {
463         status=MagickFalse;
464         continue;
465       }
466     bit=0;
467     byte=0;
468     i=0;
469     for (x=0; x < (ssize_t) image->columns; x++)
470     {
471       byte<<=1;
472       if (((MagickRealType) GetPixelRed(image,p) < threshold) ||
473           ((MagickRealType) GetPixelGreen(image,p) < threshold) ||
474           ((MagickRealType) GetPixelBlue(image,p) < threshold))
475         byte|=0x01;
476       bit++;
477       if (bit == 8)
478         {
479           value=bits[byte];
480           (void) SetMatrixElement(source_matrixs,i++,y,&value);
481           bit=0;
482           byte=0;
483         }
484       p+=GetPixelChannels(image);
485     }
486     if (bit != 0)
487       {
488         byte<<=(8-bit);
489         value=bits[byte];
490         (void) SetMatrixElement(source_matrixs,i++,y,&value);
491       }
492   }
493   RadonProjection(image,source_matrixs,destination_matrixs,1,projection);
494   image_view=DestroyCacheView(image_view);
495   destination_matrixs=DestroyMatrixInfo(destination_matrixs);
496   source_matrixs=DestroyMatrixInfo(source_matrixs);
497   return(MagickTrue);
498 }
499 
GetImageBackgroundColor(Image * image,const ssize_t offset,ExceptionInfo * exception)500 static void GetImageBackgroundColor(Image *image,const ssize_t offset,
501   ExceptionInfo *exception)
502 {
503   CacheView
504     *image_view;
505 
506   PixelInfo
507     background;
508 
509   double
510     count;
511 
512   ssize_t
513     y;
514 
515   /*
516     Compute average background color.
517   */
518   if (offset <= 0)
519     return;
520   GetPixelInfo(image,&background);
521   count=0.0;
522   image_view=AcquireVirtualCacheView(image,exception);
523   for (y=0; y < (ssize_t) image->rows; y++)
524   {
525     const Quantum
526       *magick_restrict p;
527 
528     ssize_t
529       x;
530 
531     if ((y >= offset) && (y < ((ssize_t) image->rows-offset)))
532       continue;
533     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
534     if (p == (const Quantum *) NULL)
535       continue;
536     for (x=0; x < (ssize_t) image->columns; x++)
537     {
538       if ((x >= offset) && (x < ((ssize_t) image->columns-offset)))
539         continue;
540       background.red+=QuantumScale*GetPixelRed(image,p);
541       background.green+=QuantumScale*GetPixelGreen(image,p);
542       background.blue+=QuantumScale*GetPixelBlue(image,p);
543       if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
544         background.alpha+=QuantumScale*GetPixelAlpha(image,p);
545       count++;
546       p+=GetPixelChannels(image);
547     }
548   }
549   image_view=DestroyCacheView(image_view);
550   image->background_color.red=(double) ClampToQuantum(QuantumRange*
551     background.red/count);
552   image->background_color.green=(double) ClampToQuantum(QuantumRange*
553     background.green/count);
554   image->background_color.blue=(double) ClampToQuantum(QuantumRange*
555     background.blue/count);
556   if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
557     image->background_color.alpha=(double) ClampToQuantum(QuantumRange*
558       background.alpha/count);
559 }
560 
DeskewImage(const Image * image,const double threshold,ExceptionInfo * exception)561 MagickExport Image *DeskewImage(const Image *image,const double threshold,
562   ExceptionInfo *exception)
563 {
564   AffineMatrix
565     affine_matrix;
566 
567   const char
568     *artifact;
569 
570   double
571     degrees;
572 
573   Image
574     *clone_image,
575     *crop_image,
576     *deskew_image,
577     *median_image;
578 
579   MagickBooleanType
580     status;
581 
582   RectangleInfo
583     geometry;
584 
585   ssize_t
586     i;
587 
588   size_t
589     max_projection,
590     *projection,
591     width;
592 
593   ssize_t
594     skew;
595 
596   /*
597     Compute deskew angle.
598   */
599   for (width=1; width < ((image->columns+7)/8); width<<=1) ;
600   projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1),
601     sizeof(*projection));
602   if (projection == (size_t *) NULL)
603     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
604   status=RadonTransform(image,threshold,projection,exception);
605   if (status == MagickFalse)
606     {
607       projection=(size_t *) RelinquishMagickMemory(projection);
608       ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
609     }
610   max_projection=0;
611   skew=0;
612   for (i=0; i < (ssize_t) (2*width-1); i++)
613   {
614     if (projection[i] > max_projection)
615       {
616         skew=i-(ssize_t) width+1;
617         max_projection=projection[i];
618       }
619   }
620   projection=(size_t *) RelinquishMagickMemory(projection);
621   degrees=RadiansToDegrees(-atan((double) skew/width/8));
622   if (image->debug != MagickFalse)
623     (void) LogMagickEvent(TransformEvent,GetMagickModule(),
624       "  Deskew angle: %g",degrees);
625   /*
626     Deskew image.
627   */
628   clone_image=CloneImage(image,0,0,MagickTrue,exception);
629   if (clone_image == (Image *) NULL)
630     return((Image *) NULL);
631   {
632     char
633       angle[MagickPathExtent];
634 
635     (void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees);
636     (void) SetImageArtifact(clone_image,"deskew:angle",angle);
637   }
638   (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod,
639     exception);
640   affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0)));
641   affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0)));
642   affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0))));
643   affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0)));
644   affine_matrix.tx=0.0;
645   affine_matrix.ty=0.0;
646   artifact=GetImageArtifact(image,"deskew:auto-crop");
647   if (IsStringTrue(artifact) == MagickFalse)
648     {
649       deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
650       clone_image=DestroyImage(clone_image);
651       return(deskew_image);
652     }
653   /*
654     Auto-crop image.
655   */
656   GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact),
657     exception);
658   deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception);
659   clone_image=DestroyImage(clone_image);
660   if (deskew_image == (Image *) NULL)
661     return((Image *) NULL);
662   median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception);
663   if (median_image == (Image *) NULL)
664     {
665       deskew_image=DestroyImage(deskew_image);
666       return((Image *) NULL);
667     }
668   geometry=GetImageBoundingBox(median_image,exception);
669   median_image=DestroyImage(median_image);
670   if (image->debug != MagickFalse)
671     (void) LogMagickEvent(TransformEvent,GetMagickModule(),"  Deskew geometry: "
672       "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
673       geometry.height,(double) geometry.x,(double) geometry.y);
674   crop_image=CropImage(deskew_image,&geometry,exception);
675   deskew_image=DestroyImage(deskew_image);
676   return(crop_image);
677 }
678 
679 /*
680 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
681 %                                                                             %
682 %                                                                             %
683 %                                                                             %
684 %   I n t e g r a l R o t a t e I m a g e                                     %
685 %                                                                             %
686 %                                                                             %
687 %                                                                             %
688 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
689 %
690 %  IntegralRotateImage() rotates the image an integral of 90 degrees.  It
691 %  allocates the memory necessary for the new Image structure and returns a
692 %  pointer to the rotated image.
693 %
694 %  The format of the IntegralRotateImage method is:
695 %
696 %      Image *IntegralRotateImage(const Image *image,size_t rotations,
697 %        ExceptionInfo *exception)
698 %
699 %  A description of each parameter follows.
700 %
701 %    o image: the image.
702 %
703 %    o rotations: Specifies the number of 90 degree rotations.
704 %
705 */
IntegralRotateImage(const Image * image,size_t rotations,ExceptionInfo * exception)706 MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations,
707   ExceptionInfo *exception)
708 {
709 #define RotateImageTag  "Rotate/Image"
710 
711   CacheView
712     *image_view,
713     *rotate_view;
714 
715   Image
716     *rotate_image;
717 
718   MagickBooleanType
719     status;
720 
721   MagickOffsetType
722     progress;
723 
724   RectangleInfo
725     page;
726 
727   /*
728     Initialize rotated image attributes.
729   */
730   assert(image != (Image *) NULL);
731   page=image->page;
732   rotations%=4;
733   switch (rotations)
734   {
735     case 0:
736     default:
737     {
738       rotate_image=CloneImage(image,0,0,MagickTrue,exception);
739       break;
740     }
741     case 2:
742     {
743       rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue,
744         exception);
745       break;
746     }
747     case 1:
748     case 3:
749     {
750       rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue,
751         exception);
752       break;
753     }
754   }
755   if (rotate_image == (Image *) NULL)
756     return((Image *) NULL);
757   if (rotations == 0)
758     return(rotate_image);
759   /*
760     Integral rotate the image.
761   */
762   status=MagickTrue;
763   progress=0;
764   image_view=AcquireVirtualCacheView(image,exception);
765   rotate_view=AcquireAuthenticCacheView(rotate_image,exception);
766   switch (rotations)
767   {
768     case 1:
769     {
770       size_t
771         tile_height,
772         tile_width;
773 
774       ssize_t
775         tile_y;
776 
777       /*
778         Rotate 90 degrees.
779       */
780       GetPixelCacheTileSize(image,&tile_width,&tile_height);
781       tile_width=image->columns;
782 #if defined(MAGICKCORE_OPENMP_SUPPORT)
783       #pragma omp parallel for schedule(static) shared(status) \
784         magick_number_threads(image,rotate_image,image->rows/tile_height,1)
785 #endif
786       for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
787       {
788         ssize_t
789           tile_x;
790 
791         if (status == MagickFalse)
792           continue;
793         tile_x=0;
794         for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
795         {
796           MagickBooleanType
797             sync;
798 
799           const Quantum
800             *magick_restrict p;
801 
802           Quantum
803             *magick_restrict q;
804 
805           ssize_t
806             y;
807 
808           size_t
809             height,
810             width;
811 
812           width=tile_width;
813           if ((tile_width+tile_x) > image->columns)
814             width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
815           height=tile_height;
816           if ((tile_height+tile_y) > image->rows)
817             height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
818           p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
819             exception);
820           if (p == (const Quantum *) NULL)
821             {
822               status=MagickFalse;
823               break;
824             }
825           for (y=0; y < (ssize_t) width; y++)
826           {
827             const Quantum
828               *magick_restrict tile_pixels;
829 
830             ssize_t
831               x;
832 
833             if (status == MagickFalse)
834               continue;
835             q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t)
836               (rotate_image->columns-(tile_y+height)),y+tile_x,height,1,
837               exception);
838             if (q == (Quantum *) NULL)
839               {
840                 status=MagickFalse;
841                 continue;
842               }
843             tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image);
844             for (x=0; x < (ssize_t) height; x++)
845             {
846               ssize_t
847                 i;
848 
849               for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
850               {
851                 PixelChannel channel = GetPixelChannelChannel(image,i);
852                 PixelTrait traits = GetPixelChannelTraits(image,channel);
853                 PixelTrait rotate_traits = GetPixelChannelTraits(rotate_image,
854                   channel);
855                 if ((traits == UndefinedPixelTrait) ||
856                     (rotate_traits == UndefinedPixelTrait))
857                   continue;
858                 SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
859               }
860               tile_pixels-=width*GetPixelChannels(image);
861               q+=GetPixelChannels(rotate_image);
862             }
863             sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
864             if (sync == MagickFalse)
865               status=MagickFalse;
866           }
867         }
868         if (image->progress_monitor != (MagickProgressMonitor) NULL)
869           {
870             MagickBooleanType
871               proceed;
872 
873             proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
874               image->rows);
875             if (proceed == MagickFalse)
876               status=MagickFalse;
877           }
878       }
879       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
880         image->rows-1,image->rows);
881       Swap(page.width,page.height);
882       Swap(page.x,page.y);
883       if (page.width != 0)
884         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
885       break;
886     }
887     case 2:
888     {
889       ssize_t
890         y;
891 
892       /*
893         Rotate 180 degrees.
894       */
895 #if defined(MAGICKCORE_OPENMP_SUPPORT)
896       #pragma omp parallel for schedule(static) shared(status) \
897         magick_number_threads(image,rotate_image,image->rows,1)
898 #endif
899       for (y=0; y < (ssize_t) image->rows; y++)
900       {
901         MagickBooleanType
902           sync;
903 
904         const Quantum
905           *magick_restrict p;
906 
907         Quantum
908           *magick_restrict q;
909 
910         ssize_t
911           x;
912 
913         if (status == MagickFalse)
914           continue;
915         p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
916         q=QueueCacheViewAuthenticPixels(rotate_view,0,(ssize_t) (image->rows-y-
917           1),image->columns,1,exception);
918         if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
919           {
920             status=MagickFalse;
921             continue;
922           }
923         q+=GetPixelChannels(rotate_image)*image->columns;
924         for (x=0; x < (ssize_t) image->columns; x++)
925         {
926           ssize_t
927             i;
928 
929           q-=GetPixelChannels(rotate_image);
930           for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
931           {
932             PixelChannel channel = GetPixelChannelChannel(image,i);
933             PixelTrait traits = GetPixelChannelTraits(image,channel);
934             PixelTrait rotate_traits = GetPixelChannelTraits(rotate_image,
935               channel);
936             if ((traits == UndefinedPixelTrait) ||
937                 (rotate_traits == UndefinedPixelTrait))
938               continue;
939             SetPixelChannel(rotate_image,channel,p[i],q);
940           }
941           p+=GetPixelChannels(image);
942         }
943         sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
944         if (sync == MagickFalse)
945           status=MagickFalse;
946         if (image->progress_monitor != (MagickProgressMonitor) NULL)
947           {
948             MagickBooleanType
949               proceed;
950 
951             proceed=SetImageProgress(image,RotateImageTag,progress++,
952               image->rows);
953             if (proceed == MagickFalse)
954               status=MagickFalse;
955           }
956       }
957       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
958         image->rows-1,image->rows);
959       if (page.width != 0)
960         page.x=(ssize_t) (page.width-rotate_image->columns-page.x);
961       if (page.height != 0)
962         page.y=(ssize_t) (page.height-rotate_image->rows-page.y);
963       break;
964     }
965     case 3:
966     {
967       size_t
968         tile_height,
969         tile_width;
970 
971       ssize_t
972         tile_y;
973 
974       /*
975         Rotate 270 degrees.
976       */
977       GetPixelCacheTileSize(image,&tile_width,&tile_height);
978       tile_width=image->columns;
979 #if defined(MAGICKCORE_OPENMP_SUPPORT)
980       #pragma omp parallel for schedule(static) shared(status) \
981         magick_number_threads(image,rotate_image,image->rows/tile_height,1)
982 #endif
983       for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height)
984       {
985         ssize_t
986           tile_x;
987 
988         if (status == MagickFalse)
989           continue;
990         tile_x=0;
991         for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width)
992         {
993           MagickBooleanType
994             sync;
995 
996           const Quantum
997             *magick_restrict p;
998 
999           Quantum
1000             *magick_restrict q;
1001 
1002           ssize_t
1003             y;
1004 
1005           size_t
1006             height,
1007             width;
1008 
1009           width=tile_width;
1010           if ((tile_width+tile_x) > image->columns)
1011             width=(size_t) (tile_width-(tile_x+tile_width-image->columns));
1012           height=tile_height;
1013           if ((tile_height+tile_y) > image->rows)
1014             height=(size_t) (tile_height-(tile_y+tile_height-image->rows));
1015           p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height,
1016             exception);
1017           if (p == (const Quantum *) NULL)
1018             {
1019               status=MagickFalse;
1020               break;
1021             }
1022           for (y=0; y < (ssize_t) width; y++)
1023           {
1024             const Quantum
1025               *magick_restrict tile_pixels;
1026 
1027             ssize_t
1028               x;
1029 
1030             if (status == MagickFalse)
1031               continue;
1032             q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+
1033               rotate_image->rows-(tile_x+width)),height,1,exception);
1034             if (q == (Quantum *) NULL)
1035               {
1036                 status=MagickFalse;
1037                 continue;
1038               }
1039             tile_pixels=p+((width-1)-y)*GetPixelChannels(image);
1040             for (x=0; x < (ssize_t) height; x++)
1041             {
1042               ssize_t
1043                 i;
1044 
1045               for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1046               {
1047                 PixelChannel channel = GetPixelChannelChannel(image,i);
1048                 PixelTrait traits = GetPixelChannelTraits(image,channel);
1049                 PixelTrait rotate_traits = GetPixelChannelTraits(rotate_image,
1050                   channel);
1051                 if ((traits == UndefinedPixelTrait) ||
1052                     (rotate_traits == UndefinedPixelTrait))
1053                   continue;
1054                 SetPixelChannel(rotate_image,channel,tile_pixels[i],q);
1055               }
1056               tile_pixels+=width*GetPixelChannels(image);
1057               q+=GetPixelChannels(rotate_image);
1058             }
1059 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1060             #pragma omp critical (MagickCore_IntegralRotateImage)
1061 #endif
1062             sync=SyncCacheViewAuthenticPixels(rotate_view,exception);
1063             if (sync == MagickFalse)
1064               status=MagickFalse;
1065           }
1066         }
1067         if (image->progress_monitor != (MagickProgressMonitor) NULL)
1068           {
1069             MagickBooleanType
1070               proceed;
1071 
1072             proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height,
1073               image->rows);
1074             if (proceed == MagickFalse)
1075               status=MagickFalse;
1076           }
1077       }
1078       (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType)
1079         image->rows-1,image->rows);
1080       Swap(page.width,page.height);
1081       Swap(page.x,page.y);
1082       if (page.height != 0)
1083         page.y=(ssize_t) (page.height-rotate_image->rows-page.y);
1084       break;
1085     }
1086     default:
1087       break;
1088   }
1089   rotate_view=DestroyCacheView(rotate_view);
1090   image_view=DestroyCacheView(image_view);
1091   rotate_image->type=image->type;
1092   rotate_image->page=page;
1093   if (status == MagickFalse)
1094     rotate_image=DestroyImage(rotate_image);
1095   return(rotate_image);
1096 }
1097 
1098 /*
1099 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1100 %                                                                             %
1101 %                                                                             %
1102 %                                                                             %
1103 +   X S h e a r I m a g e                                                     %
1104 %                                                                             %
1105 %                                                                             %
1106 %                                                                             %
1107 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1108 %
1109 %  XShearImage() shears the image in the X direction with a shear angle of
1110 %  'degrees'.  Positive angles shear counter-clockwise (right-hand rule), and
1111 %  negative angles shear clockwise.  Angles are measured relative to a vertical
1112 %  Y-axis.  X shears will widen an image creating 'empty' triangles on the left
1113 %  and right sides of the source image.
1114 %
1115 %  The format of the XShearImage method is:
1116 %
1117 %      MagickBooleanType XShearImage(Image *image,const double degrees,
1118 %        const size_t width,const size_t height,
1119 %        const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
1120 %
1121 %  A description of each parameter follows.
1122 %
1123 %    o image: the image.
1124 %
1125 %    o degrees: A double representing the shearing angle along the X
1126 %      axis.
1127 %
1128 %    o width, height, x_offset, y_offset: Defines a region of the image
1129 %      to shear.
1130 %
1131 %    o exception: return any errors or warnings in this structure.
1132 %
1133 */
XShearImage(Image * image,const double degrees,const size_t width,const size_t height,const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo * exception)1134 static MagickBooleanType XShearImage(Image *image,const double degrees,
1135   const size_t width,const size_t height,const ssize_t x_offset,
1136   const ssize_t y_offset,ExceptionInfo *exception)
1137 {
1138 #define XShearImageTag  "XShear/Image"
1139 
1140   typedef enum
1141   {
1142     LEFT,
1143     RIGHT
1144   } ShearDirection;
1145 
1146   CacheView
1147     *image_view;
1148 
1149   MagickBooleanType
1150     status;
1151 
1152   MagickOffsetType
1153     progress;
1154 
1155   PixelInfo
1156     background;
1157 
1158   ssize_t
1159     y;
1160 
1161   /*
1162     X shear image.
1163   */
1164   assert(image != (Image *) NULL);
1165   assert(image->signature == MagickCoreSignature);
1166   if (image->debug != MagickFalse)
1167     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1168   status=MagickTrue;
1169   background=image->background_color;
1170   progress=0;
1171   image_view=AcquireAuthenticCacheView(image,exception);
1172 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1173   #pragma omp parallel for schedule(static) shared(progress,status) \
1174     magick_number_threads(image,image,height,1)
1175 #endif
1176   for (y=0; y < (ssize_t) height; y++)
1177   {
1178     PixelInfo
1179       pixel,
1180       source,
1181       destination;
1182 
1183     double
1184       area,
1185       displacement;
1186 
1187     Quantum
1188       *magick_restrict p,
1189       *magick_restrict q;
1190 
1191     ssize_t
1192       i;
1193 
1194     ShearDirection
1195       direction;
1196 
1197     ssize_t
1198       step;
1199 
1200     if (status == MagickFalse)
1201       continue;
1202     p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1,
1203       exception);
1204     if (p == (Quantum *) NULL)
1205       {
1206         status=MagickFalse;
1207         continue;
1208       }
1209     p+=x_offset*GetPixelChannels(image);
1210     displacement=degrees*(double) (y-height/2.0);
1211     if (displacement == 0.0)
1212       continue;
1213     if (displacement > 0.0)
1214       direction=RIGHT;
1215     else
1216       {
1217         displacement*=(-1.0);
1218         direction=LEFT;
1219       }
1220     step=CastDoubleToLong(floor((double) displacement));
1221     area=(double) (displacement-step);
1222     step++;
1223     pixel=background;
1224     GetPixelInfo(image,&source);
1225     GetPixelInfo(image,&destination);
1226     switch (direction)
1227     {
1228       case LEFT:
1229       {
1230         /*
1231           Transfer pixels left-to-right.
1232         */
1233         if (step > x_offset)
1234           break;
1235         q=p-step*GetPixelChannels(image);
1236         for (i=0; i < (ssize_t) width; i++)
1237         {
1238           if ((x_offset+i) < step)
1239             {
1240               p+=GetPixelChannels(image);
1241               GetPixelInfoPixel(image,p,&pixel);
1242               q+=GetPixelChannels(image);
1243               continue;
1244             }
1245           GetPixelInfoPixel(image,p,&source);
1246           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1247             &source,(double) GetPixelAlpha(image,p),area,&destination);
1248           SetPixelViaPixelInfo(image,&destination,q);
1249           GetPixelInfoPixel(image,p,&pixel);
1250           p+=GetPixelChannels(image);
1251           q+=GetPixelChannels(image);
1252         }
1253         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1254           &background,(double) background.alpha,area,&destination);
1255         SetPixelViaPixelInfo(image,&destination,q);
1256         q+=GetPixelChannels(image);
1257         for (i=0; i < (step-1); i++)
1258         {
1259           SetPixelViaPixelInfo(image,&background,q);
1260           q+=GetPixelChannels(image);
1261         }
1262         break;
1263       }
1264       case RIGHT:
1265       {
1266         /*
1267           Transfer pixels right-to-left.
1268         */
1269         p+=width*GetPixelChannels(image);
1270         q=p+step*GetPixelChannels(image);
1271         for (i=0; i < (ssize_t) width; i++)
1272         {
1273           p-=GetPixelChannels(image);
1274           q-=GetPixelChannels(image);
1275           if ((size_t) (x_offset+width+step-i) > image->columns)
1276             continue;
1277           GetPixelInfoPixel(image,p,&source);
1278           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1279             &source,(double) GetPixelAlpha(image,p),area,&destination);
1280           SetPixelViaPixelInfo(image,&destination,q);
1281           GetPixelInfoPixel(image,p,&pixel);
1282         }
1283         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1284           &background,(double) background.alpha,area,&destination);
1285         q-=GetPixelChannels(image);
1286         SetPixelViaPixelInfo(image,&destination,q);
1287         for (i=0; i < (step-1); i++)
1288         {
1289           q-=GetPixelChannels(image);
1290           SetPixelViaPixelInfo(image,&background,q);
1291         }
1292         break;
1293       }
1294     }
1295     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1296       status=MagickFalse;
1297     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1298       {
1299         MagickBooleanType
1300           proceed;
1301 
1302 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1303         #pragma omp atomic
1304 #endif
1305         progress++;
1306         proceed=SetImageProgress(image,XShearImageTag,progress,height);
1307         if (proceed == MagickFalse)
1308           status=MagickFalse;
1309       }
1310   }
1311   image_view=DestroyCacheView(image_view);
1312   return(status);
1313 }
1314 
1315 /*
1316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1317 %                                                                             %
1318 %                                                                             %
1319 %                                                                             %
1320 +   Y S h e a r I m a g e                                                     %
1321 %                                                                             %
1322 %                                                                             %
1323 %                                                                             %
1324 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1325 %
1326 %  YShearImage shears the image in the Y direction with a shear angle of
1327 %  'degrees'.  Positive angles shear counter-clockwise (right-hand rule), and
1328 %  negative angles shear clockwise.  Angles are measured relative to a
1329 %  horizontal X-axis.  Y shears will increase the height of an image creating
1330 %  'empty' triangles on the top and bottom of the source image.
1331 %
1332 %  The format of the YShearImage method is:
1333 %
1334 %      MagickBooleanType YShearImage(Image *image,const double degrees,
1335 %        const size_t width,const size_t height,
1336 %        const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception)
1337 %
1338 %  A description of each parameter follows.
1339 %
1340 %    o image: the image.
1341 %
1342 %    o degrees: A double representing the shearing angle along the Y
1343 %      axis.
1344 %
1345 %    o width, height, x_offset, y_offset: Defines a region of the image
1346 %      to shear.
1347 %
1348 %    o exception: return any errors or warnings in this structure.
1349 %
1350 */
YShearImage(Image * image,const double degrees,const size_t width,const size_t height,const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo * exception)1351 static MagickBooleanType YShearImage(Image *image,const double degrees,
1352   const size_t width,const size_t height,const ssize_t x_offset,
1353   const ssize_t y_offset,ExceptionInfo *exception)
1354 {
1355 #define YShearImageTag  "YShear/Image"
1356 
1357   typedef enum
1358   {
1359     UP,
1360     DOWN
1361   } ShearDirection;
1362 
1363   CacheView
1364     *image_view;
1365 
1366   MagickBooleanType
1367     status;
1368 
1369   MagickOffsetType
1370     progress;
1371 
1372   PixelInfo
1373     background;
1374 
1375   ssize_t
1376     x;
1377 
1378   /*
1379     Y Shear image.
1380   */
1381   assert(image != (Image *) NULL);
1382   assert(image->signature == MagickCoreSignature);
1383   if (image->debug != MagickFalse)
1384     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1385   status=MagickTrue;
1386   progress=0;
1387   background=image->background_color;
1388   image_view=AcquireAuthenticCacheView(image,exception);
1389 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1390   #pragma omp parallel for schedule(static) shared(progress,status) \
1391     magick_number_threads(image,image,width,1)
1392 #endif
1393   for (x=0; x < (ssize_t) width; x++)
1394   {
1395     double
1396       area,
1397       displacement;
1398 
1399     PixelInfo
1400       pixel,
1401       source,
1402       destination;
1403 
1404     Quantum
1405       *magick_restrict p,
1406       *magick_restrict q;
1407 
1408     ssize_t
1409       i;
1410 
1411     ShearDirection
1412       direction;
1413 
1414     ssize_t
1415       step;
1416 
1417     if (status == MagickFalse)
1418       continue;
1419     p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows,
1420       exception);
1421     if (p == (Quantum *) NULL)
1422       {
1423         status=MagickFalse;
1424         continue;
1425       }
1426     p+=y_offset*GetPixelChannels(image);
1427     displacement=degrees*(double) (x-width/2.0);
1428     if (displacement == 0.0)
1429       continue;
1430     if (displacement > 0.0)
1431       direction=DOWN;
1432     else
1433       {
1434         displacement*=(-1.0);
1435         direction=UP;
1436       }
1437     step=CastDoubleToLong(floor((double) displacement));
1438     area=(double) (displacement-step);
1439     step++;
1440     pixel=background;
1441     GetPixelInfo(image,&source);
1442     GetPixelInfo(image,&destination);
1443     switch (direction)
1444     {
1445       case UP:
1446       {
1447         /*
1448           Transfer pixels top-to-bottom.
1449         */
1450         if (step > y_offset)
1451           break;
1452         q=p-step*GetPixelChannels(image);
1453         for (i=0; i < (ssize_t) height; i++)
1454         {
1455           if ((y_offset+i) < step)
1456             {
1457               p+=GetPixelChannels(image);
1458               GetPixelInfoPixel(image,p,&pixel);
1459               q+=GetPixelChannels(image);
1460               continue;
1461             }
1462           GetPixelInfoPixel(image,p,&source);
1463           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1464             &source,(double) GetPixelAlpha(image,p),area,
1465             &destination);
1466           SetPixelViaPixelInfo(image,&destination,q);
1467           GetPixelInfoPixel(image,p,&pixel);
1468           p+=GetPixelChannels(image);
1469           q+=GetPixelChannels(image);
1470         }
1471         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1472           &background,(double) background.alpha,area,&destination);
1473         SetPixelViaPixelInfo(image,&destination,q);
1474         q+=GetPixelChannels(image);
1475         for (i=0; i < (step-1); i++)
1476         {
1477           SetPixelViaPixelInfo(image,&background,q);
1478           q+=GetPixelChannels(image);
1479         }
1480         break;
1481       }
1482       case DOWN:
1483       {
1484         /*
1485           Transfer pixels bottom-to-top.
1486         */
1487         p+=height*GetPixelChannels(image);
1488         q=p+step*GetPixelChannels(image);
1489         for (i=0; i < (ssize_t) height; i++)
1490         {
1491           p-=GetPixelChannels(image);
1492           q-=GetPixelChannels(image);
1493           if ((size_t) (y_offset+height+step-i) > image->rows)
1494             continue;
1495           GetPixelInfoPixel(image,p,&source);
1496           CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1497             &source,(double) GetPixelAlpha(image,p),area,
1498             &destination);
1499           SetPixelViaPixelInfo(image,&destination,q);
1500           GetPixelInfoPixel(image,p,&pixel);
1501         }
1502         CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha,
1503           &background,(double) background.alpha,area,&destination);
1504         q-=GetPixelChannels(image);
1505         SetPixelViaPixelInfo(image,&destination,q);
1506         for (i=0; i < (step-1); i++)
1507         {
1508           q-=GetPixelChannels(image);
1509           SetPixelViaPixelInfo(image,&background,q);
1510         }
1511         break;
1512       }
1513     }
1514     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1515       status=MagickFalse;
1516     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1517       {
1518         MagickBooleanType
1519           proceed;
1520 
1521 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1522         #pragma omp atomic
1523 #endif
1524         progress++;
1525         proceed=SetImageProgress(image,YShearImageTag,progress,image->rows);
1526         if (proceed == MagickFalse)
1527           status=MagickFalse;
1528       }
1529   }
1530   image_view=DestroyCacheView(image_view);
1531   return(status);
1532 }
1533 
1534 /*
1535 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1536 %                                                                             %
1537 %                                                                             %
1538 %                                                                             %
1539 %   S h e a r I m a g e                                                       %
1540 %                                                                             %
1541 %                                                                             %
1542 %                                                                             %
1543 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1544 %
1545 %  ShearImage() creates a new image that is a shear_image copy of an existing
1546 %  one.  Shearing slides one edge of an image along the X or Y axis, creating
1547 %  a parallelogram.  An X direction shear slides an edge along the X axis,
1548 %  while a Y direction shear slides an edge along the Y axis.  The amount of
1549 %  the shear is controlled by a shear angle.  For X direction shears, x_shear
1550 %  is measured relative to the Y axis, and similarly, for Y direction shears
1551 %  y_shear is measured relative to the X axis.  Empty triangles left over from
1552 %  shearing the image are filled with the background color defined by member
1553 %  'background_color' of the image..  ShearImage() allocates the memory
1554 %  necessary for the new Image structure and returns a pointer to the new image.
1555 %
1556 %  ShearImage() is based on the paper "A Fast Algorithm for General Raster
1557 %  Rotatation" by Alan W. Paeth.
1558 %
1559 %  The format of the ShearImage method is:
1560 %
1561 %      Image *ShearImage(const Image *image,const double x_shear,
1562 %        const double y_shear,ExceptionInfo *exception)
1563 %
1564 %  A description of each parameter follows.
1565 %
1566 %    o image: the image.
1567 %
1568 %    o x_shear, y_shear: Specifies the number of degrees to shear the image.
1569 %
1570 %    o exception: return any errors or warnings in this structure.
1571 %
1572 */
ShearImage(const Image * image,const double x_shear,const double y_shear,ExceptionInfo * exception)1573 MagickExport Image *ShearImage(const Image *image,const double x_shear,
1574   const double y_shear,ExceptionInfo *exception)
1575 {
1576   Image
1577     *integral_image,
1578     *shear_image;
1579 
1580   MagickBooleanType
1581     status;
1582 
1583   PointInfo
1584     shear;
1585 
1586   RectangleInfo
1587     border_info,
1588     bounds;
1589 
1590   assert(image != (Image *) NULL);
1591   assert(image->signature == MagickCoreSignature);
1592   if (image->debug != MagickFalse)
1593     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1594   assert(exception != (ExceptionInfo *) NULL);
1595   assert(exception->signature == MagickCoreSignature);
1596   if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0))
1597     ThrowImageException(ImageError,"AngleIsDiscontinuous");
1598   if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0))
1599     ThrowImageException(ImageError,"AngleIsDiscontinuous");
1600   /*
1601     Initialize shear angle.
1602   */
1603   integral_image=CloneImage(image,0,0,MagickTrue,exception);
1604   if (integral_image == (Image *) NULL)
1605     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1606   shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0))));
1607   shear.y=tan(DegreesToRadians(fmod(y_shear,360.0)));
1608   if ((shear.x == 0.0) && (shear.y == 0.0))
1609     return(integral_image);
1610   if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
1611     {
1612       integral_image=DestroyImage(integral_image);
1613       return(integral_image);
1614     }
1615   if (integral_image->alpha_trait == UndefinedPixelTrait)
1616     (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
1617   /*
1618     Compute image size.
1619   */
1620   bounds.width=image->columns+CastDoubleToLong(floor(fabs(shear.x)*
1621     image->rows+0.5));
1622   bounds.x=CastDoubleToLong(ceil((double) image->columns+((fabs(shear.x)*
1623     image->rows)-image->columns)/2.0-0.5));
1624   bounds.y=CastDoubleToLong(ceil((double) image->rows+((fabs(shear.y)*
1625     bounds.width)-image->rows)/2.0-0.5));
1626   /*
1627     Surround image with border.
1628   */
1629   integral_image->border_color=integral_image->background_color;
1630   integral_image->compose=CopyCompositeOp;
1631   border_info.width=(size_t) bounds.x;
1632   border_info.height=(size_t) bounds.y;
1633   shear_image=BorderImage(integral_image,&border_info,image->compose,exception);
1634   integral_image=DestroyImage(integral_image);
1635   if (shear_image == (Image *) NULL)
1636     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1637   /*
1638     Shear the image.
1639   */
1640   if (shear_image->alpha_trait == UndefinedPixelTrait)
1641     (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception);
1642   status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x,
1643     (ssize_t) (shear_image->rows-image->rows)/2,exception);
1644   if (status == MagickFalse)
1645     {
1646       shear_image=DestroyImage(shear_image);
1647       return((Image *) NULL);
1648     }
1649   status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t)
1650     (shear_image->columns-bounds.width)/2,bounds.y,exception);
1651   if (status == MagickFalse)
1652     {
1653       shear_image=DestroyImage(shear_image);
1654       return((Image *) NULL);
1655     }
1656   status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType)
1657     image->columns,(MagickRealType) image->rows,MagickFalse,exception);
1658   shear_image->alpha_trait=image->alpha_trait;
1659   shear_image->compose=image->compose;
1660   shear_image->page.width=0;
1661   shear_image->page.height=0;
1662   if (status == MagickFalse)
1663     shear_image=DestroyImage(shear_image);
1664   return(shear_image);
1665 }
1666 
1667 /*
1668 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1669 %                                                                             %
1670 %                                                                             %
1671 %                                                                             %
1672 %   S h e a r R o t a t e I m a g e                                           %
1673 %                                                                             %
1674 %                                                                             %
1675 %                                                                             %
1676 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1677 %
1678 %  ShearRotateImage() creates a new image that is a rotated copy of an existing
1679 %  one.  Positive angles rotate counter-clockwise (right-hand rule), while
1680 %  negative angles rotate clockwise.  Rotated images are usually larger than
1681 %  the originals and have 'empty' triangular corners.  X axis.  Empty
1682 %  triangles left over from shearing the image are filled with the background
1683 %  color defined by member 'background_color' of the image.  ShearRotateImage
1684 %  allocates the memory necessary for the new Image structure and returns a
1685 %  pointer to the new image.
1686 %
1687 %  ShearRotateImage() is based on the paper "A Fast Algorithm for General
1688 %  Raster Rotatation" by Alan W. Paeth.  ShearRotateImage is adapted from a
1689 %  similar method based on the Paeth paper written by Michael Halle of the
1690 %  Spatial Imaging Group, MIT Media Lab.
1691 %
1692 %  The format of the ShearRotateImage method is:
1693 %
1694 %      Image *ShearRotateImage(const Image *image,const double degrees,
1695 %        ExceptionInfo *exception)
1696 %
1697 %  A description of each parameter follows.
1698 %
1699 %    o image: the image.
1700 %
1701 %    o degrees: Specifies the number of degrees to rotate the image.
1702 %
1703 %    o exception: return any errors or warnings in this structure.
1704 %
1705 */
ShearRotateImage(const Image * image,const double degrees,ExceptionInfo * exception)1706 MagickExport Image *ShearRotateImage(const Image *image,const double degrees,
1707   ExceptionInfo *exception)
1708 {
1709   Image
1710     *integral_image,
1711     *rotate_image;
1712 
1713   MagickBooleanType
1714     status;
1715 
1716   MagickRealType
1717     angle;
1718 
1719   PointInfo
1720     shear;
1721 
1722   RectangleInfo
1723     border_info,
1724     bounds;
1725 
1726   size_t
1727     height,
1728     rotations,
1729     shear_width,
1730     width;
1731 
1732   /*
1733     Adjust rotation angle.
1734   */
1735   assert(image != (Image *) NULL);
1736   assert(image->signature == MagickCoreSignature);
1737   if (image->debug != MagickFalse)
1738     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1739   assert(exception != (ExceptionInfo *) NULL);
1740   assert(exception->signature == MagickCoreSignature);
1741   angle=fmod(degrees,360.0);
1742   if (angle < -45.0)
1743     angle+=360.0;
1744   for (rotations=0; angle > 45.0; rotations++)
1745     angle-=90.0;
1746   rotations%=4;
1747   /*
1748     Calculate shear equations.
1749   */
1750   integral_image=IntegralRotateImage(image,rotations,exception);
1751   if (integral_image == (Image *) NULL)
1752     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1753   shear.x=(-tan((double) DegreesToRadians(angle)/2.0));
1754   shear.y=sin((double) DegreesToRadians(angle));
1755   if ((shear.x == 0.0) && (shear.y == 0.0))
1756     return(integral_image);
1757   if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse)
1758     {
1759       integral_image=DestroyImage(integral_image);
1760       return(integral_image);
1761     }
1762   if (integral_image->alpha_trait == UndefinedPixelTrait)
1763     (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception);
1764   /*
1765     Compute maximum bounds for 3 shear operations.
1766   */
1767   width=integral_image->columns;
1768   height=integral_image->rows;
1769   bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5);
1770   bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5);
1771   shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+
1772     bounds.width+0.5);
1773   bounds.x=CastDoubleToLong(floor((double) ((shear_width > bounds.width) ?
1774     width : bounds.width-shear_width+2)/2.0+0.5));
1775   bounds.y=CastDoubleToLong(floor(((double) bounds.height-height+2)/2.0+0.5));
1776   /*
1777     Surround image with a border.
1778   */
1779   integral_image->border_color=integral_image->background_color;
1780   integral_image->compose=CopyCompositeOp;
1781   border_info.width=(size_t) bounds.x;
1782   border_info.height=(size_t) bounds.y;
1783   rotate_image=BorderImage(integral_image,&border_info,image->compose,
1784     exception);
1785   integral_image=DestroyImage(integral_image);
1786   if (rotate_image == (Image *) NULL)
1787     ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
1788   /*
1789     Rotate the image.
1790   */
1791   status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t)
1792     (rotate_image->rows-height)/2,exception);
1793   if (status == MagickFalse)
1794     {
1795       rotate_image=DestroyImage(rotate_image);
1796       return((Image *) NULL);
1797     }
1798   status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t)
1799     (rotate_image->columns-bounds.width)/2,bounds.y,exception);
1800   if (status == MagickFalse)
1801     {
1802       rotate_image=DestroyImage(rotate_image);
1803       return((Image *) NULL);
1804     }
1805   status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t)
1806     (rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows-
1807     bounds.height)/2,exception);
1808   if (status == MagickFalse)
1809     {
1810       rotate_image=DestroyImage(rotate_image);
1811       return((Image *) NULL);
1812     }
1813   status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width,
1814     (MagickRealType) height,MagickTrue,exception);
1815   rotate_image->alpha_trait=image->alpha_trait;
1816   rotate_image->compose=image->compose;
1817   rotate_image->page.width=0;
1818   rotate_image->page.height=0;
1819   if (status == MagickFalse)
1820     rotate_image=DestroyImage(rotate_image);
1821   return(rotate_image);
1822 }
1823