ImageResizer  3.4.0
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events
Public Member Functions | Protected Member Functions | Protected Attributes | Properties | List of all members
ImageResizer.ImageBuilder Class Reference

Provides methods for generating resized images, and for reading and writing them to disk. Use ImageBuilder.Current to get the current instance (as configured in the application configuration), or use ImageBuilder.Current.Create() to control which extensions are used. More...

Inheritance diagram for ImageResizer.ImageBuilder:
Inheritance graph
[legend]
Collaboration diagram for ImageResizer.ImageBuilder:
Collaboration graph
[legend]

Public Member Functions

 ImageBuilder (IEnumerable< BuilderExtension > extensions, IEncoderProvider encoderProvider, IVirtualImageProvider virtualFileProvider, ISettingsModifier settingsModifier)
 Create a new instance of ImageBuilder using the specified extensions, encoder provider, file provider, and settings filter. Extension methods will be fired in the order they exist in the collection. More...
 
virtual ImageBuilder Create (IEnumerable< BuilderExtension > extensions, IEncoderProvider writer, IVirtualImageProvider virtualFileProvider, ISettingsModifier settingsModifier)
 Creates another instance of the class using the specified extensions. Subclasses should override this and point to their own constructor. More...
 
virtual ImageBuilder Copy ()
 Copies the instance along with extensions. Subclasses must override this. More...
 
virtual Bitmap LoadImage (object source, ResizeSettings settings)
 Loads a Bitmap from the specified source. If a filename is available, it will be attached to bitmap.Tag in a BitmapTag instance. The Bitmap.Tag.Path value may be a virtual, relative, UNC, windows, or unix path. Does not dispose 'source' if it is a Stream or Image instance - that's the responsibility of the calling code. More...
 
virtual IDictionary< string,
object > 
LoadImageInfo (object source, IEnumerable< string > requestedInfo)
 Returns a dictionary of information about the given image. More...
 
virtual Bitmap LoadImage (object source, ResizeSettings settings, bool restoreStreamPos)
 Loads a Bitmap from the specified source. If a filename is available, it will be attached to bitmap.Tag in a BitmapTag instance. The Bitmap.Tag.Path value may be a virtual, relative, UNC, windows, or unix path. Does not dispose 'source' if it is a Stream or Image instance - that's the responsibility of the calling code. More...
 
override Bitmap DecodeStream (Stream s, ResizeSettings settings, string optionalPath)
 Decodes the stream into a System.Drawing.Bitmap instance. As of 3.0.7, now ensures the stream can safely be closed after the method returns. May copy the stream. The copied stream will be in b.Tag.Source. Does not close or dispose any streams. More...
 
Stream GetStreamFromSource (object source, ResizeSettings settings, ref bool disposeStream, out string path, out bool restoreStreamPosition)
 For plugin use only. Returns a stream instance from the specified source object and settings object. To exend this method, override GetStream. More...
 
virtual Bitmap Build (object source, ResizeSettings settings)
 Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior. More...
 
virtual Bitmap Build (object source, ResizeSettings settings, bool disposeSource)
 Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. More...
 
virtual void Build (object source, object dest, ResizeSettings settings)
 Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior. More...
 
virtual ImageJob Build (object source, object dest, Instructions instructions)
 Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior. More...
 
virtual void Build (object source, object dest, ResizeSettings settings, bool disposeSource)
 Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will not be disposed unless disposeSource=true. More...
 
virtual string Build (object source, object dest, ResizeSettings settings, bool disposeSource, bool addFileExtension)
 Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will not be disposed unless disposeSource=true. If passed a path destination, the physical path of the written file will be returned. More...
 
virtual ImageJob Build (ImageJob job)
 The most flexible method for processing an image More...
 
virtual void Process (ImageState s)
 Processes an ImageState instance. Used by Build, GetFinalSize, and TranslatePoint. Can be overriden by a plugin with the OnProcess method More...
 
virtual PointF[] TranslatePoints (PointF[] sourcePoints, Size originalSize, ResizeSettings q)
 Doesn't support flipping. Translate a point on the original bitmap to a point on the new bitmap. If the original point no longer exists, returns Empty More...
 
virtual Size GetFinalSize (Size originalSize, ResizeSettings q)
 Gets the final size of an image More...
 
virtual Size GetFinalSize (Size originalSize, Instructions q)
 Gets the final size of an image More...
 
virtual IEnumerable< string > GetSupportedFileExtensions ()
 Returns a list of the file extensions ImageBuilder can load by default. Plugins can implement IFileExtensionPlugin to add new ones. More...
 
virtual IEnumerable< string > GetSupportedQuerystringKeys ()
 Returns a list of the querystring commands ImageBuilder can parse by default. Plugins can implement IQuerystringPlugin to add new ones. More...
 
- Public Member Functions inherited from ImageResizer.Resizing.AbstractImageProcessor
 AbstractImageProcessor ()
 Creates a new AbstractImageProcessor with no extensions More...
 
 AbstractImageProcessor (IEnumerable< BuilderExtension > extensions)
 Creates a new AbstractImageProcessor which will run the specified extensions with each method call. More...
 
virtual Bitmap DecodeStreamFailed (Stream s, ResizeSettings settings, string optionalPath)
 Extensions are executed until one extension returns a non-null value. This is taken to mean that the error has been resolved. Extensions should not throw an exception unless they wish to cause subsequent extensions to not execute. If extensions throw an ArgumentException or ExternalException, it will be wrapped in an ImageCorruptedException instance. If the Bitmap class is used for decoding, read gdi-bugs.txt and make sure you set b.Tag to new BitmapTag(optionalPath,stream); More...
 

Protected Member Functions

 ImageBuilder ()
 Shouldn't be used except to make a factory instance. More...
 
override RequestedAction BuildJob (ImageJob job)
 
override RequestedAction buildToStream (Bitmap source, Stream dest, ResizeSettings settings)
 Override this when you need to override the behavior of image encoding and/or Bitmap processing Not for external use. Does NOT dispose of 'source' or 'source's underlying stream. More...
 
override Bitmap buildToBitmap (Bitmap source, ResizeSettings settings, bool transparencySupported)
 Override this when you need to override the behavior of Bitmap processing. Not for external use. Does NOT dispose of 'source' or 'source's underlying stream. More...
 
override RequestedAction Layout (ImageState s)
 Process.3: Handles the layout phase of Processing More...
 
override RequestedAction Render (ImageState s)
 Handles the rendering phase of processing More...
 
override RequestedAction PrepareSourceBitmap (ImageState s)
 Process.1 Switches the bitmap to the correct frame or page, and applies source flipping commands More...
 
override RequestedAction LayoutPadding (ImageState s)
 Process.3(Layout).4: Ring "padding" is added to the layout More...
 
override RequestedAction LayoutMargin (ImageState s)
 Process.3(Layout).10: Margins are added to the layout More...
 
override RequestedAction LayoutBorder (ImageState s)
 Process.3(Layout).6: Ring "border" is added to the layout More...
 
override RequestedAction LayoutRound (ImageState s)
 Process.3(Layout).anytime: Occurs when the layout point values are rounded to integers. May be called anytime during Layout() More...
 
override RequestedAction LayoutRotate (ImageState s)
 Process.3(Layout).anytime: Occurs when the layout is rotated. May be called anytime during Layout() More...
 
override RequestedAction LayoutNormalize (ImageState s)
 Process.3(Layout).anytime: Occurs when the layout is normalized to 0,0. May be called anytime during Layout() More...
 
override RequestedAction EndLayout (ImageState s)
 Process.3(Layout).12: Occurs once layout has finished. No more changes should occur to points or rings in the layout after this method. destSize is calculated here. More...
 
override RequestedAction PrepareDestinationBitmap (ImageState s)
 Creates a bitmap of s.destSize dimensions, intializes a graphics object for it, and configures all the default settings. More...
 
override RequestedAction RenderBackground (ImageState s)
 Sets the background color if needed or requested More...
 
override RequestedAction RenderPadding (ImageState s)
 Process.5(Render).5 Image padding is drawn More...
 
override RequestedAction CreateImageAttribues (ImageState s)
 Process.5(Render).7: An ImageAttributes instance is created if it doesn't already exist. More...
 
override RequestedAction RenderImage (ImageState s)
 Process.5(Render).10: The image is copied to the destination parallelogram specified by ring 'image'. More...
 
override RequestedAction RenderBorder (ImageState s)
 Process.5(Render).12: The border is rendered More...
 
override RequestedAction FlushChanges (ImageState s)
 Process.5(Render).17: Changes are flushed to the bitmap here and the graphics object is destroyed. More...
 
override RequestedAction ProcessFinalBitmap (ImageState s)
 Process.6: Non-rendering changes to the bitmap object occur here, such as flipping. The graphics object is unavailable. More...
 
override RequestedAction LayoutImage (ImageState s)
 Populates copyRect, as well as Rings image and imageArea. Translates and scales any existing rings as if they existed on the original bitmap. More...
 
- Protected Member Functions inherited from ImageResizer.Resizing.AbstractImageProcessor
virtual void PreLoadImage (ref object source, ref string path, ref bool disposeSource, ref ResizeSettings settings)
 Extend this to allow additional types of source objects to be accepted by transforming them into Bitmap instances. More...
 
virtual Stream GetStream (object source, ResizeSettings settings, ref bool disposeStream, out string path, out bool restoreStreamPosition)
 Extend this to allow additional types of source objects to be accepted by transforming them into Stream instances. First plugin to return a Stream wins. More...
 
virtual RequestedAction PostDecodeStream (ref Bitmap img, ResizeSettings settings)
 Extend this to modify the Bitmap instance after it has been decoded by DecodeStream or DecodeStreamFailed More...
 
virtual void PreAcquireStream (ref object dest, ResizeSettings settings)
 Extend this to allow additional types of destination objects to be accepted by transforming them into a stream. More...
 
virtual RequestedAction BuildJob (ImageResizer.ImageJob job)
 The method to override if you want to replace the entire pipeline. All Build() calls call this method first. Does nothing in ImageBuilder More...
 
virtual RequestedAction OnProcess (ImageState s)
 Process.0 First step of the Process() method. Can replace the entire Process method if RequestAction.Cancel is returned. Can be used to add points to translate (for image maps), and also to modify the settings More...
 
virtual RequestedAction PostPrepareSourceBitmap (ImageState s)
 Process.2 Extend this to apply any pre-processing to the source bitmap that needs to occur before Layout begins More...
 
virtual RequestedAction FlipExistingPoints (ImageState s)
 Process.3(Layout).1: This is where the points in the layout are flipped the same way the source bitmap was flipped (unless their flags specify otherwise) More...
 
virtual RequestedAction PostLayoutImage (ImageState s)
 Process.3(Layout).3: Add rings here to insert them between the image area and the padding More...
 
virtual RequestedAction PostLayoutPadding (ImageState s)
 Process.3(Layout).5: Add rings here to insert them between the padding and the border More...
 
virtual RequestedAction PostLayoutBorder (ImageState s)
 Process.3(Layout).7: Add rings here to insert them between the border and the effect rings More...
 
virtual RequestedAction LayoutEffects (ImageState s)
 Process.3(Layout).8: Effects such as 'shadow' are added here. More...
 
virtual RequestedAction PostLayoutEffects (ImageState s)
 Process.3(Layout).9: Add rings here to insert them between the effects and the margin More...
 
virtual RequestedAction PostLayoutMargin (ImageState s)
 Process.3(Layout).11: Add rings here to insert them around the margin. Rings will be outermost More...
 
virtual RequestedAction PostLayoutRotate (ImageState s)
 Process.3(Layout).anytime: Occurs after the layout is rotated. May be called anytime during Layout() More...
 
virtual RequestedAction PostLayoutNormalize (ImageState s)
 Process.3(Layout).anytime: Occurs after the layout is normalized. May be called anytime during Layout() More...
 
virtual RequestedAction PostLayoutRound (ImageState s)
 Process.3(Layout).anytime: Occurs after the layout point values are rounded to integers. May be called anytime during Layout() More...
 
virtual RequestedAction PostRenderBackground (ImageState s)
 Process.5(Render).2 After the background color is rendered More...
 
virtual RequestedAction RenderEffects (ImageState s)
 Process.5(Render).3 Effects (such as a drop shadow or outer glow) are rendered More...
 
virtual RequestedAction PostRenderEffects (ImageState s)
 Process.5(Render).4 After outer effects are rendered More...
 
virtual RequestedAction PostRenderPadding (ImageState s)
 Process.5(Render).6 After image padding is drawn More...
 
virtual RequestedAction PostCreateImageAttributes (ImageState s)
 Process.5(Render).8: The ImageAttributes instance exists and can be modified or replaced. More...
 
virtual RequestedAction PreRenderImage (ImageState s)
 Process.5(Render).9: Plugins have a chance to pre-process the source image before it gets rendered, and save it to s.preRenderBitmap More...
 
virtual RequestedAction PostRenderImage (ImageState s)
 Process.5(Render).11: After the image is drawn More...
 
virtual RequestedAction PostRenderBorder (ImageState s)
 Process.5(Render).13: After the border is drawn More...
 
virtual RequestedAction PreRenderOverlays (ImageState s)
 Process.5(Render).14: Any last-minute changes before watermarking or overlays are applied More...
 
virtual RequestedAction RenderOverlays (ImageState s)
 Process.5(Render).15: Watermarks can be rendered here. All image processing should be done More...
 
virtual RequestedAction PreFlushChanges (ImageState s)
 Process.5(Render).16: Called before changes are flushed and the graphics object is destroyed. More...
 
virtual RequestedAction PostFlushChanges (ImageState s)
 Process.5(Render).18: Changes have been flushed to the bitmap, but the final bitmap has not been flipped yet. More...
 
virtual RequestedAction EndProcess (ImageState s)
 Process.7: Layout and rendering are both complete. More...
 

Protected Attributes

IEncoderProvider _encoderProvider = null
 
ISettingsModifier _settingsModifier = null
 
- Protected Attributes inherited from ImageResizer.Resizing.AbstractImageProcessor
volatile IEnumerable
< BuilderExtension
exts
 Contains the set of extensions that are called for every method. More...
 

Properties

IEncoderProvider EncoderProvider [get]
 Handles the encoder selection and provision proccess. More...
 
ISettingsModifier SettingsModifier [get]
 May be null. A class to modify or normalize ResizeSettings instances before they are used. More...
 
IVirtualImageProvider VirtualFileProvider [get]
 Provides a resolution service for app-relative URLs. More...
 
static ImageBuilder Current [get]
 Returns a shared instance of ImageBuilder or a subclass, equivalent to Config.Current.CurrentImageBuilder More...
 

Detailed Description

Provides methods for generating resized images, and for reading and writing them to disk. Use ImageBuilder.Current to get the current instance (as configured in the application configuration), or use ImageBuilder.Current.Create() to control which extensions are used.

Definition at line 27 of file ImageBuilder.cs.

Constructor & Destructor Documentation

ImageResizer.ImageBuilder.ImageBuilder ( )
inlineprotected

Shouldn't be used except to make a factory instance.

Definition at line 32 of file ImageBuilder.cs.

Referenced by ImageResizer.ImageBuilder.Copy(), and ImageResizer.ImageBuilder.Create().

32 { }
ImageResizer.ImageBuilder.ImageBuilder ( IEnumerable< BuilderExtension extensions,
IEncoderProvider  encoderProvider,
IVirtualImageProvider  virtualFileProvider,
ISettingsModifier  settingsModifier 
)
inline

Create a new instance of ImageBuilder using the specified extensions, encoder provider, file provider, and settings filter. Extension methods will be fired in the order they exist in the collection.

Parameters
extensions
encoderProvider
settingsModifier
virtualFileProvider

Definition at line 68 of file ImageBuilder.cs.

69  : base(extensions) {
70  this._encoderProvider = encoderProvider;
71  this._virtualFileProvider = virtualFileProvider;
72  this._settingsModifier = settingsModifier;
73  }

Member Function Documentation

virtual Bitmap ImageResizer.ImageBuilder.Build ( object  source,
ResizeSettings  settings 
)
inlinevirtual

Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.

Parameters
sourceMay be an instance of string (a physical path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream.
settingsResizing and processing command to apply to the.

Definition at line 319 of file ImageBuilder.cs.

Referenced by ImageResizer.ImageBuilder.LoadImageInfo().

319  {
320  return Build(source, settings, true);
321  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
virtual Bitmap ImageResizer.ImageBuilder.Build ( object  source,
ResizeSettings  settings,
bool  disposeSource 
)
inlinevirtual

Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg.

If passed a source Stream, Bitmap, or Image instance, it will not be disposed unless disposeSource=true.

Parameters
sourceMay be an instance of string (a physical path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream.
settingsResizing and processing command to apply to the.
disposeSourceIf false, 'source' will not be disposed.

Definition at line 334 of file ImageBuilder.cs.

334  {
335  ImageJob j = new ImageJob(source, typeof(Bitmap), settings, disposeSource, false);
336  Build(j);
337  return j.Result as Bitmap;
338  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
virtual void ImageResizer.ImageBuilder.Build ( object  source,
object  dest,
ResizeSettings  settings 
)
inlinevirtual

Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.

Parameters
sourceMay be an instance of string (a physical path or app-relative virtual path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. App-relative virtual paths will use the VirtualPathProvider system
destMay be a physical path (string), or a Stream instance. Does not have to be seekable.
settingsResizing and processing command to apply to the image.

Definition at line 347 of file ImageBuilder.cs.

347  {
348  Build(source, dest, settings, true);
349  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
virtual ImageJob ImageResizer.ImageBuilder.Build ( object  source,
object  dest,
Instructions  instructions 
)
inlinevirtual

Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.

Parameters
sourceMay be an instance of string (a physical path or app-relative virtual path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. App-relative virtual paths will use the VirtualPathProvider system
destMay be a physical path (string), or a Stream instance. Does not have to be seekable.
instructionsResizing and processing command to apply to the image.

Definition at line 358 of file ImageBuilder.cs.

359  {
360  var j = new ImageJob(source, dest, instructions, true, false);
361  Build(j);
362  return j;
363  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
virtual void ImageResizer.ImageBuilder.Build ( object  source,
object  dest,
ResizeSettings  settings,
bool  disposeSource 
)
inlinevirtual

Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will not be disposed unless disposeSource=true.

Parameters
sourceMay be an instance of string (a physical path or app-relative virtual path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. App-relative virtual paths will use the VirtualPathProvider system
destMay be a physical path (string), or a Stream instance. Does not have to be seekable.
settingsResizing and processing command to apply to the image.
disposeSourceTrue to dispose 'source' after use. False to leave intact.

Definition at line 373 of file ImageBuilder.cs.

373  {
374  Build(source, dest, settings, disposeSource, false);
375  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
virtual string ImageResizer.ImageBuilder.Build ( object  source,
object  dest,
ResizeSettings  settings,
bool  disposeSource,
bool  addFileExtension 
)
inlinevirtual

Resizes and processes the specified source image and stores the encoded result in the specified destination. If passed a source Stream, Bitmap, or Image instance, it will not be disposed unless disposeSource=true. If passed a path destination, the physical path of the written file will be returned.

Parameters
sourceMay be an instance of string (a physical path or app-relative virtual path), VirtualFile, IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. App-relative virtual paths will use the VirtualPathProvider system
destMay be a physical path (string), or a Stream instance. Does not have to be seekable.
settingsResizing and processing command to apply to the image.
disposeSourceTrue to dispose 'source' after use. False to leave intact.
addFileExtensionIf true, will add the correct file extension to 'dest' if it is a string.

Definition at line 390 of file ImageBuilder.cs.

390  {
391  return Build(new ImageJob(source, dest, settings, disposeSource, addFileExtension)).FinalPath;
392  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
virtual ImageJob ImageResizer.ImageBuilder.Build ( ImageJob  job)
inlinevirtual

The most flexible method for processing an image

Parameters
job
Returns

Definition at line 400 of file ImageBuilder.cs.

400  {
401  if (job == null) throw new ArgumentNullException("job", "ImageJob parameter null. Cannot Build a null ImageJob instance");
402 
403  //Clone and filter settings FIRST, before calling plugins.
404  ResizeSettings s = job.Settings == null ? new ResizeSettings() : new ResizeSettings(job.Settings);
405  if (SettingsModifier != null) s = SettingsModifier.Modify(s);
406  job.Settings = s;
407 
408  try {
409  //Allow everything else to be overriden
410  if (BuildJob(job) != RequestedAction.Cancel) throw new ImageProcessingException("Nobody did the job");
411  return job;
412  } finally {
413  //Follow the dispose requests
414  if (job.DisposeSourceObject && job.Source is IDisposable && job.Source != null) ((IDisposable)job.Source).Dispose();
415  if (job.DisposeDestinationStream && job.Dest is IDisposable && job.Dest != null) ((IDisposable)job.Dest).Dispose();
416  }
417  }
ISettingsModifier SettingsModifier
May be null. A class to modify or normalize ResizeSettings instances before they are used...
Definition: ImageBuilder.cs:44
override RequestedAction BuildJob(ImageJob job)
override RequestedAction ImageResizer.ImageBuilder.BuildJob ( ImageJob  job)
inlineprotected

They only want information/attributes

Definition at line 421 of file ImageBuilder.cs.

421  {
422  if (base.BuildJob(job) == RequestedAction.Cancel) return RequestedAction.Cancel;
423 
424  Bitmap b = null;
425  try {
426  ResizeSettings s = job.Settings;
427 
428  //Load image
429  b = LoadImage(job.Source, s, job.ResetSourceStream);
430 
431  //Save source path info
432  job.SourcePathData = (b != null && b.Tag != null && b.Tag is BitmapTag) ? ((BitmapTag)b.Tag).Path : null;
433 
434  job.ResultInfo["source.width"] = b.Width;
435  job.ResultInfo["source.height"] = b.Height;
436 
437  //Calucalte the appropriate file extension and mime type
438  if (job.Dest != typeof(Bitmap)){
439  IEncoder e = this.EncoderProvider.GetEncoder(s, b);
440  if (e != null)
441  {
442  job.ResultInfo["result.ext"] = e.Extension;
443  job.ResultInfo["result.mime"] = e.MimeType;
444  }
445  }
446 
447  if (job.Dest == typeof(IDictionary<string, object>))
448  {
449  ///They only want information/attributes
450  job.Result = job.ResultInfo;
451  return RequestedAction.Cancel;
452  }
453 
454  //Fire PreAcquireStream(ref dest, settings) to modify 'dest'
455  object dest = job.Dest;
456  this.PreAcquireStream(ref dest, s);
457  job.Dest = dest;
458 
459  if (dest == typeof(Bitmap)) {
460  job.Result = buildToBitmap(b, s, true);
461 
462  //Write to Physical file
463  } else if (dest is string) {
464  //Make physical and resolve variable references all at the same time.
465  job.FinalPath = job.ResolveTemplatedPath(dest as string,
466  delegate(string var) {
467  if ("ext".Equals(var, StringComparison.OrdinalIgnoreCase)) {
468  return job.ResultFileExtension;
469  }
470  if ("width".Equals(var, StringComparison.OrdinalIgnoreCase))
471  return GetFinalSize(new System.Drawing.Size(b.Width, b.Height), new ResizeSettings(job.Settings)).Width.ToString(NumberFormatInfo.InvariantInfo);
472  if ("height".Equals(var, StringComparison.OrdinalIgnoreCase))
473  return GetFinalSize(new System.Drawing.Size(b.Width, b.Height), new ResizeSettings(job.Settings)).Height.ToString(NumberFormatInfo.InvariantInfo);
474  return null;
475  });
476  //If requested, auto-create the parent directory(ies)
477  if (job.CreateParentDirectory) {
478  string dirName = Path.GetDirectoryName(job.FinalPath);
479  if (!Directory.Exists(dirName)) Directory.CreateDirectory(dirName);
480  }
481  System.IO.FileStream fs = new FileStream(job.FinalPath, FileMode.Create, FileAccess.Write);
482  using (fs) {
483  buildToStream(b, fs, s);
484  fs.Flush();//TODO: Switch to .Flush(true) with .NET 4
485  }
486  //Write to Unknown stream
487  } else if (dest is Stream) {
488  buildToStream(b, (Stream)dest, s);
489  } else throw new ArgumentException("Destination may be a string or Stream.", "Dest");
490 
491  } finally {
492  //Get the source bitmap's underlying stream (may differ from 'source')
493  Stream underlyingStream = null;
494  if (b != null && b.Tag != null && b.Tag is BitmapTag) underlyingStream = ((BitmapTag)b.Tag).Source;
495 
496  //Close the source bitamp's underlying stream unless it is the same stream (EDIT: or bitmap) we were passed.
497  var closeUnderlyingStream = (b != job.Source && underlyingStream != job.Source && underlyingStream != null);
498 
499  //Dispose the bitmap unless we were passed it. We check for 'null' in case an ImageCorruptedException occured.
500  if (b != null && b != job.Source) b.Dispose();
501 
502  //Dispose the underlying stream after disposing the bitmap
503  if (closeUnderlyingStream) underlyingStream.Dispose();
504  }
505 
506  return RequestedAction.Cancel;
507  }
RequestedAction
What to do about remaining handlers/methods for the specified section
virtual Size GetFinalSize(Size originalSize, ResizeSettings q)
Gets the final size of an image
override Bitmap buildToBitmap(Bitmap source, ResizeSettings settings, bool transparencySupported)
Override this when you need to override the behavior of Bitmap processing. Not for external use...
virtual Bitmap LoadImage(object source, ResizeSettings settings)
Loads a Bitmap from the specified source. If a filename is available, it will be attached to bitmap...
override RequestedAction buildToStream(Bitmap source, Stream dest, ResizeSettings settings)
Override this when you need to override the behavior of image encoding and/or Bitmap processing Not f...
An image encoder. Exposes methods for suitability checking, encoding, transparency compatibility chec...
Definition: IEncoder.cs:13
override Bitmap ImageResizer.ImageBuilder.buildToBitmap ( Bitmap  source,
ResizeSettings  settings,
bool  transparencySupported 
)
inlineprotectedvirtual

Override this when you need to override the behavior of Bitmap processing. Not for external use. Does NOT dispose of 'source' or 'source's underlying stream.

Parameters
source
settings
transparencySupportedTrue if the output method will support transparency. If false, the image should be provided a matte color
Returns

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 536 of file ImageBuilder.cs.

536  {
537  Bitmap b = base.buildToBitmap(source,settings,transparencySupported);
538  if (b != null) return b; //Allow extensions to replace the method wholesale.
539 
540  using (ImageState state = new ImageState(settings, source.Size, transparencySupported)) {
541  state.sourceBitmap = source;
542 
543  //Generic processing of ImageState instances.
544  Process(state);
545 
546  //Save a reference to return
547  b = state.destBitmap;
548  state.destBitmap = null; //So it doesn't get disposed yet
549 
550  //Don't dispose the source bitmap either, just the graphics object.
551  state.sourceBitmap = null;
552  }
553  return b;
554  }
Encapsulates the state of an image being resized. Can be used to simulate a resize as well as actuall...
Definition: ImageState.cs:15
virtual void Process(ImageState s)
Processes an ImageState instance. Used by Build, GetFinalSize, and TranslatePoint. Can be overriden by a plugin with the OnProcess method
override RequestedAction ImageResizer.ImageBuilder.buildToStream ( Bitmap  source,
Stream  dest,
ResizeSettings  settings 
)
inlineprotectedvirtual

Override this when you need to override the behavior of image encoding and/or Bitmap processing Not for external use. Does NOT dispose of 'source' or 'source's underlying stream.

Parameters
source
dest
settings

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 516 of file ImageBuilder.cs.

516  {
517  if (base.buildToStream(source, dest, settings) == RequestedAction.Cancel) return RequestedAction.None;
518 
519  IEncoder e = this.EncoderProvider.GetEncoder(settings,source);
520  if (e == null) throw new ImageProcessingException("No image encoder was found for this request.");
521  using (Bitmap b = buildToBitmap(source, settings,e.SupportsTransparency)) {//Determines output format, includes code for saving in a variety of formats.
522  //Save to stream
523  e.Write(b, dest);
524  }
525  return RequestedAction.None;
526  }
RequestedAction
What to do about remaining handlers/methods for the specified section
override Bitmap buildToBitmap(Bitmap source, ResizeSettings settings, bool transparencySupported)
Override this when you need to override the behavior of Bitmap processing. Not for external use...
An image encoder. Exposes methods for suitability checking, encoding, transparency compatibility chec...
Definition: IEncoder.cs:13
virtual ImageBuilder ImageResizer.ImageBuilder.Copy ( )
inlinevirtual

Copies the instance along with extensions. Subclasses must override this.

Returns

Definition at line 90 of file ImageBuilder.cs.

90  {
91  return new ImageBuilder(this.exts,this._encoderProvider, this._virtualFileProvider,this._settingsModifier);
92  }
ImageBuilder()
Shouldn&#39;t be used except to make a factory instance.
Definition: ImageBuilder.cs:32
volatile IEnumerable< BuilderExtension > exts
Contains the set of extensions that are called for every method.
virtual ImageBuilder ImageResizer.ImageBuilder.Create ( IEnumerable< BuilderExtension extensions,
IEncoderProvider  writer,
IVirtualImageProvider  virtualFileProvider,
ISettingsModifier  settingsModifier 
)
inlinevirtual

Creates another instance of the class using the specified extensions. Subclasses should override this and point to their own constructor.

Parameters
extensions
writer
virtualFileProvider
settingsModifier
Returns

Definition at line 83 of file ImageBuilder.cs.

83  {
84  return new ImageBuilder(extensions,writer,virtualFileProvider,settingsModifier);
85  }
ImageBuilder()
Shouldn&#39;t be used except to make a factory instance.
Definition: ImageBuilder.cs:32
override RequestedAction ImageResizer.ImageBuilder.CreateImageAttribues ( ImageState  s)
inlineprotectedvirtual

Process.5(Render).7: An ImageAttributes instance is created if it doesn't already exist.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 829 of file ImageBuilder.cs.

829  {
830  if (base.CreateImageAttribues(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
831  if (s.copyAttibutes == null) s.copyAttibutes = new ImageAttributes();
832  return RequestedAction.None;
833  }
RequestedAction
What to do about remaining handlers/methods for the specified section
ImageAttributes copyAttibutes
Allows color correction/modification during the image copy.
Definition: ImageState.cs:186
override Bitmap ImageResizer.ImageBuilder.DecodeStream ( Stream  s,
ResizeSettings  settings,
string  optionalPath 
)
inlinevirtual

Decodes the stream into a System.Drawing.Bitmap instance. As of 3.0.7, now ensures the stream can safely be closed after the method returns. May copy the stream. The copied stream will be in b.Tag.Source. Does not close or dispose any streams.

Parameters
s
settings
optionalPath
Returns

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 210 of file ImageBuilder.cs.

210  {
211  Bitmap b = base.DecodeStream(s, settings, optionalPath);
212  if (b != null && b.Tag == null) b.Tag = new BitmapTag(optionalPath); //Assume Bitmap wasn't used.
213  if (b != null) return b;
214 
215  bool useICM = true;
216  if (settings != null && "true".Equals(settings["ignoreicc"], StringComparison.OrdinalIgnoreCase)) useICM = false;
217 
218  //NDJ - May 24, 2011 - Copying stream into memory so the original can be closed safely.
219  MemoryStream ms = StreamExtensions.CopyToMemoryStream(s);
220  b = new Bitmap(ms, useICM);
221  b.Tag = new BitmapTag(optionalPath, ms); //May 25, 2011: Storing a ref to the MemorySteam so it won't accidentally be garbage collected.
222  return b;
223  }
override RequestedAction ImageResizer.ImageBuilder.EndLayout ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).12: Occurs once layout has finished. No more changes should occur to points or rings in the layout after this method. destSize is calculated here.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 735 of file ImageBuilder.cs.

736  {
737  if (base.EndLayout(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
738 
739  //Calculates a bounding box around all the rings in the layout, then rounds that size. Creates a 1x1 pixel destSize value at minimum.
741  s.destSize = new Size((int)Math.Max(1, s.destSize.Width), (int)Math.Max(1, s.destSize.Height));
742  return RequestedAction.None;
743  }
RequestedAction
What to do about remaining handlers/methods for the specified section
static PointF[] RoundPoints(PointF[] a)
Rounds the elements of the specified array [not used]
Definition: PolygonMath.cs:20
Size destSize
The size of the target bitmap image. Set after all sizing operations have completed.
Definition: ImageState.cs:47
RectangleF GetBoundingBox()
Gets a bounding box that encloses all rings that don&#39;t have ExcludeFromBoundingBox set...
Defines a collection of utility functions for manipulating polygons. These functions may be (re)moved...
Definition: PolygonMath.cs:13
LayoutBuilder layout
The layout object. Used for calculated and flowing the layout of the various rings around the image (...
Definition: ImageState.cs:42
override RequestedAction ImageResizer.ImageBuilder.FlushChanges ( ImageState  s)
inlineprotectedvirtual

Process.5(Render).17: Changes are flushed to the bitmap here and the graphics object is destroyed.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 895 of file ImageBuilder.cs.

895  {
896  if (base.FlushChanges(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
897 
898  if (s.destGraphics == null) return RequestedAction.None;
899  //Commit changes.
900  s.destGraphics.Flush(FlushIntention.Flush);
901  s.destGraphics.Dispose();
902  s.destGraphics = null;
903  return RequestedAction.None;
904  }
RequestedAction
What to do about remaining handlers/methods for the specified section
Graphics destGraphics
A graphics object to write to the destination bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:182
virtual Size ImageResizer.ImageBuilder.GetFinalSize ( Size  originalSize,
ResizeSettings  q 
)
inlinevirtual

Gets the final size of an image

Returns

Definition at line 947 of file ImageBuilder.cs.

948  {
949  return GetFinalSize(originalSize, new Instructions(q));
950  }
virtual Size GetFinalSize(Size originalSize, ResizeSettings q)
Gets the final size of an image
virtual Size ImageResizer.ImageBuilder.GetFinalSize ( Size  originalSize,
Instructions  q 
)
inlinevirtual

Gets the final size of an image

Returns

Definition at line 956 of file ImageBuilder.cs.

957  {
958  ImageState s = new ImageState(new ResizeSettings(q), originalSize, true);
959  Process(s);
960  return s.finalSize;
961  }
Encapsulates the state of an image being resized. Can be used to simulate a resize as well as actuall...
Definition: ImageState.cs:15
virtual void Process(ImageState s)
Processes an ImageState instance. Used by Build, GetFinalSize, and TranslatePoint. Can be overriden by a plugin with the OnProcess method
Stream ImageResizer.ImageBuilder.GetStreamFromSource ( object  source,
ResizeSettings  settings,
ref bool  disposeStream,
out string  path,
out bool  restoreStreamPosition 
)
inline

For plugin use only. Returns a stream instance from the specified source object and settings object. To exend this method, override GetStream.

Parameters
sourceThe physical or app-relative path, or a VirtualFile, IVirtualFile, Stream, HttpPostedFile, or HttpPostedFileBase instance.
settingsQuerystring settings to pass to the VirtualFileProvider
disposeStreamYou should externally initialize this to true, unless the user-provided 'source' is a Stream instance. Will be set to false for HttpPostedFile and HttpPostedFileBase instances, so they can be reused.
pathThe physical or virtual path associated with the stream (if present). Otherwise null
restoreStreamPositionTrue if you should save and restore the seek position of the stream. True for HttpPostedFile and HttpPostedFileBase instances.
Returns

Definition at line 235 of file ImageBuilder.cs.

Referenced by ImageResizer.ImageBuilder.LoadImage().

235  {
236  if (source == null) throw new ArgumentNullException("source", "The source argument cannot be null; how do you load an image from a null value?");
237  if (settings == null) settings = new ResizeSettings();
238 
239  //Allow plugins to extend this
240  bool disposeS = disposeStream;
241  Stream s = base.GetStream(source, settings, ref disposeS, out path, out restoreStreamPosition);
242  if (s != null) {
243  disposeStream = disposeS;
244  return s;
245  }
246 
247  //App-relative path - converted to virtual path
248  if (source is string) {
249  path = source as string;
250  //Convert app-relative paths to VirtualFile instances
251  if (path.StartsWith("~", StringComparison.OrdinalIgnoreCase)) {
252  source = this.VirtualFileProvider.GetFile(PathUtils.ResolveAppRelative(path), settings);
253  if (source == null) throw new FileNotFoundException("The specified virtual file could not be found.", PathUtils.ResolveAppRelative(path));
254  }
255  }
256 
257  path = null;
258  restoreStreamPosition = false;
259  //Stream
260  if (source is Stream) {
261  s = (Stream)source;
262  }
263  //VirtualFile
264  else if (source is System.Web.Hosting.VirtualFile) {
265  path = ((System.Web.Hosting.VirtualFile)source).VirtualPath;
266  s = ((System.Web.Hosting.VirtualFile)source).Open();
267  //IVirtualFile
268  } else if (source is IVirtualFile) {
269  path = ((IVirtualFile)source).VirtualPath;
270  s = ((IVirtualFile)source).Open();
271  //PhysicalPath
272  } else if (source is string) {
273  path = (string)source;
274  s = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
275  } else if (source is byte[]) {
276  s = new MemoryStream((byte[])source, 0, ((byte[])source).Length, false, true);
277  } else {
278  //For HttpPostedFile and HttpPostedFileBase - we must use reflection to support .NET 3.5 without losing 2.0 compat.
279  PropertyInfo pname = source.GetType().GetProperty("FileName", typeof(string));
280  PropertyInfo pstream = source.GetType().GetProperty("InputStream");
281 
282  if (pname != null && pstream != null) {
283  path = pname.GetValue(source, null) as string;
284  s = pstream.GetValue(source, null) as Stream;
285  disposeStream = false; //We never want to dispose the HttpPostedFile or HttpPostedFileBase streams..
286  restoreStreamPosition = true;
287  }
288 
289  if (s == null) return null;
290  }
291 
292 
293  try {
294 
295  if (s != null && s.Length <= s.Position && s.Position > 0)
296  throw new ImageProcessingException("The source stream is at the end (have you already read it?). You must call stream.Seek(0, SeekOrigin.Begin); before re-using a stream, or use ImageJob with ResetSourceStream=true the first time the stream is read.");
297 
298  if (s != null && s.Length == 0)
299  throw new ImageProcessingException("Source stream is empty; it has a length of 0. No bytes, no data. We can't work with this.");
300 
301  } catch (NotSupportedException) {
302  }
303 
304  return s;
305  }
A virtual file to support IVirtualImageProvider
Definition: IVirtualFile.cs:10
A set of utility methods for manipulating virtual paths
Definition: PathUtils.cs:17
static string ResolveAppRelative(string virtualPath)
Resolves app-relative paths to virtual paths. Does nothing with virtual or relative paths...
Definition: PathUtils.cs:150
virtual IEnumerable<string> ImageResizer.ImageBuilder.GetSupportedFileExtensions ( )
inlinevirtual

Returns a list of the file extensions ImageBuilder can load by default. Plugins can implement IFileExtensionPlugin to add new ones.

Returns

Implements ImageResizer.Plugins.IFileExtensionPlugin.

Definition at line 1137 of file ImageBuilder.cs.

1137  {
1138  return _supportedFileExtensions;
1139  }
virtual IEnumerable<string> ImageResizer.ImageBuilder.GetSupportedQuerystringKeys ( )
inlinevirtual

Returns a list of the querystring commands ImageBuilder can parse by default. Plugins can implement IQuerystringPlugin to add new ones.

Returns

Implements ImageResizer.Plugins.IQuerystringPlugin.

Definition at line 1154 of file ImageBuilder.cs.

1154  {
1155  return _supportedQuerystringKeys;
1156  }
override RequestedAction ImageResizer.ImageBuilder.Layout ( ImageState  s)
inlineprotectedvirtual

Process.3: Handles the layout phase of Processing

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 575 of file ImageBuilder.cs.

575  {
576  if (base.Layout(s) == RequestedAction.Cancel) return RequestedAction.Cancel;
577  FlipExistingPoints(s); //Not implemented
578  LayoutImage(s);
579  PostLayoutImage(s);
580  LayoutPadding(s);
582  LayoutBorder(s);
583  PostLayoutBorder(s);
584  LayoutEffects(s);
586  LayoutMargin(s);
587  PostLayoutMargin(s);
588  LayoutRotate(s);
589  PostLayoutRotate(s);
590  LayoutNormalize(s);
592  LayoutRound(s);
593  PostLayoutRound(s);
594  EndLayout(s);
595  return RequestedAction.None;
596  }
RequestedAction
What to do about remaining handlers/methods for the specified section
override RequestedAction LayoutRotate(ImageState s)
Process.3(Layout).anytime: Occurs when the layout is rotated. May be called anytime during Layout() ...
override RequestedAction EndLayout(ImageState s)
Process.3(Layout).12: Occurs once layout has finished. No more changes should occur to points or ring...
override RequestedAction LayoutNormalize(ImageState s)
Process.3(Layout).anytime: Occurs when the layout is normalized to 0,0. May be called anytime during ...
virtual RequestedAction PostLayoutNormalize(ImageState s)
Process.3(Layout).anytime: Occurs after the layout is normalized. May be called anytime during Layout...
virtual RequestedAction PostLayoutRound(ImageState s)
Process.3(Layout).anytime: Occurs after the layout point values are rounded to integers. May be called anytime during Layout()
virtual RequestedAction PostLayoutPadding(ImageState s)
Process.3(Layout).5: Add rings here to insert them between the padding and the border ...
virtual RequestedAction PostLayoutImage(ImageState s)
Process.3(Layout).3: Add rings here to insert them between the image area and the padding ...
override RequestedAction LayoutImage(ImageState s)
Populates copyRect, as well as Rings image and imageArea. Translates and scales any existing rings as...
override RequestedAction LayoutRound(ImageState s)
Process.3(Layout).anytime: Occurs when the layout point values are rounded to integers. May be called anytime during Layout()
virtual RequestedAction PostLayoutEffects(ImageState s)
Process.3(Layout).9: Add rings here to insert them between the effects and the margin ...
virtual RequestedAction PostLayoutBorder(ImageState s)
Process.3(Layout).7: Add rings here to insert them between the border and the effect rings ...
override RequestedAction LayoutMargin(ImageState s)
Process.3(Layout).10: Margins are added to the layout
override RequestedAction LayoutBorder(ImageState s)
Process.3(Layout).6: Ring &quot;border&quot; is added to the layout
virtual RequestedAction PostLayoutRotate(ImageState s)
Process.3(Layout).anytime: Occurs after the layout is rotated. May be called anytime during Layout() ...
override RequestedAction LayoutPadding(ImageState s)
Process.3(Layout).4: Ring &quot;padding&quot; is added to the layout
virtual RequestedAction PostLayoutMargin(ImageState s)
Process.3(Layout).11: Add rings here to insert them around the margin. Rings will be outermost ...
virtual RequestedAction FlipExistingPoints(ImageState s)
Process.3(Layout).1: This is where the points in the layout are flipped the same way the source bitma...
virtual RequestedAction LayoutEffects(ImageState s)
Process.3(Layout).8: Effects such as &#39;shadow&#39; are added here.
override RequestedAction ImageResizer.ImageBuilder.LayoutBorder ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).6: Ring "border" is added to the layout

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 699 of file ImageBuilder.cs.

699  {
700  if (base.LayoutBorder(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
701 
702  //And borders
703  if (!s.settings.Border.IsEmpty) {
704  s.layout.AddRing("border", s.settings.Border);
705  }
706  return RequestedAction.None;
707  }
RequestedAction
What to do about remaining handlers/methods for the specified section
BoxPadding Border
Friendly get/set accessor for the [&quot;borderWidth&quot;] value. Returns BoxPadding.Empty when unspecified...
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
bool IsEmpty
Returns true if th
Definition: BoxPadding.cs:106
override RequestedAction ImageResizer.ImageBuilder.LayoutImage ( ImageState  s)
inlineprotectedvirtual

Populates copyRect, as well as Rings image and imageArea. Translates and scales any existing rings as if they existed on the original bitmap.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 972 of file ImageBuilder.cs.

972  {
973  if (base.LayoutImage(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
974 
975  if (s.copyRect.IsEmpty) {
976  //Use the crop size if present.
977  s.copyRect = new RectangleF(new PointF(0, 0), s.originalSize);
978  if (NameValueCollectionExtensions.GetList<double>(s.settings, "crop", 0, 4) != null) {
979  s.copyRect = PolygonMath.ToRectangle(s.settings.getCustomCropSourceRect(s.originalSize)); //Round the custom crop rectangle coordinates
980  if (s.copyRect.Size.IsEmpty) throw new Exception("You must specify a custom crop rectange if crop=custom");
981  }
982  }
983  //Save the manual crop size.
984  SizeF manualCropSize = s.copySize;
985  RectangleF manualCropRect = s.copyRect;
986 
987  FitMode fit = s.settings.Mode;
988  //Determine fit mode to use if both vertical and horizontal limits are used.
989  if (fit == FitMode.None){
990  if (s.settings.Width != -1 || s.settings.Height != -1){
991 
992  if ("fill".Equals(s.settings["stretch"], StringComparison.OrdinalIgnoreCase)) fit = FitMode.Stretch;
993  else if ("auto".Equals(s.settings["crop"], StringComparison.OrdinalIgnoreCase)) fit = FitMode.Crop;
994  else if (!string.IsNullOrEmpty(s.settings["carve"])
995  && !"false".Equals(s.settings["carve"], StringComparison.OrdinalIgnoreCase)
996  && !"none".Equals(s.settings["carve"], StringComparison.OrdinalIgnoreCase)) fit = FitMode.Carve;
997  else fit = FitMode.Pad;
998  }else{
999  fit = FitMode.Max;
1000  }
1001 
1002  }
1003 
1004 
1005 
1006 
1007  //Aspect ratio of the image
1008  double imageRatio = s.copySize.Width / s.copySize.Height;
1009 
1010  //Zoom factor
1011  double zoom = s.settings.Get<double>("zoom", 1);
1012 
1013  //The target size for the image
1014  SizeF targetSize = new SizeF(-1, -1);
1015  //Target area for the image
1016  SizeF areaSize = new SizeF(-1, -1);
1017  //If any dimensions are specified, calculate. Otherwise, use original image dimensions
1018  if (s.settings.Width != -1 || s.settings.Height != -1 || s.settings.MaxHeight != -1 || s.settings.MaxWidth != -1) {
1019  //A dimension was specified.
1020  //We first calculate the largest size the image can be under the width/height/maxwidth/maxheight restrictions.
1021  //- pretending stretch=fill and scale=both
1022 
1023  //Temp vars - results stored in targetSize and areaSize
1024  double width = s.settings.Width;
1025  double height = s.settings.Height;
1026  double maxwidth = s.settings.MaxWidth;
1027  double maxheight = s.settings.MaxHeight;
1028 
1029  //Eliminate cases where both a value and a max value are specified: use the smaller value for the width/height
1030  if (maxwidth > 0 && width > 0) { width = Math.Min(maxwidth, width); maxwidth = -1; }
1031  if (maxheight > 0 && height > 0) { height = Math.Min(maxheight, height); maxheight = -1; }
1032 
1033  //Handle cases of width/maxheight and height/maxwidth as in legacy versions.
1034  if (width != -1 && maxheight != -1) maxheight = Math.Min(maxheight, (width / imageRatio));
1035  if (height != -1 && maxwidth != -1) maxwidth = Math.Min(maxwidth, (height * imageRatio));
1036 
1037 
1038  //Move max values to width/height. FitMode should already reflect the mode we are using, and we've already resolved mixed modes above.
1039  width = Math.Max(width, maxwidth);
1040  height = Math.Max(height, maxheight);
1041 
1042  //Calculate missing value (a missing value is handled the same everywhere).
1043  if (width > 0 && height <= 0) height = width/ imageRatio;
1044  else if (height > 0 && width <= 0) width = height * imageRatio;
1045 
1046  //We now have width & height, our target size. It will only be a different aspect ratio from the image if both 'width' and 'height' are specified.
1047 
1048  //FitMode.Max
1049  if (fit == FitMode.Max) {
1050  areaSize = targetSize = PolygonMath.ScaleInside(manualCropSize, new SizeF((float)width, (float)height));
1051  //FitMode.Pad
1052  } else if (fit == FitMode.Pad) {
1053  areaSize = new SizeF((float)width, (float)height);
1054  targetSize = PolygonMath.ScaleInside(manualCropSize, areaSize);
1055  //FitMode.crop
1056  } else if (fit == FitMode.Crop) {
1057  //We autocrop - so both target and area match the requested size
1058  areaSize = targetSize = new SizeF((float)width, (float)height);
1059  //Determine the size of the area we are copying
1060  Size sourceSize = PolygonMath.RoundPoints(PolygonMath.ScaleInside(areaSize, manualCropSize));
1061  //Center the portion we are copying within the manualCropSize
1062  s.copyRect = PolygonMath.ToRectangle(PolygonMath.AlignWith(new RectangleF(0, 0, sourceSize.Width, sourceSize.Height), s.copyRect, s.settings.Anchor));
1063 
1064  } else { //Stretch and carve both act like stretching, so do that:
1065  areaSize = targetSize = new SizeF((float)width, (float)height);
1066  }
1067 
1068 
1069  }else{
1070  //No dimensions specified, no fit mode needed. Use manual crop dimensions
1071  areaSize = targetSize = manualCropSize;
1072  }
1073 
1074  //Multiply both areaSize and targetSize by zoom.
1075  areaSize.Width *= (float)zoom;
1076  areaSize.Height *= (float)zoom;
1077  targetSize.Width *= (float)zoom;
1078  targetSize.Height *= (float)zoom;
1079 
1080  //Todo: automatic crop is permitted to break the scaling rules. Fix!!
1081 
1082  //Now do upscale/downscale checks. If they take effect, set targetSize to imageSize
1083  if (s.settings.Scale == ScaleMode.DownscaleOnly) {
1084  if (PolygonMath.FitsInside(manualCropSize, targetSize)) {
1085  //The image is smaller or equal to its target polygon. Use original image coordinates instead.
1086  areaSize = targetSize = manualCropSize;
1087  s.copyRect = manualCropRect;
1088  }
1089  } else if (s.settings.Scale == ScaleMode.UpscaleOnly) {
1090  if (!PolygonMath.FitsInside(manualCropSize, targetSize)) {
1091  //The image is larger than its target. Use original image coordintes instead
1092  areaSize = targetSize = manualCropSize;
1093  s.copyRect = manualCropRect;
1094  }
1095  } else if (s.settings.Scale == ScaleMode.UpscaleCanvas) {
1096  //Same as downscaleonly, except areaSize isn't changed.
1097  if (PolygonMath.FitsInside(manualCropSize, targetSize)) {
1098  //The image is smaller or equal to its target polygon.
1099 
1100  //Use manual copy rect/size instead.
1101 
1102  targetSize = manualCropSize;
1103  s.copyRect = manualCropRect;
1104  }
1105  }
1106 
1107 
1108  //May 12: require max dimension and round values to minimize rounding differences later.
1109  areaSize.Width = Math.Max(1, (float)Math.Round(areaSize.Width));
1110  areaSize.Height = Math.Max(1, (float)Math.Round(areaSize.Height));
1111  targetSize.Width = Math.Max(1, (float)Math.Round(targetSize.Width));
1112  targetSize.Height = Math.Max(1, (float)Math.Round(targetSize.Height));
1113 
1114 
1115  //Translate and scale all existing rings
1116  s.layout.Shift(s.copyRect, new RectangleF(new Point(0, 0), targetSize));
1117 
1118  s.layout.AddRing("image", PolygonMath.ToPoly(new RectangleF(new PointF(0, 0), targetSize)));
1119 
1120  s.layout.AddRing("imageArea",PolygonMath.ToPoly(new RectangleF(new PointF(0, 0), areaSize)));
1121 
1122  //Center imageArea around 'image'
1123  s.layout["imageArea"] = PolygonMath.AlignWith(s.layout["imageArea"], s.layout["image"], s.settings.Anchor);
1124 
1125  return RequestedAction.None;
1126  }
RequestedAction
What to do about remaining handlers/methods for the specified section
int MaxWidth
[&quot;maxwidth&quot;]: Sets the maximum desired width of the image. (minus padding, borders, margins, effects, and rotation). The image may be smaller than this value to maintain aspect ratio when both maxwidth and maxheight are specified.
ScaleMode Scale
[&quot;scale&quot;] Whether to downscale, upscale, upscale the canvas, or both upscale or downscale the image a...
static bool FitsInside(SizeF inner, SizeF outer)
Returns true if &#39;inner&#39; fits inside or equals &#39;outer&#39;
Definition: PolygonMath.cs:420
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
int Width
[&quot;width&quot;]: Sets the desired width of the image. (minus padding, borders, margins, effects, and rotation). The only instance the resulting image will be smaller is if the original source image is smaller. Set Scale=Both to upscale these images and ensure the output always matches &#39;width&#39; and &#39;height&#39;. If both width and height are specified, the image will be &#39;letterboxed&#39; to match the desired aspect ratio. Change the Mode property to adjust this behavior.
Defines a collection of utility functions for manipulating polygons. These functions may be (re)moved...
Definition: PolygonMath.cs:13
Size originalSize
The original size of the source bitmap. Use this instead of accessing the bitmap directly for this in...
Definition: ImageState.cs:30
ScaleMode
Controls whether the image is allowed to upscale, downscale, both, or if only the canvas gets to be u...
Definition: Enumerations.cs:75
int MaxHeight
[&quot;maxheight&quot;]: Sets the maximum desired height of the image. (minus padding, borders, margins, effects, and rotation). The image may be smaller than this value to maintain aspect ratio when both maxwidth and maxheight are specified.
FitMode
How to resolve aspect ratio differences between the requested size and the original image&#39;s size...
RectangleF copyRect
The rectangular portion of the source image to copy
Definition: ImageState.cs:57
int Height
[&quot;height&quot;]: Sets the desired height of the image. (minus padding, borders, margins, effects, and rotation) The only instance the resulting image will be smaller is if the original source image is smaller. Set Scale=Both to upscale these images and ensure the output always matches &#39;width&#39; and &#39;height&#39;. If both width and height are specified, the image will be &#39;letterboxed&#39; to match the desired aspect ratio. Change the Mode property to adjust this behavior.
override RequestedAction ImageResizer.ImageBuilder.LayoutMargin ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).10: Margins are added to the layout

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 689 of file ImageBuilder.cs.

689  {
690  if (base.LayoutMargin(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
691 
692  //We need to add padding
693  if (!s.settings.Margin.IsEmpty) {
694  s.layout.AddRing("margin", s.settings.Margin);
695  }
696  return RequestedAction.None;
697  }
RequestedAction
What to do about remaining handlers/methods for the specified section
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
bool IsEmpty
Returns true if th
Definition: BoxPadding.cs:106
BoxPadding Margin
[&quot;margin&quot;]: Gets/sets the width(s) of the margin outside the image border and effects.
override RequestedAction ImageResizer.ImageBuilder.LayoutNormalize ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).anytime: Occurs when the layout is normalized to 0,0. May be called anytime during Layout()

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 726 of file ImageBuilder.cs.

727  {
728  if (base.LayoutNormalize(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
729  //Normalize all the rings
730  s.layout.Normalize(new PointF(0, 0));
731  return RequestedAction.None;
732  }
RequestedAction
What to do about remaining handlers/methods for the specified section
void Normalize(PointF origin)
Normalizes all rings and invisible polygons so that the outermost ring&#39;s bounding box starts at the s...
LayoutBuilder layout
The layout object. Used for calculated and flowing the layout of the various rings around the image (...
Definition: ImageState.cs:42
override RequestedAction ImageResizer.ImageBuilder.LayoutPadding ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).4: Ring "padding" is added to the layout

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 679 of file ImageBuilder.cs.

679  {
680  if (base.LayoutPadding(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
681 
682  //We need to add padding
683  if (!s.settings.Padding.IsEmpty) {
684  s.layout.AddRing("padding", s.settings.Padding);
685  }
686  return RequestedAction.None;
687  }
RequestedAction
What to do about remaining handlers/methods for the specified section
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
bool IsEmpty
Returns true if th
Definition: BoxPadding.cs:106
BoxPadding Padding
[&quot;paddingWidth&quot;]: Gets/sets the width(s) of padding inside the image border.
override RequestedAction ImageResizer.ImageBuilder.LayoutRotate ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).anytime: Occurs when the layout is rotated. May be called anytime during Layout()

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 719 of file ImageBuilder.cs.

720  {
721  if (base.LayoutRotate(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
722  //Now, rotate all rings.
723  s.layout.Rotate(s.settings.Rotate, new PointF(0, 0));
724  return RequestedAction.None;
725  }
RequestedAction
What to do about remaining handlers/methods for the specified section
double Rotate
[&quot;rotate&quot;] The degress to rotate the image clockwise. -360 to 360.
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
void Rotate(double degrees, PointF origin)
Rotates all existing rings (Except those flagged ignore)
LayoutBuilder layout
The layout object. Used for calculated and flowing the layout of the various rings around the image (...
Definition: ImageState.cs:42
override RequestedAction ImageResizer.ImageBuilder.LayoutRound ( ImageState  s)
inlineprotectedvirtual

Process.3(Layout).anytime: Occurs when the layout point values are rounded to integers. May be called anytime during Layout()

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 711 of file ImageBuilder.cs.

712  {
713  if (base.LayoutRound(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
714  //Todo, round points here.
715  //s.layout.Round();
716  return RequestedAction.None;
717  }
RequestedAction
What to do about remaining handlers/methods for the specified section
virtual Bitmap ImageResizer.ImageBuilder.LoadImage ( object  source,
ResizeSettings  settings 
)
inlinevirtual

Loads a Bitmap from the specified source. If a filename is available, it will be attached to bitmap.Tag in a BitmapTag instance. The Bitmap.Tag.Path value may be a virtual, relative, UNC, windows, or unix path. Does not dispose 'source' if it is a Stream or Image instance - that's the responsibility of the calling code.

Parameters
sourceMay be an instance of string, VirtualFile, IVirtualFile IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. If passed an Image instance, the image will be cloned, which will cause metadata, indexed state, and any additional frames to be lost. Accepts physical paths and application relative paths. (C:... and ~/path)
settingsWill ignore ICC profile if ?ignoreicc=true.
Returns
A Bitmap. The .Tag property will include a BitmapTag instance. If .Tag.Source is not null, remember to dispose it when you dispose the Bitmap.

Definition at line 104 of file ImageBuilder.cs.

104  {
105  return LoadImage(source, settings, false);
106  }
virtual Bitmap LoadImage(object source, ResizeSettings settings)
Loads a Bitmap from the specified source. If a filename is available, it will be attached to bitmap...
virtual Bitmap ImageResizer.ImageBuilder.LoadImage ( object  source,
ResizeSettings  settings,
bool  restoreStreamPos 
)
inlinevirtual

Loads a Bitmap from the specified source. If a filename is available, it will be attached to bitmap.Tag in a BitmapTag instance. The Bitmap.Tag.Path value may be a virtual, relative, UNC, windows, or unix path. Does not dispose 'source' if it is a Stream or Image instance - that's the responsibility of the calling code.

Parameters
sourceMay be an instance of string, VirtualFile, IVirtualFile IVirtualBitmapFile, HttpPostedFile, Bitmap, Image, or Stream. If passed an Image instance, the image will be cloned, which will cause metadata, indexed state, and any additional frames to be lost. Accepts physical paths and application relative paths. (C:... and ~/path)
settingsWill ignore ICC profile if ?ignoreicc=true.
restoreStreamPosIf true, the position of the source stream will be restored after being read
Returns
A Bitmap. The .Tag property will include a BitmapTag instance. If .Tag.Source is not null, remember to dispose it when you dispose the Bitmap.

Definition at line 127 of file ImageBuilder.cs.

127  {
128  if (source == null) throw new ArgumentNullException("source", "The source argument cannot be null; how do you load an image from a null value?");
129 
130  bool disposeStream = !(source is Stream);
131  string path = null;
132 
133  //Fire PreLoadImage(source,settings)
134  this.PreLoadImage(ref source, ref path, ref disposeStream, ref settings);
135 
136  System.Drawing.Bitmap b = null;
137  string loadFailureReasons = "File may be corrupted, empty, or may contain a PNG image with a single dimension greater than 65,535 pixels.";
138 
139  //Bitmap
140  if (source is Bitmap) return source as Bitmap;
141  //Image
142  if (source is System.Drawing.Image)
143  return new Bitmap((System.Drawing.Image)source); //Note, this clones just the raw bitmap data - doesn't copy attributes, bit depth, or anything.
144  //IVirtualBitmapFile
145  if (source is IVirtualBitmapFile) {
146  b = ((IVirtualBitmapFile)source).GetBitmap();
147  if (b.Tag == null) b.Tag = new BitmapTag(((IVirtualBitmapFile)source).VirtualPath);
148  return b;
149  }
150 
151  bool restoreStreamPosition = false;
152  Stream s = GetStreamFromSource(source, settings, ref disposeStream, out path, out restoreStreamPosition);
153  if (s == null) throw new ArgumentException("Source may only be an instance of string, VirtualFile, IVirtualBitmapFile, HttpPostedFile, HttpPostedFileBase, Bitmap, Image, or Stream.", "source");
154 
155  if (restoreStreamPos) restoreStreamPosition = true;
156 
157  //Save the original stream position if it's an HttpPostedFile
158  long originalPosition = (restoreStreamPosition) ? s.Position : - 1;
159 
160  try {
161  try {
162  //First try DecodeStream
163  b = this.DecodeStream(s, settings, path);
164  //Let the fallbacks work. (Only happens when a plugin overrides DecodeStream and retuns null)
165  if (b == null) throw new ImageCorruptedException("Failed to decode image. Plugin made DecodeStream return null.", null);
166  } catch (Exception e) {
167  //if (Debugger.IsAttached) throw e;
168  Debug.Write("Falling back to DecodeStreamFailed: " + e.Message + "\n" + e.StackTrace);
169 
170  if (!s.CanSeek)
171  throw new ImageCorruptedException("Cannot attempt fallback decoding path on a non-seekable stream", e);
172 
173  b = DecodeStreamFailed(s, settings, path);
174  if (b == null) throw; //If none of the extensions loaded the image, throw the exception anyhow.
175  }
176  } catch (ArgumentException ae) {
177  ae.Data.Add("path", path);
178  throw new ImageCorruptedException(loadFailureReasons, ae);
179  } catch (ExternalException ee) {
180  ee.Data.Add("path", path);
181  throw new ImageCorruptedException(loadFailureReasons, ee);
182  } finally {
183  //Now, we can't dispose the stream if Bitmap is still using it.
184  if (b != null && b.Tag != null && b.Tag is BitmapTag && ((BitmapTag)b.Tag).Source == s) {
185  //And, it looks like Bitmap is still using it.
186  s = null;
187  }
188  //Dispose the stream if we opened it. If someone passed it to us, they're responsible.
189  if (s != null && disposeStream) { s.Dispose(); s = null; }
190 
191  //Restore the stream position if we were given an HttpPostedFile instance
192  if (originalPosition > -1 && s != null && s.CanSeek) s.Position = originalPosition;
193 
194  //Make sure the bitmap is tagged with its path. DecodeStream usually handles this, only relevant for extension decoders.
195  if (b != null && b.Tag == null && path != null) b.Tag = new BitmapTag(path);
196 
197  }
198  PostDecodeStream(ref b,settings);
199  return b;
200  }
virtual RequestedAction PostDecodeStream(ref Bitmap img, ResizeSettings settings)
Extend this to modify the Bitmap instance after it has been decoded by DecodeStream or DecodeStreamFa...
Stream GetStreamFromSource(object source, ResizeSettings settings, ref bool disposeStream, out string path, out bool restoreStreamPosition)
For plugin use only. Returns a stream instance from the specified source object and settings object...
For virtual files who want to provide their data in Bitmap form (like a PSD reader or gradient genera...
virtual Bitmap DecodeStreamFailed(Stream s, ResizeSettings settings, string optionalPath)
Extensions are executed until one extension returns a non-null value. This is taken to mean that the ...
virtual IDictionary<string,object> ImageResizer.ImageBuilder.LoadImageInfo ( object  source,
IEnumerable< string >  requestedInfo 
)
inlinevirtual

Returns a dictionary of information about the given image.

Parameters
source
requestedInfoPass null to get the defaults ("source.width", source.height")
Returns

Definition at line 114 of file ImageBuilder.cs.

114  {
115  return Build(new ImageJob(source, requestedInfo)).ResultInfo;
116  }
virtual Bitmap Build(object source, ResizeSettings settings)
Resizes and processes the specified source image and returns a bitmap of the result. Note! This method assumes that transparency will be supported in the final output format, and therefore does not apply a matte color. Use &amp;bgcolor to specify a background color if you use this method with a non-transparent format such as Jpeg. If passed a source Stream, Bitmap, or Image instance, it will be disposed after use. Use disposeSource=False to disable that behavior.
override RequestedAction ImageResizer.ImageBuilder.PrepareDestinationBitmap ( ImageState  s)
inlineprotectedvirtual

Creates a bitmap of s.destSize dimensions, intializes a graphics object for it, and configures all the default settings.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 749 of file ImageBuilder.cs.

750  {
751  if (base.PrepareDestinationBitmap(s) == RequestedAction.Cancel) return RequestedAction.Cancel;
752 
753  if (s.sourceBitmap == null) return RequestedAction.None;
754 
755  //Create new bitmap using calculated size.
756  s.destBitmap = new Bitmap(s.destSize.Width,s.destSize.Height, PixelFormat.Format32bppArgb);
757 
758 
759  //Create graphics handle
760  Graphics g = s.destGraphics = Graphics.FromImage(s.destBitmap);
761 
762  //High quality everthing
763  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
764  g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
765  g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
766  g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
767  g.CompositingMode = CompositingMode.SourceOver;
768  return RequestedAction.None;
769  }
RequestedAction
What to do about remaining handlers/methods for the specified section
Bitmap sourceBitmap
The source bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:66
Size destSize
The size of the target bitmap image. Set after all sizing operations have completed.
Definition: ImageState.cs:47
override RequestedAction ImageResizer.ImageBuilder.PrepareSourceBitmap ( ImageState  s)
inlineprotectedvirtual

Process.1 Switches the bitmap to the correct frame or page, and applies source flipping commands

Parameters
s
Returns

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 629 of file ImageBuilder.cs.

630  {
631  if (base.PrepareSourceBitmap(s) == RequestedAction.Cancel) return RequestedAction.Cancel ; //Call extensions
632 
633  if (s.sourceBitmap == null) return RequestedAction.None ; //Nothing to do if there is no bitmap
634 
635  Bitmap src = s.sourceBitmap;
636  ResizeSettings q = s.settings;
637 
638  int page = 0;
639  if (!string.IsNullOrEmpty(q["page"]) && !int.TryParse(q["page"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out page))
640  page = 0;
641 
642  int frame = 0;
643  if (!string.IsNullOrEmpty(q["frame"]) && !int.TryParse(q["frame"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out frame))
644  frame = 0;
645 
646  //So users can use 1-based numbers
647  page--; frame--;
648 
649  //Support page selection in a .tiff document.
650  try {
651  //Stay on the last page/frame if out of bounds
652  if (page > 0 && page >= src.GetFrameCount(FrameDimension.Page)) page = src.GetFrameCount(FrameDimension.Page) - 1;
653  if (frame > 0 && frame >= src.GetFrameCount(FrameDimension.Time)) frame = src.GetFrameCount(FrameDimension.Time) - 1;
654 
655  //Select the right page/frame if specified
656  if (page > 0) src.SelectActiveFrame(FrameDimension.Page, page);
657  if (frame > 0) src.SelectActiveFrame(FrameDimension.Time, frame);
658  s.originalSize = s.sourceBitmap.Size;
659  } catch (ExternalException) { } //When somebody tries &frame or &page on a single-frame image
660 
661 
662 
663  //Flipping has to be done on the original - it can't be done as part of the DrawImage or later, after the borders are drawn.
664 
665  if (s.sourceBitmap != null && (s.settings.SourceFlip != RotateFlipType.RotateNoneFlipNone || !string.IsNullOrEmpty(s.settings["sRotate"]))) {
666  double angle = s.settings.Get<double>("sRotate",0);
667 
668  s.EnsurePreRenderBitmap();
669  s.preRenderBitmap.RotateFlip(PolygonMath.CombineFlipAndRotate(s.settings.SourceFlip, angle));
670  s.originalSize = s.preRenderBitmap.Size;
671  }
672  return RequestedAction.None;
673  }
RequestedAction
What to do about remaining handlers/methods for the specified section
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
RotateFlipType SourceFlip
[&quot;sFlip&quot;] Allows you to flip the source image vertically, horizontally, or both. Rotation is not supp...
Bitmap sourceBitmap
The source bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:66
virtual void ImageResizer.ImageBuilder.Process ( ImageState  s)
inlinevirtual

Processes an ImageState instance. Used by Build, GetFinalSize, and TranslatePoint. Can be overriden by a plugin with the OnProcess method

Parameters
s

Definition at line 561 of file ImageBuilder.cs.

561  {
562  if (OnProcess(s) == RequestedAction.Cancel) return;
563  PrepareSourceBitmap(s); // We select the page/frame and flip the source bitmap here
565  Layout(s); //Layout everything
566  PrepareDestinationBitmap(s); //Create a bitmap and graphics object based on s.destSize
567  Render(s); //Render using the graphics object
568  ProcessFinalBitmap(s); //Perform the final flipping of the bitmap.
569  EndProcess(s);
570  }
override RequestedAction Render(ImageState s)
Handles the rendering phase of processing
RequestedAction
What to do about remaining handlers/methods for the specified section
override RequestedAction ProcessFinalBitmap(ImageState s)
Process.6: Non-rendering changes to the bitmap object occur here, such as flipping. The graphics object is unavailable.
virtual RequestedAction EndProcess(ImageState s)
Process.7: Layout and rendering are both complete.
override RequestedAction PrepareSourceBitmap(ImageState s)
Process.1 Switches the bitmap to the correct frame or page, and applies source flipping commands ...
override RequestedAction Layout(ImageState s)
Process.3: Handles the layout phase of Processing
override RequestedAction PrepareDestinationBitmap(ImageState s)
Creates a bitmap of s.destSize dimensions, intializes a graphics object for it, and configures all th...
virtual RequestedAction OnProcess(ImageState s)
Process.0 First step of the Process() method. Can replace the entire Process method if RequestAction...
virtual RequestedAction PostPrepareSourceBitmap(ImageState s)
Process.2 Extend this to apply any pre-processing to the source bitmap that needs to occur before Lay...
override RequestedAction ImageResizer.ImageBuilder.ProcessFinalBitmap ( ImageState  s)
inlineprotectedvirtual

Process.6: Non-rendering changes to the bitmap object occur here, such as flipping. The graphics object is unavailable.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 906 of file ImageBuilder.cs.

906  {
907  if (base.ProcessFinalBitmap(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
908 
909  //The default if we are doing a simulation
910 
911  s.finalSize = s.destSize;
912  //Skip this when we are doing simulations
913  if (s.destBitmap == null) return RequestedAction.None;
914 
915  //The last flipping.
916  if (s.settings.Flip != RotateFlipType.RotateNoneFlipNone)
917  s.destBitmap.RotateFlip(s.settings.Flip);
918 
919  //Set DPI value
920  if (!string.IsNullOrEmpty(s.settings["dpi"])){
921  int dpi = s.settings.Get<int>("dpi",96);
922  s.destBitmap.SetResolution(dpi, dpi);
923  }
924 
925  s.finalSize = s.destBitmap.Size;
926  return RequestedAction.None;
927  }
RequestedAction
What to do about remaining handlers/methods for the specified section
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
Bitmap destBitmap
The destination bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:178
Size destSize
The size of the target bitmap image. Set after all sizing operations have completed.
Definition: ImageState.cs:47
RotateFlipType Flip
Allows you to flip the entire resulting image vertically, horizontally, or both. Rotation is not supp...
Size finalSize
The dimensions of the bitmap afer all operations have been applied to it (Calling FlipRotate can chan...
Definition: ImageState.cs:51
override RequestedAction ImageResizer.ImageBuilder.Render ( ImageState  s)
inlineprotectedvirtual

Handles the rendering phase of processing

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 601 of file ImageBuilder.cs.

601  {
602  if (base.Render(s) == RequestedAction.Cancel) return RequestedAction.Cancel;
603  RenderBackground(s);
605  RenderEffects(s);
607  RenderPadding(s);
611  PreRenderImage(s);
612  RenderImage(s);
613  PostRenderImage(s);
614  RenderBorder(s);
615  PostRenderBorder(s);
617  RenderOverlays(s);
618  PreFlushChanges(s);
619  FlushChanges(s);
620  PostFlushChanges(s);
621  return RequestedAction.None;
622  }
RequestedAction
What to do about remaining handlers/methods for the specified section
override RequestedAction RenderImage(ImageState s)
Process.5(Render).10: The image is copied to the destination parallelogram specified by ring &#39;image&#39;...
virtual RequestedAction PreRenderOverlays(ImageState s)
Process.5(Render).14: Any last-minute changes before watermarking or overlays are applied ...
virtual RequestedAction PostCreateImageAttributes(ImageState s)
Process.5(Render).8: The ImageAttributes instance exists and can be modified or replaced.
virtual RequestedAction PreFlushChanges(ImageState s)
Process.5(Render).16: Called before changes are flushed and the graphics object is destroyed...
override RequestedAction RenderPadding(ImageState s)
Process.5(Render).5 Image padding is drawn
override RequestedAction RenderBackground(ImageState s)
Sets the background color if needed or requested
override RequestedAction RenderBorder(ImageState s)
Process.5(Render).12: The border is rendered
virtual RequestedAction PostRenderEffects(ImageState s)
Process.5(Render).4 After outer effects are rendered
virtual RequestedAction PostRenderBackground(ImageState s)
Process.5(Render).2 After the background color is rendered
virtual RequestedAction PostFlushChanges(ImageState s)
Process.5(Render).18: Changes have been flushed to the bitmap, but the final bitmap has not been flip...
virtual RequestedAction PostRenderPadding(ImageState s)
Process.5(Render).6 After image padding is drawn
override RequestedAction FlushChanges(ImageState s)
Process.5(Render).17: Changes are flushed to the bitmap here and the graphics object is destroyed...
virtual RequestedAction RenderOverlays(ImageState s)
Process.5(Render).15: Watermarks can be rendered here. All image processing should be done ...
virtual RequestedAction PostRenderBorder(ImageState s)
Process.5(Render).13: After the border is drawn
virtual RequestedAction PostRenderImage(ImageState s)
Process.5(Render).11: After the image is drawn
override RequestedAction CreateImageAttribues(ImageState s)
Process.5(Render).7: An ImageAttributes instance is created if it doesn&#39;t already exist...
virtual RequestedAction RenderEffects(ImageState s)
Process.5(Render).3 Effects (such as a drop shadow or outer glow) are rendered
virtual RequestedAction PreRenderImage(ImageState s)
Process.5(Render).9: Plugins have a chance to pre-process the source image before it gets rendered...
override RequestedAction ImageResizer.ImageBuilder.RenderBackground ( ImageState  s)
inlineprotectedvirtual

Sets the background color if needed or requested

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 775 of file ImageBuilder.cs.

775  {
776  if (base.RenderBackground(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
777 
778  //Skip this when we are doing simulations
779  if (s.destGraphics == null) return RequestedAction.None;
780 
781  Graphics g = s.destGraphics;
782 
783  //If the image doesn't support transparency, we need to fill the background color now.
784  Color background = s.settings.BackgroundColor;
785 
786 
787 
788  //Find out if we can safely know that nothing will be showing from behind the image (no margin, padding, etc, and source format doesn't have alpha channel).
789  //Doesn't know anything about s.preRenderBitmap
790  bool nothingToShow = (s.sourceBitmap != null && (s.sourceBitmap.PixelFormat == PixelFormat.Format24bppRgb ||
791  s.sourceBitmap.PixelFormat == PixelFormat.Format32bppRgb ||
792  s.sourceBitmap.PixelFormat == PixelFormat.Format48bppRgb) &&
793  PolygonMath.ArraysEqual(s.layout["image"], s.layout.LastRing.points) &&
794  PolygonMath.IsUnrotated(s.layout["image"]) && string.IsNullOrEmpty(s.settings["s.alpha"])
795  && string.IsNullOrEmpty(s.settings["s.roundcorners"])
796  && string.IsNullOrEmpty(s.settings["filter"]));
797 
798  //Set the background to white if the background will be showing and the destination format doesn't support transparency.
799  if (background == Color.Transparent && !s.supportsTransparency & !nothingToShow)
800  background = Color.White;
801 
802 
803 
804  //Fill background
805  if (background != Color.Transparent) //This causes increased aliasing at the edges - i.e., a faint white border that is even more pronounced than usual.
806  g.Clear(background); //Does this work for Color.Transparent? --
807  return RequestedAction.None;
808  }
RequestedAction
What to do about remaining handlers/methods for the specified section
static Boolean ArraysEqual(PointF[] a1, PointF[] a2)
Returns true if the member elements of the specified arrays match, and the arrays are of the same len...
Definition: PolygonMath.cs:275
PointSet LastRing
Returns the last ring that was added. Only returns PointSets where flags = Ring
Graphics destGraphics
A graphics object to write to the destination bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:182
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
Defines a collection of utility functions for manipulating polygons. These functions may be (re)moved...
Definition: PolygonMath.cs:13
LayoutBuilder layout
The layout object. Used for calculated and flowing the layout of the various rings around the image (...
Definition: ImageState.cs:42
bool supportsTransparency
Rendering choices can depend on whether the output format supports transparency.
Definition: ImageState.cs:36
override RequestedAction ImageResizer.ImageBuilder.RenderBorder ( ImageState  s)
inlineprotectedvirtual

Process.5(Render).12: The border is rendered

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 857 of file ImageBuilder.cs.

857  {
858  if (base.RenderBorder(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
859 
860  //Skip this when we are doing simulations
861  if (s.destGraphics == null) return RequestedAction.None;
862 
863  //Draw border
864  if (s.settings.Border.IsEmpty) return RequestedAction.None;
865 
866  if (double.IsNaN(s.settings.Border.All)) {
867  float[] widths = new float[] { (float)s.settings.Border.Top * -1, (float)s.settings.Border.Right * -1, (float)s.settings.Border.Bottom * -1, (float)s.settings.Border.Left * -1 };
868  PointF[,] corners = PolygonMath.GetCorners(s.layout["border"],widths);
869 
870  for (int i = 0; i <= corners.GetUpperBound(0); i++) {
871  int last = i == 0 ? corners.GetUpperBound(0) : i -1;
872 
873  PointF start = PolygonMath.Average(corners[last, 3], corners[last, 0]);
874  PointF end = PolygonMath.Average(corners[i, 0], corners[i, 1]);
875 
876  using (Pen p = new Pen(s.settings.BorderColor, widths[i < 1 ? 3 : i -1] * -1)) {
877  p.Alignment = System.Drawing.Drawing2D.PenAlignment.Center; //PenAlignment.Center is the only supported mode.
878  p.LineJoin = System.Drawing.Drawing2D.LineJoin.Miter;
879  s.destGraphics.DrawLine(p, start, end);
880  }
881 
882  }
883  } else {
884  using (Pen p = new Pen(s.settings.BorderColor, (float)s.settings.Border.All)) {
885  p.Alignment = System.Drawing.Drawing2D.PenAlignment.Center; //PenAlignment.Center is the only supported mode.
886  p.LineJoin = System.Drawing.Drawing2D.LineJoin.Miter;
887  s.destGraphics.DrawPolygon(p, PolygonMath.InflatePoly(s.layout["border"], (float)(s.settings.Border.All / -2.0))); //I hope GDI rounds the same way as .NET.. Otherwise there may be an off-by-one error..
888  }
889  }
890 
891  return RequestedAction.None;
892  }
RequestedAction
What to do about remaining handlers/methods for the specified section
Graphics destGraphics
A graphics object to write to the destination bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:182
BoxPadding Border
Friendly get/set accessor for the [&quot;borderWidth&quot;] value. Returns BoxPadding.Empty when unspecified...
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
bool IsEmpty
Returns true if th
Definition: BoxPadding.cs:106
Color BorderColor
Gets/sets [&quot;borderColor&quot;]. Named and hex values are supported. (rgb and rgba, both 3...
double All
Returns double.NaN unless all edges are the same width, in which case that width is returned ...
Definition: BoxPadding.cs:88
override RequestedAction ImageResizer.ImageBuilder.RenderImage ( ImageState  s)
inlineprotectedvirtual

Process.5(Render).10: The image is copied to the destination parallelogram specified by ring 'image'.

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 835 of file ImageBuilder.cs.

835  {
836  if (base.RenderImage(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
837 
838  //Skip this when we are doing simulations
839  if (s.destGraphics == null) return RequestedAction.None;
840 
841  if (!string.IsNullOrEmpty(s.settings["gdi.filter"])) {
842  s.destGraphics.InterpolationMode = s.settings.Get<InterpolationMode>("gdi.filter", s.destGraphics.InterpolationMode);
843  }
844 
845  s.copyAttibutes.SetWrapMode(WrapMode.TileFlipXY);
846  if (s.preRenderBitmap != null) {
847  using (Bitmap b = s.preRenderBitmap) { //Dispose the intermediate bitmap aggressively
848  s.destGraphics.DrawImage(s.preRenderBitmap, PolygonMath.getParallelogram(s.layout["image"]),
849  s.copyRect, GraphicsUnit.Pixel, s.copyAttibutes);
850  }
851  } else {
852  s.destGraphics.DrawImage(s.sourceBitmap, PolygonMath.getParallelogram(s.layout["image"]), s.copyRect, GraphicsUnit.Pixel, s.copyAttibutes);
853  }
854  return RequestedAction.None;
855  }
RequestedAction
What to do about remaining handlers/methods for the specified section
Graphics destGraphics
A graphics object to write to the destination bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:182
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
ImageAttributes copyAttibutes
Allows color correction/modification during the image copy.
Definition: ImageState.cs:186
Bitmap preRenderBitmap
An optional intermediate bitmap, created by plugins who need to process the source bitmap it gets ren...
Definition: ImageState.cs:71
RectangleF copyRect
The rectangular portion of the source image to copy
Definition: ImageState.cs:57
override RequestedAction ImageResizer.ImageBuilder.RenderPadding ( ImageState  s)
inlineprotectedvirtual

Process.5(Render).5 Image padding is drawn

Parameters
s

Reimplemented from ImageResizer.Resizing.AbstractImageProcessor.

Definition at line 811 of file ImageBuilder.cs.

811  {
812  if (base.RenderPadding(s) == RequestedAction.Cancel) return RequestedAction.Cancel; //Call extensions
813 
814  //Skip this when we are doing simulations
815  if (s.destGraphics == null) return RequestedAction.None;
816 
817  if (!s.layout.ContainsRing("padding")) return RequestedAction.None;
818 
819  Color paddingColor = s.settings.PaddingColor;
820  //Inherit color
821  if (paddingColor.Equals(Color.Transparent)) paddingColor = s.settings.BackgroundColor;
822  //Draw padding around image if needed.
823  if (!paddingColor.Equals(s.settings.BackgroundColor) && paddingColor != Color.Transparent)
824  using (Brush b = new SolidBrush(paddingColor)) s.destGraphics.FillPolygon(b, s.layout["padding"]);
825 
826  return RequestedAction.None;
827  }
RequestedAction
What to do about remaining handlers/methods for the specified section
Graphics destGraphics
A graphics object to write to the destination bitmap. If null, skip drawing commands, but continue layout logic.
Definition: ImageState.cs:182
Color PaddingColor
Gets/sets [&quot;paddingColor&quot;]. Named and hex values are supported. (rgb and rgba, both 3...
Color BackgroundColor
[&quot;bgcolor&quot;]: Named and hex values are supported. (rgb and rgba, both 3, 6, and 8 digits).
ResizeSettings settings
The commands to apply to the bitmap
Definition: ImageState.cs:25
LayoutBuilder layout
The layout object. Used for calculated and flowing the layout of the various rings around the image (...
Definition: ImageState.cs:42
virtual PointF [] ImageResizer.ImageBuilder.TranslatePoints ( PointF[]  sourcePoints,
Size  originalSize,
ResizeSettings  q 
)
inlinevirtual

Doesn't support flipping. Translate a point on the original bitmap to a point on the new bitmap. If the original point no longer exists, returns Empty

Returns

Definition at line 934 of file ImageBuilder.cs.

934  {
935  ImageState s = new ImageState(q, originalSize, true);
936  s.layout.AddInvisiblePolygon("points", sourcePoints);
937  Process(s);
938  return s.layout["points"];
939  }
Encapsulates the state of an image being resized. Can be used to simulate a resize as well as actuall...
Definition: ImageState.cs:15
virtual void Process(ImageState s)
Processes an ImageState instance. Used by Build, GetFinalSize, and TranslatePoint. Can be overriden by a plugin with the OnProcess method

Property Documentation

ImageBuilder ImageResizer.ImageBuilder.Current
staticget

Returns a shared instance of ImageBuilder or a subclass, equivalent to Config.Current.CurrentImageBuilder

Returns

Definition at line 59 of file ImageBuilder.cs.

IEncoderProvider ImageResizer.ImageBuilder.EncoderProvider
get

Handles the encoder selection and provision proccess.

Definition at line 37 of file ImageBuilder.cs.

ISettingsModifier ImageResizer.ImageBuilder.SettingsModifier
get

May be null. A class to modify or normalize ResizeSettings instances before they are used.

Definition at line 44 of file ImageBuilder.cs.

IVirtualImageProvider ImageResizer.ImageBuilder.VirtualFileProvider
get

Provides a resolution service for app-relative URLs.

Definition at line 51 of file ImageBuilder.cs.


The documentation for this class was generated from the following file: