diff --git a/.nuget/NuGet.Config b/.nuget/NuGet.Config deleted file mode 100644 index 67f8ea046..000000000 --- a/.nuget/NuGet.Config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.nuget/NuGet.exe.REMOVED.git-id b/.nuget/NuGet.exe.REMOVED.git-id deleted file mode 100644 index 3379f42e0..000000000 --- a/.nuget/NuGet.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9ca66594f912a1fe7aec510819006fb1a80bc1a9 \ No newline at end of file diff --git a/.nuget/NuGet.targets b/.nuget/NuGet.targets deleted file mode 100644 index 3f8c37b22..000000000 --- a/.nuget/NuGet.targets +++ /dev/null @@ -1,144 +0,0 @@ - - - - $(MSBuildProjectDirectory)\..\ - - - false - - - false - - - true - - - false - - - - - - - - - - - $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) - - - - - $(SolutionDir).nuget - - - - $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config - $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config - - - - $(MSBuildProjectDirectory)\packages.config - $(PackagesProjectConfig) - - - - - $(NuGetToolsPath)\NuGet.exe - @(PackageSource) - - "$(NuGetExePath)" - mono --runtime=v4.0.30319 "$(NuGetExePath)" - - $(TargetDir.Trim('\\')) - - -RequireConsent - -NonInteractive - - "$(SolutionDir) " - "$(SolutionDir)" - - - $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) - $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols - - - - RestorePackages; - $(BuildDependsOn); - - - - - $(BuildDependsOn); - BuildPackage; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.nuget/packages.config b/.nuget/packages.config deleted file mode 100644 index 091917678..000000000 --- a/.nuget/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/ImageProcessor.sln b/ImageProcessor.sln index b2056a4ad..75e092892 100644 --- a/ImageProcessor.sln +++ b/ImageProcessor.sln @@ -1,20 +1,12 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor", "src\ImageProcessor\ImageProcessor.csproj", "{8047C4AC-7097-4DE4-B00D-6D55EBCF1D36}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Tests", "tests\ImageProcessor.Tests\ImageProcessor.Tests.csproj", "{1741DC66-5404-4B15-AE58-B7721F1568A4}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{3D5BCCE2-A7EB-4453-9A86-A9C55CCFDCDF}" - ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config - .nuget\NuGet.exe = .nuget\NuGet.exe - .nuget\NuGet.targets = .nuget\NuGet.targets - .nuget\packages.config = .nuget\packages.config - EndProjectSection -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU diff --git a/old/.gitattributes b/old/.gitattributes deleted file mode 100644 index a664be3a8..000000000 --- a/old/.gitattributes +++ /dev/null @@ -1,49 +0,0 @@ -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain - -*.jpg binary -*.png binary -*.gif binary - -*.cs text=auto diff=csharp -*.vb text=auto -*.c text=auto -*.cpp text=auto -*.cxx text=auto -*.h text=auto -*.hxx text=auto -*.py text=auto -*.rb text=auto -*.java text=auto -*.html text=auto -*.htm text=auto -*.css text=auto -*.scss text=auto -*.sass text=auto -*.less text=auto -*.js text=auto -*.lisp text=auto -*.clj text=auto -*.sql text=auto -*.php text=auto -*.lua text=auto -*.m text=auto -*.asm text=auto -*.erl text=auto -*.fs text=auto -*.fsx text=auto -*.hs text=auto - -*.csproj text=auto merge=union -*.vbproj text=auto merge=union -*.fsproj text=auto merge=union -*.dbproj text=auto merge=union -*.sln text=auto eol=crlf merge=union diff --git a/old/.gitignore b/old/.gitignore deleted file mode 100644 index 3fd18e8e1..000000000 --- a/old/.gitignore +++ /dev/null @@ -1,173 +0,0 @@ -################# -## Eclipse -################# - -*.pydevproject -.project -.metadata -bin/** -tmp/** -tmp/**/* -*.tmp -*.bak -*.swp -*~.nib -local.properties -.classpath -.settings/ -.loadpath - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - - -################# -## Visual Studio -################# - -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.sln.docstates - -# Build results -**/[Dd]ebug/ -**/[Rr]elease/ -*_i.c -*_p.c -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.vspscc -.builds -**/*.dotCover - -# Xamarin -*.userprefs - -## TODO: If you have NuGet Package Restore enabled, uncomment this -packages/ - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf - -# Visual Studio profiler -*.psess -*.vsp - -# ReSharper is a .NET coding add-in -_ReSharper* - -# Installshield output folder -[Ee]xpress - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish - -# Others -[Bb]in -[Oo]bj -sql -TestResults -*.Cache -ClientBin -stylecop.* -~$* -*.dbmdl -Generated_Code #added for RIA/Silverlight projects - -# Backup & report files from converting an old project file to a newer -# Visual Studio version. Backup files are not needed, because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML - - - -############ -## Windows -############ - -# Windows image file caches -Thumbs.db - -# Folder config file -Desktop.ini - - -############# -## Python -############# - -*.py[co] - -# Packages -*.egg -*.egg-info -dist -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox - -#Translations -*.mo - -#Mr Developer -.mr.developer.cfg - -# Mac crap -.DS_Store - -build/_BuildOutput/ -build/*.nupkg -build/TestResult.xml -*.db - -_site/ \ No newline at end of file diff --git a/old/APACHE-2.0-LICENSE.txt b/old/APACHE-2.0-LICENSE.txt deleted file mode 100644 index a666c6e07..000000000 --- a/old/APACHE-2.0-LICENSE.txt +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2012 James South - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/old/README.md b/old/README.md deleted file mode 100644 index 5ed8112fc..000000000 --- a/old/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# ImageProcessor - -### Build Status - -|Branch | | -|:--------|:--------| -|**Debug**|[![Build status](https://ci.appveyor.com/api/projects/status/8ypr7527dnao04yr?svg=true)](https://ci.appveyor.com/project/JamesSouth/imageprocessor)| -|**Release**|[![Build status](https://ci.appveyor.com/api/projects/status/8ypr7527dnao04yr/branch/Master?svg=true)](https://ci.appveyor.com/project/JamesSouth/imageprocessor/branch/Master)| -|**Coverage Report**|[![Coverage Status](https://coveralls.io/repos/JimBobSquarePants/ImageProcessor/badge.svg)](https://coveralls.io/r/JimBobSquarePants/ImageProcessor?branch=V2)| - -### Latest Releases -|Library |Version |Downloads | -|:-----------------|:-----------------|:-----------------| -|**ImageProcessor**|[![Nuget count](http://img.shields.io/nuget/v/ImageProcessor.svg)](https://www.nuget.org/packages/ImageProcessor/)|[![Nuget downloads](http://img.shields.io/nuget/dt/ImageProcessor.svg)](https://www.nuget.org/packages/ImageProcessor/)| -|**ImageProcessor.Web**|[![Nuget count](http://img.shields.io/nuget/v/ImageProcessor.Web.svg)](https://www.nuget.org/packages/ImageProcessor.Web/)|[![Nuget downloads](http://img.shields.io/nuget/dt/ImageProcessor.Web.svg)](https://www.nuget.org/packages/ImageProcessor.Web/)| - -[![Issues open](http://img.shields.io/github/issues-raw/JimBobSquarePants/imageprocessor.svg)](https://huboard.com/JimBobSquarePants/ImageProcessor/) -[![Source Browser](https://img.shields.io/badge/Browse-Source-green.svg)](http://sourcebrowser.io/Browse/JimBobSquarePants/ImageProcessor/) -[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/JimBobSquarePants/ImageProcessor?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -Imageprocessor is a lightweight, extensible library written in C# that allows you to manipulate images on-the-fly using .NET 4.5+ - -It's fast, extensible, easy to use, comes bundled with some great features and is fully open source. - -For full documentation please see [http://imageprocessor.org/](http://imageprocessor.org/) - -## Contributing to ImageProcessor -Contribution is most welcome! I mean, that's what this is all about isn't it? - -Things I would :heart: people to help me out with: - - - Unit tests. I need to get some going for all the regular expressions within the ImageProcessor core plus anywhere else we can think of. If that's your bag please contribute. - - Documentation. Nobody likes doing docs, I've written a lot but my prose is clumsy and verbose. If you think you can make things clearer or you spot any mistakes please submit a pull request (Guide to how the docs work below). - -**Just remember to StyleCop all things! :oncoming_police_car:** - -## RoadMap -I want the next version of ImageProcessor to run on all devices. Sadly it looks like using `System.Drawing` will not allow me to do that so I need to have a look at using an alternative. This is a lot of work so any help that could be offered would be greatly appreciated. - -## Documentation - -ImageProcessor's documentation, included in this repo in the gh-pages branch, is built with [Jekyll](http://jekyllrb.com) and publicly hosted on GitHub Pages at . The docs may also be run locally. - -### Running documentation locally -1. If necessary, [install Jekyll](http://jekyllrb.com/docs/installation) (requires v2.2.x). - - **Windows users:** Read [this unofficial guide](https://github.com/juthilo/run-jekyll-on-windows/) to get Jekyll up and running without problems. -2. From the root `/ImageProcessor` directory, run `jekyll serve` in the command line. -3. Open in your browser to navigate to your site. -Learn more about using Jekyll by reading its [documentation](http://jekyllrb.com/docs/home/). diff --git a/old/appveyor.yml b/old/appveyor.yml deleted file mode 100644 index 6bf4c35e7..000000000 --- a/old/appveyor.yml +++ /dev/null @@ -1,61 +0,0 @@ -# http://www.appveyor.com/docs/appveyor-yml - -#---------------------------------# -# general configuration # -#---------------------------------# - -# branches to build -branches: - - # blacklist - except: - - gh-pages - -#---------------------------------# -# environment configuration # -#---------------------------------# - -# Operating system (build VM template) -os: Windows Server 2012 - -# this is how to allow failing jobs in the matrix -matrix: - fast_finish: true # set this flag to immediately finish build once one of the jobs fails. - -environment: - COVERALLS_REPO_TOKEN: - secure: 1hvfHFO3qtGTcwB+AnCGYsn0az0j9MzAux5hee5CFeyRJ+lWut0LjnyqvsI/5Pfa - -#---------------------------------# -# build configuration # -#---------------------------------# - -# to run your custom scripts instead of automatic MSBuild -before_build: - - ps: Import-Module .\build\psake.psm1 - -build_script: - - ps: Invoke-Psake .\build\build.ps1 -properties @{"BuildNumber"=$env:APPVEYOR_BUILD_NUMBER;"AppVeyor"=$env:APPVEYOR;"CoverallsRepoToken"=$env:COVERALLS_REPO_TOKEN} - -#---------------------------------# -# tests configuration # -#---------------------------------# - -# to disable automatic tests (they're included in the build process) -test: off - -#---------------------------------# -# artifacts configuration # -#---------------------------------# - -artifacts: - - path: build\_BuildOutput\NuGets\*.nupkg - -#---------------------------------# -# global handlers # -#---------------------------------# - -# on successful build -on_success: - - ps: Import-Module .\build\psake.psm1 - - ps: Invoke-Psake .\build\build.ps1 Publish-Nuget -properties @{"NugetApiKey"=$env:APIKEY;"NugetSource"=$env:SOURCE} diff --git a/old/build/Build.bat b/old/build/Build.bat deleted file mode 100644 index d0526c7a7..000000000 --- a/old/build/Build.bat +++ /dev/null @@ -1,5 +0,0 @@ -@echo off - -powershell "Import-Module %~dp0\psake.psm1 ; Invoke-Psake %~dp0\build.ps1 ; exit $LASTEXITCODE" - -pause \ No newline at end of file diff --git a/old/build/Doxyfile.REMOVED.git-id b/old/build/Doxyfile.REMOVED.git-id deleted file mode 100644 index 9e5930093..000000000 --- a/old/build/Doxyfile.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -877afa6ca55ed11d2377363369ea1c39adace2d2 \ No newline at end of file diff --git a/old/build/ImageProcessorDoc.shfbproj b/old/build/ImageProcessorDoc.shfbproj deleted file mode 100644 index aee9be03b..000000000 --- a/old/build/ImageProcessorDoc.shfbproj +++ /dev/null @@ -1,85 +0,0 @@ - - - - - Debug - AnyCPU - 2.0 - {e3928e44-1c57-4c7e-9595-2a5b491455da} - 1.9.9.0 - - Documentation - Documentation - Documentation - - .NET Framework 4.0 - _BuildOutput\Help\SandCastle\ - Documentation - en-US - OnlyWarningsAndErrors - HtmlHelp1 - False - True - False - False - True - 2 - False - Standard - Blank - False - VS2013 - False - Guid - ImageProcessor Documented Class Library - AboveNamespaces - - - - - Imageprocessor is a lightweight library written in C# that allows you to manipulate images on-the-fly using .NET. - -It&#39%3bs fast, extensible, easy to use, comes bundled with some great features and is fully open source. - -For full documentation please see http://imageprocessor.org/ - - The main namespace for all features - Regroups the possible exceptions - Regroups the extensions - The library configuration - The imaging components - The filters to apply on the images - The possible image formats - The image processors - - Summary, Parameter, Returns, AutoDocumentCtors, TypeParameter, AutoDocumentDispose - _BuildOutput\Help\SandCastle\Working\ - - - - - - - - - - - - - - - - - - - - - ImageProcessor - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E} - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.Plugins.Cair.nuspec b/old/build/NuSpecs/ImageProcessor.Plugins.Cair.nuspec deleted file mode 100644 index 0614f13ae..000000000 --- a/old/build/NuSpecs/ImageProcessor.Plugins.Cair.nuspec +++ /dev/null @@ -1,31 +0,0 @@ - - - - ImageProcessor.Plugins.Cair - 1.0.1.0 - ImageProcessor.Plugins.Cair - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - Adds support to ImageProcessor for Content Aware Image Resizing. - -If you use ImageProcessor please get in touch via my twitter @james_m_south - -Feedback is always welcome - Adds support to ImageProcessor for Content Aware Image Resizing. - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff Cair Seam Carving - - - - - - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.Plugins.WebP.nuspec b/old/build/NuSpecs/ImageProcessor.Plugins.WebP.nuspec deleted file mode 100644 index 7e5c7ea9f..000000000 --- a/old/build/NuSpecs/ImageProcessor.Plugins.WebP.nuspec +++ /dev/null @@ -1,32 +0,0 @@ - - - - ImageProcessor.Plugins.WebP - 1.0.2.0 - ImageProcessor.Plugins.WebP - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - Adds support to ImageProcessor for the WebP image format. - -If you use ImageProcessor please get in touch via my twitter @james_m_south - -Feedback is always welcome - Adds support to ImageProcessor and ImageProcessor.Web for the WebP image format. - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff WebP - - - - - - - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.Web.Config.nuspec b/old/build/NuSpecs/ImageProcessor.Web.Config.nuspec deleted file mode 100644 index bd28b9625..000000000 --- a/old/build/NuSpecs/ImageProcessor.Web.Config.nuspec +++ /dev/null @@ -1,35 +0,0 @@ - - - - ImageProcessor.Web.Config - 2.2.1.0 - ImageProcessor.Web.Config - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - Adds configuration to your ImageProcessor.Web solution to allow you to override the default settings. - -If you use ImageProcessor.Web please get in touch via my twitter @james_m_south - -Feedback is always welcome - ImageProcessor.Web configuration settings for ASP.NET websites. - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff ASP Cache EXIF - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.Web.Plugins.AzureBlobCache.nuspec b/old/build/NuSpecs/ImageProcessor.Web.Plugins.AzureBlobCache.nuspec deleted file mode 100644 index 48eb13cb3..000000000 --- a/old/build/NuSpecs/ImageProcessor.Web.Plugins.AzureBlobCache.nuspec +++ /dev/null @@ -1,41 +0,0 @@ - - - - ImageProcessor.Web.Plugins.AzureBlobCache - 1.0.1.0 - ImageProcessor.Web.Plugins.AzureBlobCache - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - Adds a self cleaning cache that uses Azure Blob Containers to store processed images. - -If you use ImageProcessor.Web please get in touch via my twitter @james_m_south - -Feedback is always welcome - ImageProcessor.Web AzureBlobCache for ASP.NET websites. - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff Azure Cache Asp - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.Web.PostProcessor.nuspec b/old/build/NuSpecs/ImageProcessor.Web.PostProcessor.nuspec deleted file mode 100644 index 04034f5f3..000000000 --- a/old/build/NuSpecs/ImageProcessor.Web.PostProcessor.nuspec +++ /dev/null @@ -1,32 +0,0 @@ - - - - ImageProcessor.Web.PostProcessor - 1.0.3.0 - ImageProcessor.Web.PostProcessor - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - Applies various image compression tools to further optimize cached .png, .gif, and .jpg images. - -If you use ImageProcessor please get in touch via my twitter @james_m_south - -Feedback is always welcome - ImageProcessor.Web PostProcessor for ASP.NET websites. - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff ASP Cache EXIF - - - - - - - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.Web.nuspec b/old/build/NuSpecs/ImageProcessor.Web.nuspec deleted file mode 100644 index 5c6c43385..000000000 --- a/old/build/NuSpecs/ImageProcessor.Web.nuspec +++ /dev/null @@ -1,34 +0,0 @@ - - - - ImageProcessor.Web - 4.3.0.0 - ImageProcessor.Web - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - ImageProcessor.Web adds a configurable HttpModule to your website which allows on-the-fly processing of image files. The module also comes with a file and browser based cache that can handle millions of images, increasing your processing output and saving precious server memory. - -Methods include: Resize, Rotate, Rounded Corners, Flip, Crop, Watermark, Filter, Saturation, Brightness, Contrast, Quality, Format, Vignette, Gaussian Blur, Gaussian Sharpen, and Transparency. - -If you use ImageProcessor.Web please get in touch via my twitter @james_m_south - -Feedback is always welcome - An extension to ImageProcessor that allows on-the-fly processing of image files in an ASP.NET website - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff ASP Cache EXIF - - - - - - - - - - - \ No newline at end of file diff --git a/old/build/NuSpecs/ImageProcessor.nuspec b/old/build/NuSpecs/ImageProcessor.nuspec deleted file mode 100644 index 5a7ef518d..000000000 --- a/old/build/NuSpecs/ImageProcessor.nuspec +++ /dev/null @@ -1,29 +0,0 @@ - - - - ImageProcessor - 2.2.4.0 - ImageProcessor - James South - James South - http://imageprocessor.org - http://imageprocessor.org/assets/ico/apple-touch-icon-144x144.png - false - Image Processor is an easy to use and extend processing library written in C#. Its fluent API makes common imaging tasks very simple to perform. - -Methods include; Resize, Rotate, Rounded Corners, Flip, Crop, Watermark, Filter, Saturation, Brightness, Contrast, Quality, Format, Vignette, Gaussian Blur, Gaussian Sharpen, and Transparency. - -If you use ImageProcessor please get in touch on my twitter @james_m_south. - -Feedback is always welcome. - A library for manipulating image files written in C#. - - James South - en-GB - Image Resize Crop Rotate Quality Watermark Gif Jpg Jpeg Bitmap Png Tiff Fluent Animated EXIF - - - - - - \ No newline at end of file diff --git a/old/build/build.ps1 b/old/build/build.ps1 deleted file mode 100644 index 1e59052bb..000000000 --- a/old/build/build.ps1 +++ /dev/null @@ -1,244 +0,0 @@ -Properties { - # call nuget.bat with these values as parameters - $NugetApiKey = $null - $NugetSource = $null - - # see appveyor.yml for usage - $BuildNumber = $null - $CoverallsRepoToken = $null - $AppVeyor = $null - - # Input and output paths - $BUILD_PATH = Resolve-Path "." - $SRC_PATH = Join-Path $BUILD_PATH "..\src" - $PLUGINS_PATH = Join-Path $SRC_PATH "Plugins\ImageProcessor" - $NUSPECS_PATH = Join-Path $BUILD_PATH "NuSpecs" - $BIN_PATH = Join-Path $BUILD_PATH "_BuildOutput" - $NUGET_OUTPUT = Join-Path $BIN_PATH "NuGets" - $TEST_RESULTS = Join-Path $BUILD_PATH "TestResults" - - # API documentation - $API_BIN_PATH = Join-Path $BIN_PATH "ImageProcessor\lib\net45\ImageProcessor.dll" # from which DLL Docu builds its help output - $API_DOC_PATH = Join-Path $BIN_PATH "Help\docu" - - # External binaries paths - $NUGET_EXE = Join-Path $SRC_PATH ".nuget\NuGet.exe" - $NUNIT_EXE = Join-Path $SRC_PATH "packages\NUnit.Runners.2.6.3\tools\nunit-console.exe" - $COVERALLS_EXE = Join-Path $SRC_PATH "packages\coveralls.io.1.3.2\tools\coveralls.net.exe" - $OPENCOVER_EXE = Join-Path $SRC_PATH "packages\OpenCover.4.5.3809-rc94\OpenCover.Console.exe" - $REPORTGEN_EXE = Join-Path $SRC_PATH "packages\ReportGenerator.1.9.1.0\ReportGenerator.exe" - $NUNITREPORT_EXE = Join-Path $BUILD_PATH "tools\NUnitHTMLReportGenerator.exe" - - # list of projects - $PROJECTS_PATH = (Join-Path $BUILD_PATH "build.xml") - [xml]$PROJECTS = Get-Content $PROJECTS_PATH - - $TestProjects = @( - "ImageProcessor.UnitTests", - "ImageProcessor.Web.UnitTests" - ) -} - -Framework "4.0x86" -FormatTaskName "-------- {0} --------" - -task default -depends Cleanup-Binaries, Set-VersionNumber, Build-Solution, Run-Tests, Run-Coverage, Generate-Nuget - -# cleans up the binaries output folder -task Cleanup-Binaries { - Write-Host "Removing binaries and artifacts so everything is nice and clean" - if (Test-Path $BIN_PATH) { - Remove-Item $BIN_PATH -Force -Recurse - } - - if (Test-Path $NUGET_OUTPUT) { - Remove-Item $NUGET_OUTPUT -Force -Recurse - } - - if (Test-Path $TEST_RESULTS) { - Remove-Item $TEST_RESULTS -Force -Recurse - } -} - -# sets the version number from the build number in the build.xml file -task Set-VersionNumber { - if ($BuildNumber -eq $null -or $BuildNumber -eq "") { - return - } - - $PROJECTS.projects.project | % { - if ($_.version -match "([\d+\.]*)[\d+|\*]") { # get numbers of current version except last one - $_.version = "$($Matches[1])$BuildNumber" - } - } - $PROJECTS.Save($PROJECTS_PATH) -} - -# builds the solutions -task Build-Solution -depends Cleanup-Binaries, Set-VersionNumber { - Write-Host "Building projects" - - # build the projects - # regular "$xmlobject.node | % { $_ }" don't work when they're nested: http://fredmorrison.wordpress.com/2013/03/19/reading-xml-with-powershell-why-most-examples-you-see-are-wrong/ - [System.Xml.XmlElement] $root = $PROJECTS.get_DocumentElement() - [System.Xml.XmlElement] $project = $null - foreach($project in $root.ChildNodes) { - if ($project.projfile -eq $null -or $project.projfile -eq "") { - continue # goes to next item - } - - $projectPath = Resolve-Path $project.folder - Write-Host "Building project $($project.name) at version $($project.version)" - - # it would be possible to update more infos from the xml (description etc), so as to have all infos in one place - Update-AssemblyInfo -file (Join-Path $projectPath "Properties\AssemblyInfo.cs") -version $project.version - - [System.Xml.XmlElement] $output = $null - foreach($output in $project.outputs.ChildNodes) { - # using invoke-expression solves a few character escape issues - $buildCommand = "msbuild $(Join-Path $projectPath $project.projfile) /t:Build /p:Warnings=true /p:Configuration=Release /p:PipelineDependsOnBuild=False /p:OutDir=$(Join-Path $BIN_PATH $output.folder) $($output.additionalParameters) /clp:WarningsOnly /clp:ErrorsOnly /clp:Summary /clp:PerformanceSummary /v:Normal /nologo" - Write-Host $buildCommand -ForegroundColor DarkGreen - Exec { - Invoke-Expression $buildCommand - } - } - } -} - -# builds the test projects -task Build-Tests -depends Cleanup-Binaries { - Write-Host "Building the unit test projects" - - if (-not (Test-Path $TEST_RESULTS)) { - mkdir $TEST_RESULTS | Out-Null - } - - # make sure the runner exes are restored - & $NUGET_EXE restore (Join-Path $SRC_PATH "ImageProcessor.sln") - - # build the test projects - $TestProjects | % { - Write-Host "Building project $_" - Exec { - msbuild (Join-Path $SRC_PATH "$_\$_.csproj") /t:Build /p:Configuration=Release /p:Platform="AnyCPU" /p:Warnings=true /clp:WarningsOnly /clp:ErrorsOnly /v:Normal /nologo - } - } -} - -# runs the unit tests -task Run-Tests -depends Build-Tests { - Write-Host "Running unit tests" - $TestProjects | % { - $TestDllFolder = Join-Path $SRC_PATH "$_\bin\Release" - $TestDdlPath = Join-Path $TestDllFolder "$_.dll" - $TestOutputPath = Join-Path $TEST_RESULTS "$($_)_Unit.xml" - - Write-Host "Running unit tests on project $_" - & $NUNIT_EXE $TestDdlPath /result:$TestOutputPath /noshadow /nologo - - $ReportPath = (Join-Path $TEST_RESULTS "Tests") - if (-not (Test-Path $ReportPath)) { - mkdir $ReportPath | Out-Null - } - - Write-Host "Transforming tests results file to HTML" - & $NUNITREPORT_EXE $TestOutputPath (Join-Path $ReportPath "$_.html") - } -} - -# runs the code coverage (separate from the unit test because it takes so much longer) -task Run-Coverage -depends Build-Tests { - Write-Host "Running code coverage over unit tests" - $TestProjects | % { - $TestDllFolder = Join-Path $SRC_PATH "$_\bin\Release" - $TestDdlPath = Join-Path $TestDllFolder "$_.dll" - $CoverageOutputPath = Join-Path $TEST_RESULTS "$($_)_Coverage.xml" - - Write-Host "AppVeyor $AppVeyor" - - $appVeyor = "" - if ($AppVeyor -ne $null -and $AppVeyor -ne "") { - $appVeyor = " -appveyor" - } - - Write-Host "Running code coverage on project $_" - $coverageFilter = "-filter:+[*]* -[FluentAssertions*]* -[ImageProcessor]*Common.Exceptions -[ImageProcessor.UnitTests]* -[ImageProcessor.Web.UnitTests]*" - & $OPENCOVER_EXE -threshold:1 -oldstyle -register:user -target:$NUNIT_EXE -targetargs:"$TestDdlPath /noshadow /nologo" $appVeyor -targetdir:$TestDllFolder -output:$CoverageOutputPath $coverageFilter - - Write-Host "Transforming coverage results file to HTML" - & $REPORTGEN_EXE -verbosity:Info -reports:$CoverageOutputPath -targetdir:(Join-Path $TEST_RESULTS "Coverage\$_") - - Write-Host "CoverallsRepoToken $CoverallsRepoToken" - - if ($CoverallsRepoToken -ne $null -and $CoverallsRepoToken -ne "") { - Write-Host "Uploading coverage report to Coveralls.io" - Exec { . $COVERALLS_EXE --opencover $CoverageOutputPath } - } - } -} - -# generates the API documentation. Disabled for now. -task Generate-APIDoc -depends Build-Solution { - Write-Host "Generating API docs" - - & .\tools\docu\docu.exe $API_BIN_PATH --output=$API_DOC_PATH - - & .\tools\doxygen\doxygen.exe .\Doxyfile -} - -# generates a Nuget package -task Generate-Nuget -depends Set-VersionNumber, Build-Solution { - Write-Host "Generating Nuget packages for each project" - - # Nuget doesn't create the output dir automatically... - if (-not (Test-Path $NUGET_OUTPUT)) { - mkdir $NUGET_OUTPUT | Out-Null - } - - # Package the nuget - $PROJECTS.projects.project | % { - $nuspec_local_path = (Join-Path $NUSPECS_PATH $_.nuspec) - Write-Host "Building Nuget package from $nuspec_local_path" - - # change the version values - [xml]$nuspec_contents = Get-Content $nuspec_local_path - $nuspec_contents.package.metadata.version = $_.version - $nuspec_contents.Save($nuspec_local_path) - - if ((-not (Test-Path $nuspec_local_path)) -or (-not (Test-Path $NUGET_OUTPUT))) { - throw New-Object [System.IO.FileNotFoundException] "The file $nuspec_local_path or $NUGET_OUTPUT could not be found" - } - - # pack the nuget - & $NUGET_EXE Pack $nuspec_local_path -OutputDirectory $NUGET_OUTPUT - } -} - -# publishes the nuget on a feed -task Publish-Nuget { - if ($NugetApiKey -eq $null -or $NugetApiKey -eq "") { - throw New-Object [System.ArgumentException] "You must provide an API key as parameter: 'Invoke-psake Publish-Nuget -properties @{`"NugetApiKey`"=`"YOURAPIKEY`"}' ; or add a APIKEY environment variable to AppVeyor" - } - - Get-ChildItem $NUGET_OUTPUT -Filter "*.nugpkg" | % { - if ($NugetSource -eq $null -or $NugetSource -eq "") { - & $NUGET_EXE push $_ -ApiKey $apikey -Source $NugetSource - } else { - & $NUGET_EXE push $_ -ApiKey $apikey - } - } -} - -# updates the AssemblyInfo file with the specified version -# http://www.luisrocha.net/2009/11/setting-assembly-version-with-windows.html -function Update-AssemblyInfo ([string]$file, [string] $version) { - $assemblyVersionPattern = 'AssemblyVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)' - $fileVersionPattern = 'AssemblyFileVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)' - $assemblyVersion = 'AssemblyVersion("' + $version + '")'; - $fileVersion = 'AssemblyFileVersion("' + $version + '")'; - - (Get-Content $file) | ForEach-Object { - % {$_ -replace $assemblyVersionPattern, $assemblyVersion } | - % {$_ -replace $fileVersionPattern, $fileVersion } - } | Set-Content $file -} \ No newline at end of file diff --git a/old/build/build.xml b/old/build/build.xml deleted file mode 100644 index 694c0cada..000000000 --- a/old/build/build.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - ImageProcessor - 2.2.4.0 - ..\src\ImageProcessor - ImageProcessor.csproj - - - - - ImageProcessor.nuspec - - - - ImageProcessor Web - 4.3.0.0 - ..\src\ImageProcessor.Web - ImageProcessor.Web.csproj - - - - ImageProcessor.Web.nuspec - - - - ImageProcessor Web.config sample - 2.2.1.0 - ImageProcessor.Web.Config.nuspec - - - - ImageProcessor Web PostProcessor - 1.0.3.0 - ..\src\ImageProcessor.Web.PostProcessor - ImageProcessor.Web.PostProcessor.csproj - - - - ImageProcessor.Web.PostProcessor.nuspec - - - - ImageProcessor Web Azure Blob Cache plugin - 1.0.1.0 - ..\src\Plugins\ImageProcessor.Web\ImageProcessor.Web.Plugins.AzureBlobCache - ImageProcessor.Web.Plugins.AzureBlobCache.csproj - - - - ImageProcessor.Web.Plugins.AzureBlobCache.nuspec - - - - ImageProcessor Cair plugin - 1.0.1.0 - ..\src\Plugins\ImageProcessor\ImageProcessor.Plugins.Cair - ImageProcessor.Plugins.Cair.csproj - - - - ImageProcessor.Plugins.Cair.nuspec - - - - ImageProcessor WebP plugin - 1.0.2.0 - ..\src\Plugins\ImageProcessor\ImageProcessor.Plugins.WebP - ImageProcessor.Plugins.WebP.csproj - - - - ImageProcessor.Plugins.WebP.nuspec - - \ No newline at end of file diff --git a/old/build/content/ImageProcessor.Plugins.WebP/web.config.transform b/old/build/content/ImageProcessor.Plugins.WebP/web.config.transform deleted file mode 100644 index aaa15b857..000000000 --- a/old/build/content/ImageProcessor.Plugins.WebP/web.config.transform +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/old/build/content/ImageProcessor.Web.Config/web.config.transform b/old/build/content/ImageProcessor.Web.Config/web.config.transform deleted file mode 100644 index 6acc1eafd..000000000 --- a/old/build/content/ImageProcessor.Web.Config/web.config.transform +++ /dev/null @@ -1,16 +0,0 @@ - - - - -
-
-
- - - - - - - - - diff --git a/old/build/content/ImageProcessor.Web.Plugins.AzureBlobCache/config/imageprocessor/cache.config.transform b/old/build/content/ImageProcessor.Web.Plugins.AzureBlobCache/config/imageprocessor/cache.config.transform deleted file mode 100644 index 5e9e45ae3..000000000 --- a/old/build/content/ImageProcessor.Web.Plugins.AzureBlobCache/config/imageprocessor/cache.config.transform +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/old/build/content/ImageProcessor.Web/web.config.transform b/old/build/content/ImageProcessor.Web/web.config.transform deleted file mode 100644 index 1c216764f..000000000 --- a/old/build/content/ImageProcessor.Web/web.config.transform +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/old/build/coverage.bat b/old/build/coverage.bat deleted file mode 100644 index f27ef1d49..000000000 --- a/old/build/coverage.bat +++ /dev/null @@ -1,5 +0,0 @@ -@echo off - -powershell "Import-Module %~dp0\psake.psm1 ; Invoke-Psake %~dp0\build.ps1 Run-Coverage ; exit $LASTEXITCODE" - -pause \ No newline at end of file diff --git a/old/build/psake.psm1 b/old/build/psake.psm1 deleted file mode 100644 index c0d8ded03..000000000 --- a/old/build/psake.psm1 +++ /dev/null @@ -1,847 +0,0 @@ -# psake -# Copyright (c) 2012 James Kovacs -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -#Requires -Version 2.0 - -#-- Public Module Functions --# - -# .ExternalHelp psake.psm1-help.xml -function Invoke-Task -{ - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)] [string]$taskName - ) - - Assert $taskName ($msgs.error_invalid_task_name) - - $taskKey = $taskName.ToLower() - - if ($currentContext.aliases.Contains($taskKey)) { - $taskName = $currentContext.aliases.$taskKey.Name - $taskKey = $taskName.ToLower() - } - - $currentContext = $psake.context.Peek() - - Assert ($currentContext.tasks.Contains($taskKey)) ($msgs.error_task_name_does_not_exist -f $taskName) - - if ($currentContext.executedTasks.Contains($taskKey)) { return } - - Assert (!$currentContext.callStack.Contains($taskKey)) ($msgs.error_circular_reference -f $taskName) - - $currentContext.callStack.Push($taskKey) - - $task = $currentContext.tasks.$taskKey - - $precondition_is_valid = & $task.Precondition - - if (!$precondition_is_valid) { - WriteColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan - } else { - if ($taskKey -ne 'default') { - - if ($task.PreAction -or $task.PostAction) { - Assert ($task.Action -ne $null) ($msgs.error_missing_action_parameter -f $taskName) - } - - if ($task.Action) { - try { - foreach($childTask in $task.DependsOn) { - Invoke-Task $childTask - } - - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - $currentContext.currentTaskName = $taskName - - & $currentContext.taskSetupScriptBlock - - if ($task.PreAction) { - & $task.PreAction - } - - if ($currentContext.config.taskNameFormat -is [ScriptBlock]) { - & $currentContext.config.taskNameFormat $taskName - } else { - WriteColoredOutput ($currentContext.config.taskNameFormat -f $taskName) -foregroundcolor Cyan - } - - foreach ($variable in $task.requiredVariables) { - Assert ((test-path "variable:$variable") -and ((get-variable $variable).Value -ne $null)) ($msgs.required_variable_not_set -f $variable, $taskName) - } - - & $task.Action - - if ($task.PostAction) { - & $task.PostAction - } - - & $currentContext.taskTearDownScriptBlock - $task.Duration = $stopwatch.Elapsed - } catch { - if ($task.ContinueOnError) { - "-"*70 - WriteColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow - "-"*70 - $task.Duration = $stopwatch.Elapsed - } else { - throw $_ - } - } - } else { - # no action was specified but we still execute all the dependencies - foreach($childTask in $task.DependsOn) { - Invoke-Task $childTask - } - } - } else { - foreach($childTask in $task.DependsOn) { - Invoke-Task $childTask - } - } - - Assert (& $task.Postcondition) ($msgs.postcondition_failed -f $taskName) - } - - $poppedTaskKey = $currentContext.callStack.Pop() - Assert ($poppedTaskKey -eq $taskKey) ($msgs.error_corrupt_callstack -f $taskKey,$poppedTaskKey) - - $currentContext.executedTasks.Push($taskKey) -} - -# .ExternalHelp psake.psm1-help.xml -function Exec -{ - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][scriptblock]$cmd, - [Parameter(Position=1,Mandatory=0)][string]$errorMessage = ($msgs.error_bad_command -f $cmd), - [Parameter(Position=2,Mandatory=0)][int]$maxRetries = 0, - [Parameter(Position=3,Mandatory=0)][string]$retryTriggerErrorPattern = $null - ) - - $tryCount = 1 - - do { - try { - $global:lastexitcode = 0 - & $cmd - if ($lastexitcode -ne 0) { - throw ("Exec: " + $errorMessage) - } - break - } - catch [Exception] - { - if ($tryCount -gt $maxRetries) { - throw $_ - } - - if ($retryTriggerErrorPattern -ne $null) { - $isMatch = [regex]::IsMatch($_.Exception.Message, $retryTriggerErrorPattern) - - if ($isMatch -eq $false) { - throw $_ - } - } - - Write-Host "Try $tryCount failed, retrying again in 1 second..." - - $tryCount++ - - [System.Threading.Thread]::Sleep([System.TimeSpan]::FromSeconds(1)) - } - } - while ($true) -} - -# .ExternalHelp psake.psm1-help.xml -function Assert -{ - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)]$conditionToCheck, - [Parameter(Position=1,Mandatory=1)]$failureMessage - ) - if (!$conditionToCheck) { - throw ("Assert: " + $failureMessage) - } -} - -# .ExternalHelp psake.psm1-help.xml -function Task -{ - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][string]$name = $null, - [Parameter(Position=1,Mandatory=0)][scriptblock]$action = $null, - [Parameter(Position=2,Mandatory=0)][scriptblock]$preaction = $null, - [Parameter(Position=3,Mandatory=0)][scriptblock]$postaction = $null, - [Parameter(Position=4,Mandatory=0)][scriptblock]$precondition = {$true}, - [Parameter(Position=5,Mandatory=0)][scriptblock]$postcondition = {$true}, - [Parameter(Position=6,Mandatory=0)][switch]$continueOnError = $false, - [Parameter(Position=7,Mandatory=0)][string[]]$depends = @(), - [Parameter(Position=8,Mandatory=0)][string[]]$requiredVariables = @(), - [Parameter(Position=9,Mandatory=0)][string]$description = $null, - [Parameter(Position=10,Mandatory=0)][string]$alias = $null, - [Parameter(Position=11,Mandatory=0)][string]$maxRetries = 0, - [Parameter(Position=12,Mandatory=0)][string]$retryTriggerErrorPattern = $null - ) - if ($name -eq 'default') { - Assert (!$action) ($msgs.error_default_task_cannot_have_action) - } - - $newTask = @{ - Name = $name - DependsOn = $depends - PreAction = $preaction - Action = $action - PostAction = $postaction - Precondition = $precondition - Postcondition = $postcondition - ContinueOnError = $continueOnError - Description = $description - Duration = [System.TimeSpan]::Zero - RequiredVariables = $requiredVariables - Alias = $alias - MaxRetries = $maxRetries - RetryTriggerErrorPattern = $retryTriggerErrorPattern - } - - $taskKey = $name.ToLower() - - $currentContext = $psake.context.Peek() - - Assert (!$currentContext.tasks.ContainsKey($taskKey)) ($msgs.error_duplicate_task_name -f $name) - - $currentContext.tasks.$taskKey = $newTask - - if($alias) - { - $aliasKey = $alias.ToLower() - - Assert (!$currentContext.aliases.ContainsKey($aliasKey)) ($msgs.error_duplicate_alias_name -f $alias) - - $currentContext.aliases.$aliasKey = $newTask - } -} - -# .ExternalHelp psake.psm1-help.xml -function Properties { - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][scriptblock]$properties - ) - $psake.context.Peek().properties += $properties -} - -# .ExternalHelp psake.psm1-help.xml -function Include { - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][string]$fileNamePathToInclude - ) - Assert (test-path $fileNamePathToInclude -pathType Leaf) ($msgs.error_invalid_include_path -f $fileNamePathToInclude) - $psake.context.Peek().includes.Enqueue((Resolve-Path $fileNamePathToInclude)); -} - -# .ExternalHelp psake.psm1-help.xml -function FormatTaskName { - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)]$format - ) - $psake.context.Peek().config.taskNameFormat = $format -} - -# .ExternalHelp psake.psm1-help.xml -function TaskSetup { - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][scriptblock]$setup - ) - $psake.context.Peek().taskSetupScriptBlock = $setup -} - -# .ExternalHelp psake.psm1-help.xml -function TaskTearDown { - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][scriptblock]$teardown - ) - $psake.context.Peek().taskTearDownScriptBlock = $teardown -} - -# .ExternalHelp psake.psm1-help.xml -function Framework { - [CmdletBinding()] - param( - [Parameter(Position=0,Mandatory=1)][string]$framework - ) - $psake.context.Peek().config.framework = $framework - ConfigureBuildEnvironment -} - -# .ExternalHelp psake.psm1-help.xml -function Invoke-psake { - [CmdletBinding()] - param( - [Parameter(Position = 0, Mandatory = 0)][string] $buildFile, - [Parameter(Position = 1, Mandatory = 0)][string[]] $taskList = @(), - [Parameter(Position = 2, Mandatory = 0)][string] $framework, - [Parameter(Position = 3, Mandatory = 0)][switch] $docs = $false, - [Parameter(Position = 4, Mandatory = 0)][hashtable] $parameters = @{}, - [Parameter(Position = 5, Mandatory = 0)][hashtable] $properties = @{}, - [Parameter(Position = 6, Mandatory = 0)][alias("init")][scriptblock] $initialization = {}, - [Parameter(Position = 7, Mandatory = 0)][switch] $nologo = $false - ) - try { - if (-not $nologo) { - "psake version {0}`nCopyright (c) 2010 James Kovacs`n" -f $psake.version - } - - if (!$buildFile) { - $buildFile = $psake.config_default.buildFileName - } - elseif (!(test-path $buildFile -pathType Leaf) -and (test-path $psake.config_default.buildFileName -pathType Leaf)) { - # If the $config.buildFileName file exists and the given "buildfile" isn 't found assume that the given - # $buildFile is actually the target Tasks to execute in the $config.buildFileName script. - $taskList = $buildFile.Split(', ') - $buildFile = $psake.config_default.buildFileName - } - - # Execute the build file to set up the tasks and defaults - Assert (test-path $buildFile -pathType Leaf) ($msgs.error_build_file_not_found -f $buildFile) - - $psake.build_script_file = get-item $buildFile - $psake.build_script_dir = $psake.build_script_file.DirectoryName - $psake.build_success = $false - - $psake.context.push(@{ - "taskSetupScriptBlock" = {}; - "taskTearDownScriptBlock" = {}; - "executedTasks" = new-object System.Collections.Stack; - "callStack" = new-object System.Collections.Stack; - "originalEnvPath" = $env:path; - "originalDirectory" = get-location; - "originalErrorActionPreference" = $global:ErrorActionPreference; - "tasks" = @{}; - "aliases" = @{}; - "properties" = @(); - "includes" = new-object System.Collections.Queue; - "config" = CreateConfigurationForNewContext $buildFile $framework - }) - - LoadConfiguration $psake.build_script_dir - - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - - set-location $psake.build_script_dir - - LoadModules - - $frameworkOldValue = $framework - . $psake.build_script_file.FullName - - $currentContext = $psake.context.Peek() - - if ($framework -ne $frameworkOldValue) { - writecoloredoutput $msgs.warning_deprecated_framework_variable -foregroundcolor Yellow - $currentContext.config.framework = $framework - } - - ConfigureBuildEnvironment - - while ($currentContext.includes.Count -gt 0) { - $includeFilename = $currentContext.includes.Dequeue() - . $includeFilename - } - - if ($docs) { - WriteDocumentation - CleanupEnvironment - return - } - - foreach ($key in $parameters.keys) { - if (test-path "variable:\$key") { - set-item -path "variable:\$key" -value $parameters.$key -WhatIf:$false -Confirm:$false | out-null - } else { - new-item -path "variable:\$key" -value $parameters.$key -WhatIf:$false -Confirm:$false | out-null - } - } - - # The initial dot (.) indicates that variables initialized/modified in the propertyBlock are available in the parent scope. - foreach ($propertyBlock in $currentContext.properties) { - . $propertyBlock - } - - foreach ($key in $properties.keys) { - if (test-path "variable:\$key") { - set-item -path "variable:\$key" -value $properties.$key -WhatIf:$false -Confirm:$false | out-null - } - } - - # Simple dot sourcing will not work. We have to force the script block into our - # module's scope in order to initialize variables properly. - . $MyInvocation.MyCommand.Module $initialization - - # Execute the list of tasks or the default task - if ($taskList) { - foreach ($task in $taskList) { - invoke-task $task - } - } elseif ($currentContext.tasks.default) { - invoke-task default - } else { - throw $msgs.error_no_default_task - } - - WriteColoredOutput ("`n" + $msgs.build_success + "`n") -foregroundcolor Green - - WriteTaskTimeSummary $stopwatch.Elapsed - - $psake.build_success = $true - } catch { - $currentConfig = GetCurrentConfigurationOrDefault - if ($currentConfig.verboseError) { - $error_message = "{0}: An Error Occurred. See Error Details Below: `n" -f (Get-Date) - $error_message += ("-" * 70) + "`n" - $error_message += "Error: {0}`n" -f (ResolveError $_ -Short) - $error_message += ("-" * 70) + "`n" - $error_message += ResolveError $_ - $error_message += ("-" * 70) + "`n" - $error_message += "Script Variables" + "`n" - $error_message += ("-" * 70) + "`n" - $error_message += get-variable -scope script | format-table | out-string - } else { - # ($_ | Out-String) gets error messages with source information included. - $error_message = "Error: {0}: `n{1}" -f (Get-Date), (ResolveError $_ -Short) - } - - $psake.build_success = $false - - # if we are running in a nested scope (i.e. running a psake script from a psake script) then we need to re-throw the exception - # so that the parent script will fail otherwise the parent script will report a successful build - $inNestedScope = ($psake.context.count -gt 1) - if ( $inNestedScope ) { - throw $_ - } else { - if (!$psake.run_by_psake_build_tester) { - WriteColoredOutput $error_message -foregroundcolor Red - } - } - } finally { - CleanupEnvironment - } -} - -#-- Private Module Functions --# -function WriteColoredOutput { - param( - [string] $message, - [System.ConsoleColor] $foregroundcolor - ) - - $currentConfig = GetCurrentConfigurationOrDefault - if ($currentConfig.coloredOutput -eq $true) { - if (($Host.UI -ne $null) -and ($Host.UI.RawUI -ne $null) -and ($Host.UI.RawUI.ForegroundColor -ne $null)) { - $previousColor = $Host.UI.RawUI.ForegroundColor - $Host.UI.RawUI.ForegroundColor = $foregroundcolor - } - } - - $message - - if ($previousColor -ne $null) { - $Host.UI.RawUI.ForegroundColor = $previousColor - } -} - -function LoadModules { - $currentConfig = $psake.context.peek().config - if ($currentConfig.modules) { - - $scope = $currentConfig.moduleScope - - $global = [string]::Equals($scope, "global", [StringComparison]::CurrentCultureIgnoreCase) - - $currentConfig.modules | foreach { - resolve-path $_ | foreach { - "Loading module: $_" - $module = import-module $_ -passthru -DisableNameChecking -global:$global - if (!$module) { - throw ($msgs.error_loading_module -f $_.Name) - } - } - } - "" - } -} - -function LoadConfiguration { - param( - [string] $configdir = $PSScriptRoot - ) - - $psakeConfigFilePath = (join-path $configdir "psake-config.ps1") - - if (test-path $psakeConfigFilePath -pathType Leaf) { - try { - $config = GetCurrentConfigurationOrDefault - . $psakeConfigFilePath - } catch { - throw "Error Loading Configuration from psake-config.ps1: " + $_ - } - } -} - -function GetCurrentConfigurationOrDefault() { - if ($psake.context.count -gt 0) { - return $psake.context.peek().config - } else { - return $psake.config_default - } -} - -function CreateConfigurationForNewContext { - param( - [string] $buildFile, - [string] $framework - ) - - $previousConfig = GetCurrentConfigurationOrDefault - - $config = new-object psobject -property @{ - buildFileName = $previousConfig.buildFileName; - framework = $previousConfig.framework; - taskNameFormat = $previousConfig.taskNameFormat; - verboseError = $previousConfig.verboseError; - coloredOutput = $previousConfig.coloredOutput; - modules = $previousConfig.modules; - moduleScope = $previousConfig.moduleScope; - } - - if ($framework) { - $config.framework = $framework; - } - - if ($buildFile) { - $config.buildFileName = $buildFile; - } - - return $config -} - -function ConfigureBuildEnvironment { - $framework = $psake.context.peek().config.framework - if ($framework -cmatch '^((?:\d+\.\d+)(?:\.\d+){0,1})(x86|x64){0,1}$') { - $versionPart = $matches[1] - $bitnessPart = $matches[2] - } else { - throw ($msgs.error_invalid_framework -f $framework) - } - $versions = $null - $buildToolsVersions = $null - switch ($versionPart) { - '1.0' { - $versions = @('v1.0.3705') - } - '1.1' { - $versions = @('v1.1.4322') - } - '2.0' { - $versions = @('v2.0.50727') - } - '3.0' { - $versions = @('v2.0.50727') - } - '3.5' { - $versions = @('v3.5', 'v2.0.50727') - } - '4.0' { - $versions = @('v4.0.30319') - } - '4.5.1' { - $versions = @('v4.0.30319') - $buildToolsVersions = @('12.0') - } - default { - throw ($msgs.error_unknown_framework -f $versionPart, $framework) - } - } - - $bitness = 'Framework' - if ($versionPart -ne '1.0' -and $versionPart -ne '1.1') { - switch ($bitnessPart) { - 'x86' { - $bitness = 'Framework' - $buildToolsKey = 'MSBuildToolsPath32' - } - 'x64' { - $bitness = 'Framework64' - $buildToolsKey = 'MSBuildToolsPath' - } - { [string]::IsNullOrEmpty($_) } { - $ptrSize = [System.IntPtr]::Size - switch ($ptrSize) { - 4 { - $bitness = 'Framework' - $buildToolsKey = 'MSBuildToolsPath32' - } - 8 { - $bitness = 'Framework64' - $buildToolsKey = 'MSBuildToolsPath' - } - default { - throw ($msgs.error_unknown_pointersize -f $ptrSize) - } - } - } - default { - throw ($msgs.error_unknown_bitnesspart -f $bitnessPart, $framework) - } - } - } - $frameworkDirs = @() - if ($buildToolsVersions -ne $null) { - $frameworkDirs = @($buildToolsVersions | foreach { (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\$_" -Name $buildToolsKey).$buildToolsKey }) - } - $frameworkDirs = $frameworkDirs + @($versions | foreach { "$env:windir\Microsoft.NET\$bitness\$_\" }) - - for ($i = 0; $i -lt $frameworkDirs.Count; $i++) { - $dir = $frameworkDirs[$i] - if ($dir -Match "\$\(Registry:HKEY_LOCAL_MACHINE(.*?)@(.*)\)") { - $key = "HKLM:" + $matches[1] - $name = $matches[2] - $dir = (Get-ItemProperty -Path $key -Name $name).$name - $frameworkDirs[$i] = $dir - } - } - - $frameworkDirs | foreach { Assert (test-path $_ -pathType Container) ($msgs.error_no_framework_install_dir_found -f $_)} - - $env:path = ($frameworkDirs -join ";") + ";$env:path" - # if any error occurs in a PS function then "stop" processing immediately - # this does not effect any external programs that return a non-zero exit code - $global:ErrorActionPreference = "Stop" -} - -function CleanupEnvironment { - if ($psake.context.Count -gt 0) { - $currentContext = $psake.context.Peek() - $env:path = $currentContext.originalEnvPath - Set-Location $currentContext.originalDirectory - $global:ErrorActionPreference = $currentContext.originalErrorActionPreference - [void] $psake.context.Pop() - } -} - -function SelectObjectWithDefault -{ - [CmdletBinding()] - param( - [Parameter(ValueFromPipeline=$true)] - [PSObject] - $InputObject, - [string] - $Name, - $Value - ) - - process { - if ($_ -eq $null) { $Value } - elseif ($_ | Get-Member -Name $Name) { - $_.$Name - } - elseif (($_ -is [Hashtable]) -and ($_.Keys -contains $Name)) { - $_.$Name - } - else { $Value } - } -} - -# borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx -# modified to better handle SQL errors -function ResolveError -{ - [CmdletBinding()] - param( - [Parameter(ValueFromPipeline=$true)] - $ErrorRecord=$Error[0], - [Switch] - $Short - ) - - process { - if ($_ -eq $null) { $_ = $ErrorRecord } - $ex = $_.Exception - - if (-not $Short) { - $error_message = "`nErrorRecord:{0}ErrorRecord.InvocationInfo:{1}Exception:`n{2}" - $formatted_errorRecord = $_ | format-list * -force | out-string - $formatted_invocationInfo = $_.InvocationInfo | format-list * -force | out-string - $formatted_exception = '' - - $i = 0 - while ($ex -ne $null) { - $i++ - $formatted_exception += ("$i" * 70) + "`n" + - ($ex | format-list * -force | out-string) + "`n" - $ex = $ex | SelectObjectWithDefault -Name 'InnerException' -Value $null - } - - return $error_message -f $formatted_errorRecord, $formatted_invocationInfo, $formatted_exception - } - - $lastException = @() - while ($ex -ne $null) { - $lastMessage = $ex | SelectObjectWithDefault -Name 'Message' -Value '' - $lastException += ($lastMessage -replace "`n", '') - if ($ex -is [Data.SqlClient.SqlException]) { - $lastException += "(Line [$($ex.LineNumber)] " + - "Procedure [$($ex.Procedure)] Class [$($ex.Class)] " + - " Number [$($ex.Number)] State [$($ex.State)] )" - } - $ex = $ex | SelectObjectWithDefault -Name 'InnerException' -Value $null - } - $shortException = $lastException -join ' --> ' - - $header = $null - $current = $_ - $header = (($_.InvocationInfo | - SelectObjectWithDefault -Name 'PositionMessage' -Value '') -replace "`n", ' '), - ($_ | SelectObjectWithDefault -Name 'Message' -Value ''), - ($_ | SelectObjectWithDefault -Name 'Exception' -Value '') | - ? { -not [String]::IsNullOrEmpty($_) } | - Select -First 1 - - $delimiter = '' - if ((-not [String]::IsNullOrEmpty($header)) -and - (-not [String]::IsNullOrEmpty($shortException))) - { $delimiter = ' [<<==>>] ' } - - return "$($header)$($delimiter)Exception: $($shortException)" - } -} - -function WriteDocumentation { - $currentContext = $psake.context.Peek() - - if ($currentContext.tasks.default) { - $defaultTaskDependencies = $currentContext.tasks.default.DependsOn - } else { - $defaultTaskDependencies = @() - } - - $currentContext.tasks.Keys | foreach-object { - if ($_ -eq "default") { - return - } - - $task = $currentContext.tasks.$_ - new-object PSObject -property @{ - Name = $task.Name; - Alias = $task.Alias; - Description = $task.Description; - "Depends On" = $task.DependsOn -join ", " - Default = if ($defaultTaskDependencies -contains $task.Name) { $true } - } - } | sort 'Name' | format-table -autoSize -wrap -property Name,Alias,"Depends On",Default,Description -} - -function WriteTaskTimeSummary($invokePsakeDuration) { - "-" * 70 - "Build Time Report" - "-" * 70 - $list = @() - $currentContext = $psake.context.Peek() - while ($currentContext.executedTasks.Count -gt 0) { - $taskKey = $currentContext.executedTasks.Pop() - $task = $currentContext.tasks.$taskKey - if ($taskKey -eq "default") { - continue - } - $list += new-object PSObject -property @{ - Name = $task.Name; - Duration = $task.Duration - } - } - [Array]::Reverse($list) - $list += new-object PSObject -property @{ - Name = "Total:"; - Duration = $invokePsakeDuration - } - # using "out-string | where-object" to filter out the blank line that format-table prepends - $list | format-table -autoSize -property Name,Duration | out-string -stream | where-object { $_ } -} - -DATA msgs { -convertfrom-stringdata @' - error_invalid_task_name = Task name should not be null or empty string. - error_task_name_does_not_exist = Task {0} does not exist. - error_circular_reference = Circular reference found for task {0}. - error_missing_action_parameter = Action parameter must be specified when using PreAction or PostAction parameters for task {0}. - error_corrupt_callstack = Call stack was corrupt. Expected {0}, but got {1}. - error_invalid_framework = Invalid .NET Framework version, {0} specified. - error_unknown_framework = Unknown .NET Framework version, {0} specified in {1}. - error_unknown_pointersize = Unknown pointer size ({0}) returned from System.IntPtr. - error_unknown_bitnesspart = Unknown .NET Framework bitness, {0}, specified in {1}. - error_no_framework_install_dir_found = No .NET Framework installation directory found at {0}. - error_bad_command = Error executing command {0}. - error_default_task_cannot_have_action = 'default' task cannot specify an action. - error_duplicate_task_name = Task {0} has already been defined. - error_duplicate_alias_name = Alias {0} has already been defined. - error_invalid_include_path = Unable to include {0}. File not found. - error_build_file_not_found = Could not find the build file {0}. - error_no_default_task = 'default' task required. - error_loading_module = Error loading module {0}. - warning_deprecated_framework_variable = Warning: Using global variable $framework to set .NET framework version used is deprecated. Instead use Framework function or configuration file psake-config.ps1. - required_variable_not_set = Variable {0} must be set to run task {1}. - postcondition_failed = Postcondition failed for task {0}. - precondition_was_false = Precondition was false, not executing task {0}. - continue_on_error = Error in task {0}. {1} - build_success = Build Succeeded! -'@ -} - -import-localizeddata -bindingvariable msgs -erroraction silentlycontinue - -$script:psake = @{} -$psake.version = "4.3.2" # contains the current version of psake -$psake.context = new-object system.collections.stack # holds onto the current state of all variables -$psake.run_by_psake_build_tester = $false # indicates that build is being run by psake-BuildTester -$psake.config_default = new-object psobject -property @{ - buildFileName = "default.ps1"; - framework = "4.0"; - taskNameFormat = "Executing {0}"; - verboseError = $false; - coloredOutput = $true; - modules = $null; - moduleScope = ""; -} # contains default configuration, can be overriden in psake-config.ps1 in directory with psake.psm1 or in directory with current build script - -$psake.build_success = $false # indicates that the current build was successful -$psake.build_script_file = $null # contains a System.IO.FileInfo for the current build script -$psake.build_script_dir = "" # contains a string with fully-qualified path to current build script - -LoadConfiguration - -export-modulemember -function Invoke-psake, Invoke-Task, Task, Properties, Include, FormatTaskName, TaskSetup, TaskTearDown, Framework, Assert, Exec -variable psake diff --git a/old/build/tools/NUnitHTMLReportGenerator.exe.REMOVED.git-id b/old/build/tools/NUnitHTMLReportGenerator.exe.REMOVED.git-id deleted file mode 100644 index e34edfefe..000000000 --- a/old/build/tools/NUnitHTMLReportGenerator.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -75c3885b6db49741cd7c7efe3bda996c2fae5ae7 \ No newline at end of file diff --git a/old/build/tools/NUnitHTMLReportGenerator.exe.config b/old/build/tools/NUnitHTMLReportGenerator.exe.config deleted file mode 100644 index 3143478cc..000000000 --- a/old/build/tools/NUnitHTMLReportGenerator.exe.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/old/build/tools/docu/Interop.SparkLanguagePackageLib.dll b/old/build/tools/docu/Interop.SparkLanguagePackageLib.dll deleted file mode 100644 index 7e1a91547..000000000 Binary files a/old/build/tools/docu/Interop.SparkLanguagePackageLib.dll and /dev/null differ diff --git a/old/build/tools/docu/Spark.dll.REMOVED.git-id b/old/build/tools/docu/Spark.dll.REMOVED.git-id deleted file mode 100644 index b610d03f1..000000000 --- a/old/build/tools/docu/Spark.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d3fa096caf69385df6771dd68981b46e5e9193e1 \ No newline at end of file diff --git a/old/build/tools/docu/SparkLanguage.dll b/old/build/tools/docu/SparkLanguage.dll deleted file mode 100644 index 334e9e4ee..000000000 Binary files a/old/build/tools/docu/SparkLanguage.dll and /dev/null differ diff --git a/old/build/tools/docu/StructureMap.dll.REMOVED.git-id b/old/build/tools/docu/StructureMap.dll.REMOVED.git-id deleted file mode 100644 index 5b001dbb6..000000000 --- a/old/build/tools/docu/StructureMap.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -a8e84e553b884b6bd2ea01cf8ba12631b6788b1e \ No newline at end of file diff --git a/old/build/tools/docu/docu.exe.REMOVED.git-id b/old/build/tools/docu/docu.exe.REMOVED.git-id deleted file mode 100644 index 3dc214e09..000000000 --- a/old/build/tools/docu/docu.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -76e95d1e37dd5508a872071da057a2a74d14a833 \ No newline at end of file diff --git a/old/build/tools/docu/docu.exe.config b/old/build/tools/docu/docu.exe.config deleted file mode 100644 index e36560333..000000000 --- a/old/build/tools/docu/docu.exe.config +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/old/build/tools/docu/templates/!namespace/!type.htm.spark b/old/build/tools/docu/templates/!namespace/!type.htm.spark deleted file mode 100644 index c9805e1c2..000000000 --- a/old/build/tools/docu/templates/!namespace/!type.htm.spark +++ /dev/null @@ -1,82 +0,0 @@ - - - - - ${h(Type.PrettyName)} - ${WriteProductName(Assemblies[0])} Documentation - - - - - - - - -

${WriteProductName(Assemblies[0])} : API Documentation

-
- - - -
-
-

Type ${h(Type.PrettyName)}

-
-
-
-

Namespace ${Namespace.Name}

-

Parent ${Format(Type.ParentType)}

-

Interfaces ${WriteInterfaces(Type.Interfaces)}

-
-
- -
- - - -
-
- - -

Events

-
    -
  • ${Format(ev)}
  • -
-
- - -

Methods

-
    -
  • ${Format(method)}
  • -
-
- - -

Properties

-
    -
  • ${Format(property)}
  • -
-
- - -

Fields

-
    -
  • ${Format(field)}
  • -
-
-
- - - - - - - - - - -
-
- - - \ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_comment.spark b/old/build/tools/docu/templates/!namespace/_comment.spark deleted file mode 100644 index 122c081aa..000000000 --- a/old/build/tools/docu/templates/!namespace/_comment.spark +++ /dev/null @@ -1 +0,0 @@ -${Format(content)} \ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_events.spark b/old/build/tools/docu/templates/!namespace/_events.spark deleted file mode 100644 index 14cdf31c1..000000000 --- a/old/build/tools/docu/templates/!namespace/_events.spark +++ /dev/null @@ -1,12 +0,0 @@ - -

${title}

- -
-

${h(ev.Name)}

-
- - - -
-
-
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_example.spark b/old/build/tools/docu/templates/!namespace/_example.spark deleted file mode 100644 index 6a40b3be2..000000000 --- a/old/build/tools/docu/templates/!namespace/_example.spark +++ /dev/null @@ -1,4 +0,0 @@ -
- Show Example -
${Format(content)}
-
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_fields.spark b/old/build/tools/docu/templates/!namespace/_fields.spark deleted file mode 100644 index c4c0478c9..000000000 --- a/old/build/tools/docu/templates/!namespace/_fields.spark +++ /dev/null @@ -1,19 +0,0 @@ - -

${title}

- -
-

${h(field.ReturnType.PrettyName)} ${h(field.Name)}

-
- - - - - - -
- return ${Format(field.ReturnType)} -
- -
-
-
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_methods.spark b/old/build/tools/docu/templates/!namespace/_methods.spark deleted file mode 100644 index c09e75e3b..000000000 --- a/old/build/tools/docu/templates/!namespace/_methods.spark +++ /dev/null @@ -1,46 +0,0 @@ - -

${title}

- -
-

- ${Format(method.ReturnType)} ${h(method.PrettyName)}(${OutputMethodParams(method)}) -

-
- - - - - - -
-
Parameters
-
- -
- ${Format(param.Reference)} ${param.Name} -
-
- -
-
-
-
- -
- -
Returns
-
-
- ${Format(method.ReturnType)} -
-
- -
-
-
- - - -
-
-
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_namespaces.spark b/old/build/tools/docu/templates/!namespace/_namespaces.spark deleted file mode 100644 index 763707537..000000000 --- a/old/build/tools/docu/templates/!namespace/_namespaces.spark +++ /dev/null @@ -1,14 +0,0 @@ - \ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_properties.spark b/old/build/tools/docu/templates/!namespace/_properties.spark deleted file mode 100644 index 90b880092..000000000 --- a/old/build/tools/docu/templates/!namespace/_properties.spark +++ /dev/null @@ -1,27 +0,0 @@ - -

${title}

- -
-

- ${Format(property.ReturnType)} ${h(property.Name)} get; set; -

-
- - - -
-
Property type
-
-
- ${Format(property.ReturnType)} -
-
- -
-
-
- - -
-
-
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_remarks.spark b/old/build/tools/docu/templates/!namespace/_remarks.spark deleted file mode 100644 index 06ffb0f61..000000000 --- a/old/build/tools/docu/templates/!namespace/_remarks.spark +++ /dev/null @@ -1,3 +0,0 @@ -
- ${Format(content)} -
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_types.spark b/old/build/tools/docu/templates/!namespace/_types.spark deleted file mode 100644 index 3ca313f8f..000000000 --- a/old/build/tools/docu/templates/!namespace/_types.spark +++ /dev/null @@ -1,14 +0,0 @@ - \ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/_value.spark b/old/build/tools/docu/templates/!namespace/_value.spark deleted file mode 100644 index a2c789e96..000000000 --- a/old/build/tools/docu/templates/!namespace/_value.spark +++ /dev/null @@ -1,3 +0,0 @@ -
- Value: ${Format(content)} -
\ No newline at end of file diff --git a/old/build/tools/docu/templates/!namespace/index.htm.spark b/old/build/tools/docu/templates/!namespace/index.htm.spark deleted file mode 100644 index 13c872122..000000000 --- a/old/build/tools/docu/templates/!namespace/index.htm.spark +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - ${Namespace.Name} - ${WriteProductName(Assemblies[0])} Documentation - - - - - - - -

${WriteProductName(Assemblies[0])} : API Documentation

-
- - -
-
-

Namespace ${Namespace.Name}

-
-
-
- -

Classes

-
    - -
  • ${Format(type)}
  • -
    -
-
- - -

Interfaces

-
    - -
  • ${Format(type)}
  • -
    -
-
-

This namespace is empty.

-
-
-
- - - \ No newline at end of file diff --git a/old/build/tools/docu/templates/_common_footer.spark b/old/build/tools/docu/templates/_common_footer.spark deleted file mode 100644 index d25fc776e..000000000 --- a/old/build/tools/docu/templates/_common_footer.spark +++ /dev/null @@ -1,6 +0,0 @@ -
- Built from v${WriteVersion(Assemblies[0])} of ${WriteAssemblyTitle(Assemblies[0])} - - Generated by docu - -
\ No newline at end of file diff --git a/old/build/tools/docu/templates/_namespaces.spark b/old/build/tools/docu/templates/_namespaces.spark deleted file mode 100644 index c0ce60faa..000000000 --- a/old/build/tools/docu/templates/_namespaces.spark +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/old/build/tools/docu/templates/_types.spark b/old/build/tools/docu/templates/_types.spark deleted file mode 100644 index b55f5acac..000000000 --- a/old/build/tools/docu/templates/_types.spark +++ /dev/null @@ -1,10 +0,0 @@ - \ No newline at end of file diff --git a/old/build/tools/docu/templates/index.htm.spark b/old/build/tools/docu/templates/index.htm.spark deleted file mode 100644 index aa0e501d0..000000000 --- a/old/build/tools/docu/templates/index.htm.spark +++ /dev/null @@ -1,23 +0,0 @@ - - - - - ${WriteProductName(Assemblies[0])} API Documentation - - - - -

${WriteProductName(Assemblies[0])} : API Documentation

-
- - -
-
-

${WriteProductName(Assemblies[0])} Documentation

-
-
- - - \ No newline at end of file diff --git a/old/build/tools/docu/templates/js/example.js b/old/build/tools/docu/templates/js/example.js deleted file mode 100644 index f805c21cc..000000000 --- a/old/build/tools/docu/templates/js/example.js +++ /dev/null @@ -1,21 +0,0 @@ -$(document).ready(function() { - $('div.example').each(function(i, div) { - var a = $('a', div); - var pre = $('pre', div); - - a.pre = pre; - a.preVisible = false; - pre.hide(); - a.click(function() { - if (a.preVisible) { - a.pre.hide(); - a.text('Show Example'); - a.preVisible = false; - } else { - a.pre.show(); - a.text('Hide Example'); - a.preVisible = true; - } - }); - }); -}); \ No newline at end of file diff --git a/old/build/tools/docu/templates/js/jquery-1.3.2.min.js b/old/build/tools/docu/templates/js/jquery-1.3.2.min.js deleted file mode 100644 index b1ae21d8b..000000000 --- a/old/build/tools/docu/templates/js/jquery-1.3.2.min.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * jQuery JavaScript Library v1.3.2 - * http://jquery.com/ - * - * Copyright (c) 2009 John Resig - * Dual licensed under the MIT and GPL licenses. - * http://docs.jquery.com/License - * - * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) - * Revision: 6246 - */ -(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("",""]||!O.indexOf("",""]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!O.indexOf("",""]||(!O.indexOf("",""]||!O.indexOf("",""]||!o.support.htmlSerialize&&[1,"div
","
"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); -/* - * Sizzle CSS Selector Engine - v0.9.3 - * Copyright 2009, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return UT[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="

";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="
";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("
").append(M.responseText.replace(//g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='
';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/old/build/tools/docu/templates/js/jquery.scrollTo-min.js b/old/build/tools/docu/templates/js/jquery.scrollTo-min.js deleted file mode 100644 index 5e7877810..000000000 --- a/old/build/tools/docu/templates/js/jquery.scrollTo-min.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * jQuery.ScrollTo - Easy element scrolling using jQuery. - * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com - * Dual licensed under MIT and GPL. - * Date: 5/25/2009 - * @author Ariel Flesler - * @version 1.4.2 - * - * http://flesler.blogspot.com/2007/10/jqueryscrollto.html - */ -;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery); \ No newline at end of file diff --git a/old/build/tools/docu/templates/js/navigation.js b/old/build/tools/docu/templates/js/navigation.js deleted file mode 100644 index 4eb8eea76..000000000 --- a/old/build/tools/docu/templates/js/navigation.js +++ /dev/null @@ -1,11 +0,0 @@ -$(document).ready(function() { - var scroll = function(selector) { - var currentItem = $(selector + ' .current'); - - if (currentItem) - $(selector + ' div.scroll').scrollTo(currentItem); - }; - - scroll('#namespaces'); - scroll('#types'); -}); \ No newline at end of file diff --git a/old/build/tools/docu/templates/main.css b/old/build/tools/docu/templates/main.css deleted file mode 100644 index 98e24e6d5..000000000 --- a/old/build/tools/docu/templates/main.css +++ /dev/null @@ -1,263 +0,0 @@ -/* HTML5 ? Boilerplate */ - -html, body, div, span, object, iframe, -h1, h2, h3, h4, h5, h6, p, blockquote, pre, -abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, -small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, -fieldset, form, label, legend, -table, caption, tbody, tfoot, thead, tr, th, td, -article, aside, canvas, details, figcaption, figure, -footer, header, hgroup, menu, nav, section, summary, -time, mark, audio, video { - margin: 0; - padding: 0; - border: 0; - font-size: 100%; - font: inherit; - vertical-align: baseline; -} - -article, aside, details, figcaption, figure, -footer, header, hgroup, menu, nav, section { - display: block; -} - -blockquote, q { quotes: none; } -blockquote:before, blockquote:after, -q:before, q:after { content: ""; content: none; } -ins { background-color: #ff9; color: #000; text-decoration: none; } -mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; } -del { text-decoration: line-through; } -abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; } -table { border-collapse: collapse; border-spacing: 0; } -hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } -input, select { vertical-align: middle; } - -body { font:13px/1.231 sans-serif; } -select, input, textarea, button { font:99% sans-serif; } -pre, code, kbd, samp { font-family: monospace, sans-serif; } - -html { overflow-y: scroll; } -a:hover, a:active { outline: none; } -ul, ol { margin-left: 2em; } -ol { list-style-type: decimal; } -nav ul, nav li { margin: 0; list-style:none; list-style-image: none; } -small { font-size: 85%; } -strong, th { font-weight: bold; } -td { vertical-align: top; } -sub, sup { font-size: 75%; line-height: 0; position: relative; } -sup { top: -0.5em; } -sub { bottom: -0.25em; } - -pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; padding: 15px; } -textarea { overflow: auto; } -.ie6 legend, .ie7 legend { margin-left: -7px; } -input[type="radio"] { vertical-align: text-bottom; } -input[type="checkbox"] { vertical-align: bottom; } -.ie7 input[type="checkbox"] { vertical-align: baseline; } -.ie6 input { vertical-align: text-bottom; } -label, input[type="button"], input[type="submit"], input[type="image"], button { cursor: pointer; } -button, input, select, textarea { margin: 0; } -input:valid, textarea:valid { } -input:invalid, textarea:invalid { -moz-box-shadow: 0px 0px 5px red; -webkit-box-shadow: 0px 0px 5px red; } -.no-boxshadow input:invalid, .no-boxshadow textarea:invalid { background-color: #f0dddd; } - - -::-moz-selection{ background: #FF5E99; color:#fff; } -::selection { background:#FF5E99; color:#fff; } -a:link { -webkit-tap-highlight-color: #FF5E99; } -button { width: auto; overflow: visible; } -.ie7 img { -ms-interpolation-mode: bicubic; } - -h1, h2, h3, h4, h5, h6 { font-weight: bold; } -a, a:active, a:visited { color: #607890; } -a:hover { color: #036; } - - -/** - * Primary styles - * - * Author: Dylan Beattie (dylan@dylanbeattie.net) - */ - -body > header { - position: absolute; - left: 8px; - right: 8px; - top: 8px; - height: 16px; - padding: 4px; - border: 1px solid #333333; -} - -body > header > span#project-link { - position: absolute; - right: 4px; - top: 4px; -} - -body { - background-color: #999999; -} -nav { - padding: 0px; -} -div.scroll { - padding: 4px; - overflow: auto; - position: absolute; - top: 24px; - bottom: 0px; - left: 0px; - right: 0px; - background-color: #fff; -} - -div.scroll ul li { - padding: 2px 0px; -} -div.scroll ul li a { - text-decoration: none; -} -nav#namespaces { - position: absolute; - top: 42px; - left: 8px; - bottom: 8px; - width: 384px; - overflow: hidden; -} - -nav#types { - position: absolute; - top: 42px; - right: 8px; - left: 400px; - height: 204px; - background-color: #fff; - overflow: hidden; -} - -article { - position: absolute; - left: 400px; - top: 256px; - bottom: 40px; - right: 8px; - background-color: #fff; -} -footer { - position: absolute; - left: 400px; - bottom: 8px; - height: 16px; - right: 8px; - background-color: #aaaaaa; - padding: 4px; - font-size: 80%; -} - -header { - background-color: #cccccc; -} -header p { - padding: 4px; -} - -nav h2, header p.class { - background-color: #333333; - padding: 4px; - color: #fff; -} - -article section { - position: absolute; - top: 24px; - bottom: 0px; - left: 0px; - right: 0px; - overflow:auto; -} - -section ul li { - margin: 4px 0px; -} -article section header p { margin: 0px; } -article section h3, article section p { - padding: 4px; - margin: 4px 0px; -} -article section h3 { - font-size: 120%; -} -div.method { - padding: 4px 4px 4px 16px; -} - -div#summary { - padding: 4px; -} - -div.method div.content { - margin: 8px; -} - -footer span#docu-link { - position: absolute; - right: 4px; -} -code { - font-family: Consolas, Courier, monospaced; - font-weight: normal; -} - - -h5 { - margin: 8px 0px; -} - -dl dt { width: 180px; float: left; } -dl dd { margin-left: 180px; } - - - -.ir { display: block; text-indent: -999em; overflow: hidden; background-repeat: no-repeat; text-align: left; direction: ltr; } -.hidden { display: none; visibility: hidden; } -.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } -.visuallyhidden.focusable:active, -.visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } -.invisible { visibility: hidden; } -.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; } -.clearfix:after { clear: both; } -.clearfix { zoom: 1; } - - -@media all and (orientation:portrait) { - -} - -@media all and (orientation:landscape) { - -} - -@media screen and (max-device-width: 480px) { - - /* html { -webkit-text-size-adjust:none; -ms-text-size-adjust:none; } */ -} - - -@media print { - * { background: transparent !important; color: black !important; text-shadow: none !important; filter:none !important; - -ms-filter: none !important; } - a, a:visited { color: #444 !important; text-decoration: underline; } - a[href]:after { content: " (" attr(href) ")"; } - abbr[title]:after { content: " (" attr(title) ")"; } - .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } - pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } - thead { display: table-header-group; } - tr, img { page-break-inside: avoid; } - @page { margin: 0.5cm; } - p, h2, h3 { orphans: 3; widows: 3; } - h2, h3{ page-break-after: avoid; } -} - diff --git a/old/build/tools/doxygen/doxygen.exe.REMOVED.git-id b/old/build/tools/doxygen/doxygen.exe.REMOVED.git-id deleted file mode 100644 index 8cb27a61b..000000000 --- a/old/build/tools/doxygen/doxygen.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -e3cd94630633d09a5360ed77a721700f36ce2ec4 \ No newline at end of file diff --git a/old/build/tools/doxygen/doxyindexer.exe.REMOVED.git-id b/old/build/tools/doxygen/doxyindexer.exe.REMOVED.git-id deleted file mode 100644 index 2b08b0b66..000000000 --- a/old/build/tools/doxygen/doxyindexer.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -cf2127aaa212a8eee4938f3b7fd3a09151eacbce \ No newline at end of file diff --git a/old/build/tools/doxygen/doxysearch.cgi.REMOVED.git-id b/old/build/tools/doxygen/doxysearch.cgi.REMOVED.git-id deleted file mode 100644 index 5dbddf870..000000000 --- a/old/build/tools/doxygen/doxysearch.cgi.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -0621db7f369243429e07a6fcd66833db3a83c16e \ No newline at end of file diff --git a/old/src/.nuget/NuGet.Config b/old/src/.nuget/NuGet.Config deleted file mode 100644 index 67f8ea046..000000000 --- a/old/src/.nuget/NuGet.Config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/old/src/.nuget/NuGet.exe.REMOVED.git-id b/old/src/.nuget/NuGet.exe.REMOVED.git-id deleted file mode 100644 index 1c070b576..000000000 --- a/old/src/.nuget/NuGet.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -3ffdd33c6106bb292523c979289efb2b30220df5 \ No newline at end of file diff --git a/old/src/.nuget/NuGet.targets b/old/src/.nuget/NuGet.targets deleted file mode 100644 index 83fe90601..000000000 --- a/old/src/.nuget/NuGet.targets +++ /dev/null @@ -1,136 +0,0 @@ - - - - $(MSBuildProjectDirectory)\..\ - - - false - - - false - - - true - - - false - - - - - - - - - - - $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) - $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) - - - - - $(SolutionDir).nuget - packages.config - - - - - $(NuGetToolsPath)\NuGet.exe - @(PackageSource) - - "$(NuGetExePath)" - mono --runtime=v4.0.30319 $(NuGetExePath) - - $(TargetDir.Trim('\\')) - - -RequireConsent - -NonInteractive - - "$(SolutionDir) " - "$(SolutionDir)" - - - $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) - $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols - - - - RestorePackages; - $(BuildDependsOn); - - - - - $(BuildDependsOn); - BuildPackage; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/.nuget/packages.config b/old/src/.nuget/packages.config deleted file mode 100644 index aaa9ef5a0..000000000 --- a/old/src/.nuget/packages.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/App.config b/old/src/ImageProcessor.Playground/App.config deleted file mode 100644 index d1428ad71..000000000 --- a/old/src/ImageProcessor.Playground/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/old/src/ImageProcessor.Playground/ImageProcessor.Playground.csproj b/old/src/ImageProcessor.Playground/ImageProcessor.Playground.csproj deleted file mode 100644 index 9bdf6c2b8..000000000 --- a/old/src/ImageProcessor.Playground/ImageProcessor.Playground.csproj +++ /dev/null @@ -1,87 +0,0 @@ - - - - - Debug - AnyCPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7} - Exe - Properties - ImageProcessor.PlayGround - ImageProcessor.PlayGround - v4.5 - 512 - true - - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - {3c805e4c-d679-43f8-8c43-8909cdb4d4d7} - ImageProcessor.Web.Plugins.AzureBlobCache - - - {d011a778-59c8-4bfa-a770-c350216bf161} - ImageProcessor.Web - - - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E} - ImageProcessor - - - {c7d1f0dd-cbd6-4127-82b4-51949eff0bf5} - ImageProcessor.Plugins.Cair - - - {2cf69699-959a-44dc-a281-4e2596c25043} - ImageProcessor.Plugins.WebP - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/Program.cs b/old/src/ImageProcessor.Playground/Program.cs deleted file mode 100644 index 0ea7594df..000000000 --- a/old/src/ImageProcessor.Playground/Program.cs +++ /dev/null @@ -1,186 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The program. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.PlayGround -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Drawing; - using System.IO; - using System.Linq; - - using ImageProcessor; - using ImageProcessor.Configuration; - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Filters.EdgeDetection; - //using ImageProcessor.Imaging.Filters.ObjectDetection; - using ImageProcessor.Imaging.Filters.Photo; - using ImageProcessor.Imaging.Formats; - using ImageProcessor.Processors; - using ImageProcessor.Web.Caching; - - /// - /// The program. - /// - public class Program - { - /// - /// The main routine. - /// - /// - /// The args. - /// - public static void Main(string[] args) - { - string path = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath; - - // ReSharper disable once AssignNullToNotNullAttribute - string resolvedPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\input")); - DirectoryInfo di = new DirectoryInfo(resolvedPath); - if (!di.Exists) - { - di.Create(); - } - - // Image mask = Image.FromFile(Path.Combine(resolvedPath, "mask.png")); - // Image overlay = Image.FromFile(Path.Combine(resolvedPath, "imageprocessor.128.png")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "2008.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "stretched.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "mountain.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "blur-test.png")); - // FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "earth_lights_4800.tif")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "gamma-1.0-or-2.2.png")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "gamma_dalai_lama_gray.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "Arc-de-Triomphe-France.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "Martin-Schoeller-Jack-Nicholson-Portrait.jpeg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "night-bridge.png")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "tree.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "blue-balloon.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "test2.png")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "120430.gif")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "rickroll.original.gif")); - - //////FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "crop-base-300x200.jpg")); - //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "cmyk.png")); - //IEnumerable files = GetFilesByExtensions(di, ".gif"); - //IEnumerable files = GetFilesByExtensions(di, ".png", ".jpg", ".jpeg"); - // IEnumerable files = GetFilesByExtensions(di, ".jpg", ".jpeg", ".jfif"); - IEnumerable files = GetFilesByExtensions(di, ".png"); - //IEnumerable files = GetFilesByExtensions(di, ".gif", ".webp", ".bmp", ".jpg", ".png"); - - foreach (FileInfo fileInfo in files) - { - if (fileInfo.Name == "test5.jpg") - { - continue; - } - - byte[] photoBytes = File.ReadAllBytes(fileInfo.FullName); - Console.WriteLine("Processing: " + fileInfo.Name); - - Stopwatch stopwatch = new Stopwatch(); - stopwatch.Start(); - - // ImageProcessor - using (MemoryStream inStream = new MemoryStream(photoBytes)) - { - using (ImageFactory imageFactory = new ImageFactory(true, true)) - { - Size size = new Size(1920, 1920); - //CropLayer cropLayer = new CropLayer(20, 20, 20, 20, ImageProcessor.Imaging.CropMode.Percentage); - ResizeLayer layer = new ResizeLayer(size, ResizeMode.Max, AnchorPosition.Center, false); - // TextLayer textLayer = new TextLayer() - //{ - // Text = "هناك حقيقة مثبتة منذ زمن", - // FontColor = Color.White, - // DropShadow = true, - // Vertical = true, - // //RightToLeft = true, - // //Position = new Point(5, 5) - - //}; - - //ContentAwareResizeLayer layer = new ContentAwareResizeLayer(size) - //{ - // ConvolutionType = ConvolutionType.Sobel - //}; - // Load, resize, set the format and quality and save an image. - imageFactory.Load(inStream) - //.DetectObjects(EmbeddedHaarCascades.FrontFaceDefault) - //.Overlay(new ImageLayer - // { - // Image = overlay, - // Opacity = 50 - // }) - //.Alpha(50) - //.BackgroundColor(Color.White) - //.Resize(new Size((int)(size.Width * 1.1), 0)) - //.ContentAwareResize(layer) - //.Constrain(size) - //.Mask(mask) - //.Format(new PngFormat()) - //.BackgroundColor(Color.Cyan) - //.Watermark(textLayer) - //.ReplaceColor(Color.FromArgb(93, 136, 231), Color.FromArgb(94, 134, 78), 50) - //.GaussianSharpen(3) - //.Saturation(20) - //.Resize(size) - .Resize(layer) - // .Resize(new ResizeLayer(size, ResizeMode.Stretch)) - //.DetectEdges(new SobelEdgeFilter(), true) - //.DetectEdges(new LaplacianOfGaussianEdgeFilter()) - //.GaussianBlur(new GaussianLayer(10, 11)) - //.EntropyCrop() - //.Gamma(2.2F) - //.Halftone() - //.RotateBounded(150, false) - //.Crop(cropLayer) - //.Rotate(140) - //.Filter(MatrixFilters.Invert) - //.Brightness(-5) - //.Contrast(50) - //.Filter(MatrixFilters.Comic) - //.Flip() - //.Filter(MatrixFilters.HiSatch) - //.Pixelate(8) - //.GaussianSharpen(10) - //.Format(new PngFormat() { IsIndexed = true }) - //.Format(new PngFormat() ) - .Save(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\output", fileInfo.Name))); - //.Save(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\output", Path.GetFileNameWithoutExtension(fileInfo.Name) + ".png"))); - - stopwatch.Stop(); - } - } - - long peakWorkingSet64 = Process.GetCurrentProcess().PeakWorkingSet64; - float mB = peakWorkingSet64 / (float)1024 / 1024; - - Console.WriteLine(@"Completed {0} in {1:s\.fff} secs {2}Peak memory usage was {3} bytes or {4} Mb.", fileInfo.Name, stopwatch.Elapsed, Environment.NewLine, peakWorkingSet64.ToString("#,#"), mB); - - //Console.WriteLine("Processed: " + fileInfo.Name + " in " + stopwatch.ElapsedMilliseconds + "ms"); - } - - Console.ReadLine(); - } - - public static IEnumerable GetFilesByExtensions(DirectoryInfo dir, params string[] extensions) - { - if (extensions == null) - { - throw new ArgumentNullException("extensions"); - } - - IEnumerable files = dir.EnumerateFiles(); - return files.Where(f => extensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)); - } - } -} diff --git a/old/src/ImageProcessor.Playground/Properties/AssemblyInfo.cs b/old/src/ImageProcessor.Playground/Properties/AssemblyInfo.cs deleted file mode 100644 index a39a9ca43..000000000 --- a/old/src/ImageProcessor.Playground/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessorConsole")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ImageProcessorConsole")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ac215639-6e27-4b9c-9ebb-9116c7a5d8a6")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/old/src/ImageProcessor.Playground/images/input/000.png b/old/src/ImageProcessor.Playground/images/input/000.png deleted file mode 100644 index 892574db1..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/000.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/001.png b/old/src/ImageProcessor.Playground/images/input/001.png deleted file mode 100644 index 0a7f19e2d..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/001.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/120430.gif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/120430.gif.REMOVED.git-id deleted file mode 100644 index e55299d03..000000000 --- a/old/src/ImageProcessor.Playground/images/input/120430.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -56ba9f614f44f7c905481f35e7609cb93e8fe98c \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/1aaa.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/1aaa.jpg.REMOVED.git-id deleted file mode 100644 index 169a4049b..000000000 --- a/old/src/ImageProcessor.Playground/images/input/1aaa.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -68e14cae5c31c58b8b66d26bca6eb67c79ecd203 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/2006-citybus.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/2006-citybus.jpg.REMOVED.git-id deleted file mode 100644 index 7b98fa949..000000000 --- a/old/src/ImageProcessor.Playground/images/input/2006-citybus.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -7f6786517fa67c9dfccac831e8491e4d08866d24 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/2008.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/2008.jpg.REMOVED.git-id deleted file mode 100644 index 9e3731b87..000000000 --- a/old/src/ImageProcessor.Playground/images/input/2008.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -7eb554b7681119b1170b70f1c1c2fc0de28a60ac \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/2012-citybus.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/2012-citybus.jpg.REMOVED.git-id deleted file mode 100644 index 5d7234332..000000000 --- a/old/src/ImageProcessor.Playground/images/input/2012-citybus.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -8d39e89104598b85035a2c29592b847edcfdb8ac \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/4.sm.webp b/old/src/ImageProcessor.Playground/images/input/4.sm.webp deleted file mode 100644 index 8bbe329f7..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/4.sm.webp and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/Arc-de-Triomphe-France.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/Arc-de-Triomphe-France.jpg.REMOVED.git-id deleted file mode 100644 index 6423c7d48..000000000 --- a/old/src/ImageProcessor.Playground/images/input/Arc-de-Triomphe-France.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -ff6cd6bf1cd388e8933071ec36880c33d1bc08f2 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/Bikesgray.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/Bikesgray.png.REMOVED.git-id deleted file mode 100644 index defbf8e5e..000000000 --- a/old/src/ImageProcessor.Playground/images/input/Bikesgray.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -93b93eade2c7697a0a8fe9363d493a8a59de245a \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/Calliphora_sp_Portrait.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/Calliphora_sp_Portrait.jpg.REMOVED.git-id deleted file mode 100644 index 44bed7ad3..000000000 --- a/old/src/ImageProcessor.Playground/images/input/Calliphora_sp_Portrait.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -5d446f64d0636f6ad7e9f82625eeff89ef394fe2 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/IC580196.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/IC580196.jpg.REMOVED.git-id deleted file mode 100644 index 9309d677c..000000000 --- a/old/src/ImageProcessor.Playground/images/input/IC580196.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9ab3fa52dd238ee4caffb47c82929f4079dc38d3 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/Martin-Schoeller-Jack-Nicholson-Portrait.jpeg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/Martin-Schoeller-Jack-Nicholson-Portrait.jpeg.REMOVED.git-id deleted file mode 100644 index 421c52201..000000000 --- a/old/src/ImageProcessor.Playground/images/input/Martin-Schoeller-Jack-Nicholson-Portrait.jpeg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -ea3907f002c75115c976edb47c9a8ba28e76ad9a \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/PIA11667_modest.jpg b/old/src/ImageProcessor.Playground/images/input/PIA11667_modest.jpg deleted file mode 100644 index dafede989..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/PIA11667_modest.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/Tl4Yb.gif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/Tl4Yb.gif.REMOVED.git-id deleted file mode 100644 index 8ac65a1a1..000000000 --- a/old/src/ImageProcessor.Playground/images/input/Tl4Yb.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d5f9ac17c265d12d9d08f8bbeaf3ff13b54b149a \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/Turtle.jpg b/old/src/ImageProcessor.Playground/images/input/Turtle.jpg deleted file mode 100644 index 0e9319495..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/Turtle.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/Valve_original_(1).PNG.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/Valve_original_(1).PNG.REMOVED.git-id deleted file mode 100644 index 6659a180b..000000000 --- a/old/src/ImageProcessor.Playground/images/input/Valve_original_(1).PNG.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -bdff6764fd5c4e3054ba7d8c43cc8c29be0e6f5e \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/arc_de_triomphe_paris_france.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/arc_de_triomphe_paris_france.jpg.REMOVED.git-id deleted file mode 100644 index 5aa90ba7d..000000000 --- a/old/src/ImageProcessor.Playground/images/input/arc_de_triomphe_paris_france.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c679b986c1ccbd9f6f8d72d7e4717f380b923a75 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/blue-balloon.jpg b/old/src/ImageProcessor.Playground/images/input/blue-balloon.jpg deleted file mode 100644 index 70c5339be..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/blue-balloon.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/blur-test.jpg b/old/src/ImageProcessor.Playground/images/input/blur-test.jpg deleted file mode 100644 index 1c7dab26b..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/blur-test.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/blur-test.png b/old/src/ImageProcessor.Playground/images/input/blur-test.png deleted file mode 100644 index ffd08acbd..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/blur-test.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/bob_revolutionpro_wilderness_02_2013_72dpi_2000x2000.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/bob_revolutionpro_wilderness_02_2013_72dpi_2000x2000.jpg.REMOVED.git-id deleted file mode 100644 index 6a0fdbe79..000000000 --- a/old/src/ImageProcessor.Playground/images/input/bob_revolutionpro_wilderness_02_2013_72dpi_2000x2000.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -cfa62bc3b77a7efb16c25218c1381da5d4f36db7 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/cat.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/cat.jpg.REMOVED.git-id deleted file mode 100644 index 573b513a6..000000000 --- a/old/src/ImageProcessor.Playground/images/input/cat.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c704af2c49aa45e35eab9e1b4839edbb7221cc7e \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/ce1a34f6-52bd-11e4-8164-54281a6247c9.jpg b/old/src/ImageProcessor.Playground/images/input/ce1a34f6-52bd-11e4-8164-54281a6247c9.jpg deleted file mode 100644 index 570794c53..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/ce1a34f6-52bd-11e4-8164-54281a6247c9.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/circle.png b/old/src/ImageProcessor.Playground/images/input/circle.png deleted file mode 100644 index 95a38af8a..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/circle.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/circle2.png b/old/src/ImageProcessor.Playground/images/input/circle2.png deleted file mode 100644 index cc3873a15..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/circle2.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/circle3.png b/old/src/ImageProcessor.Playground/images/input/circle3.png deleted file mode 100644 index 4bd234165..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/circle3.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/cmyk-test.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/cmyk-test.png.REMOVED.git-id deleted file mode 100644 index 0ab3955c1..000000000 --- a/old/src/ImageProcessor.Playground/images/input/cmyk-test.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b6a165b747788ab89169b1b0ab7a66c1a67eeaee \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/cmyk.png b/old/src/ImageProcessor.Playground/images/input/cmyk.png deleted file mode 100644 index e5c625d43..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/cmyk.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/cow_PNG2140.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/cow_PNG2140.png.REMOVED.git-id deleted file mode 100644 index 5932019f7..000000000 --- a/old/src/ImageProcessor.Playground/images/input/cow_PNG2140.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -04b381ec37fffdbffa55d5b02478ad81375eaa4b \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/crop-base-300x200.jpg b/old/src/ImageProcessor.Playground/images/input/crop-base-300x200.jpg deleted file mode 100644 index e31a8b05a..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/crop-base-300x200.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/earth_lights_4800.tif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/earth_lights_4800.tif.REMOVED.git-id deleted file mode 100644 index 311632374..000000000 --- a/old/src/ImageProcessor.Playground/images/input/earth_lights_4800.tif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -e44293020be795c40cbb19f2bad7d8589d479fb2 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/effect_24bit.png b/old/src/ImageProcessor.Playground/images/input/effect_24bit.png deleted file mode 100644 index bd594381d..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/effect_24bit.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/eye-162182_1280.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/eye-162182_1280.png.REMOVED.git-id deleted file mode 100644 index 0c0b81578..000000000 --- a/old/src/ImageProcessor.Playground/images/input/eye-162182_1280.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -0693daaf5dc3451fcad6b9ad910fbdfcfa3f9882 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/gamma-1.0-or-2.2.png b/old/src/ImageProcessor.Playground/images/input/gamma-1.0-or-2.2.png deleted file mode 100644 index 6d2ba91fb..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/gamma-1.0-or-2.2.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/gamma_3x3.jpg b/old/src/ImageProcessor.Playground/images/input/gamma_3x3.jpg deleted file mode 100644 index d5524d2a8..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/gamma_3x3.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/gamma_colors.jpg b/old/src/ImageProcessor.Playground/images/input/gamma_colors.jpg deleted file mode 100644 index de44ac896..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/gamma_colors.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/gamma_dalai_lama_gray.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/gamma_dalai_lama_gray.jpg.REMOVED.git-id deleted file mode 100644 index c6c87c96c..000000000 --- a/old/src/ImageProcessor.Playground/images/input/gamma_dalai_lama_gray.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -56cbc3371def2882d1ead5d4d2456550f2b8d72c \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/gamma_rainbow.jpg b/old/src/ImageProcessor.Playground/images/input/gamma_rainbow.jpg deleted file mode 100644 index 44d996782..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/gamma_rainbow.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/giphy.gif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/giphy.gif.REMOVED.git-id deleted file mode 100644 index be4a3c389..000000000 --- a/old/src/ImageProcessor.Playground/images/input/giphy.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -8703a0c9c6f32367beed0377419a74a70fee6da0 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/grad.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/grad.png.REMOVED.git-id deleted file mode 100644 index e19918107..000000000 --- a/old/src/ImageProcessor.Playground/images/input/grad.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c30305a6617a68a2f5671b6a69dbe832d9f73e08 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/h9ghTMB.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/h9ghTMB.png.REMOVED.git-id deleted file mode 100644 index c25e3802f..000000000 --- a/old/src/ImageProcessor.Playground/images/input/h9ghTMB.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -a442c2c7ce00c44e7de9f8221ad2c396be3431c5 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/haarcascade_frontalface_alt.xml.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/haarcascade_frontalface_alt.xml.REMOVED.git-id deleted file mode 100644 index 7b391478a..000000000 --- a/old/src/ImageProcessor.Playground/images/input/haarcascade_frontalface_alt.xml.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b3860ad6afc1b4eeab715c0de52156a24ec976e7 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/img_52061.jfif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/img_52061.jfif.REMOVED.git-id deleted file mode 100644 index d151f319a..000000000 --- a/old/src/ImageProcessor.Playground/images/input/img_52061.jfif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -8725839c23cba63894d1c8646e8cfd87c615c1fc \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/mask.png b/old/src/ImageProcessor.Playground/images/input/mask.png deleted file mode 100644 index f86272dc3..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/mask.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/mask2.png b/old/src/ImageProcessor.Playground/images/input/mask2.png deleted file mode 100644 index 3b8433202..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/mask2.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/mask3.png b/old/src/ImageProcessor.Playground/images/input/mask3.png deleted file mode 100644 index 582348f7b..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/mask3.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/monster.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/monster.png.REMOVED.git-id deleted file mode 100644 index 91c7b556f..000000000 --- a/old/src/ImageProcessor.Playground/images/input/monster.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -21ea506a4ea2691e653b6dc88e47a9876167231a \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/mountain.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/mountain.jpg.REMOVED.git-id deleted file mode 100644 index 5d799dafb..000000000 --- a/old/src/ImageProcessor.Playground/images/input/mountain.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -961e0a9abe5cb414d6a34f6c40f713d88a826910 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/nLpfllv.gif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/nLpfllv.gif.REMOVED.git-id deleted file mode 100644 index c7d3c535a..000000000 --- a/old/src/ImageProcessor.Playground/images/input/nLpfllv.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -15dcc59465ef0163037cddef074d4de3f13fe8d7 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/new-york.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/new-york.jpg.REMOVED.git-id deleted file mode 100644 index ce679dd1d..000000000 --- a/old/src/ImageProcessor.Playground/images/input/new-york.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d04aa90445e483d5614cf597cbd7caa6d55d9aaa \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/night-bridge.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/night-bridge.png.REMOVED.git-id deleted file mode 100644 index 22294d823..000000000 --- a/old/src/ImageProcessor.Playground/images/input/night-bridge.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -414f5a48bd8d020beae85c2dee480cb5d22ec9b7 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/rgba.png b/old/src/ImageProcessor.Playground/images/input/rgba.png deleted file mode 100644 index 429043fa2..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/rgba.png and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/rose_PNG658.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/rose_PNG658.png.REMOVED.git-id deleted file mode 100644 index a0609f374..000000000 --- a/old/src/ImageProcessor.Playground/images/input/rose_PNG658.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -60379fd852541c3f736148862adf54691f39fdee \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/rotate.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/rotate.jpg.REMOVED.git-id deleted file mode 100644 index 7170f80e1..000000000 --- a/old/src/ImageProcessor.Playground/images/input/rotate.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -166cc5e22c4caf8740e5771fe7b52e23637dd7fa \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/sample1.jpg b/old/src/ImageProcessor.Playground/images/input/sample1.jpg deleted file mode 100644 index 909fa4fc5..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/sample1.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/shutterstock_19173982_Arc_de_triomphe-square1.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/shutterstock_19173982_Arc_de_triomphe-square1.jpg.REMOVED.git-id deleted file mode 100644 index 8de5c3abf..000000000 --- a/old/src/ImageProcessor.Playground/images/input/shutterstock_19173982_Arc_de_triomphe-square1.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -a2cccdee0f806b2d41bfcdbb2dc9a1fe3d8656c6 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/test-original.gif.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/test-original.gif.REMOVED.git-id deleted file mode 100644 index 60122bcf6..000000000 --- a/old/src/ImageProcessor.Playground/images/input/test-original.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -782fb5ca5bb57601d2533c090a3c56bc2abd2ae0 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/test.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/test.jpg.REMOVED.git-id deleted file mode 100644 index a144a0d2b..000000000 --- a/old/src/ImageProcessor.Playground/images/input/test.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -99704952050f56a69f591220bb9f0f2014215c7f \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/test.webp b/old/src/ImageProcessor.Playground/images/input/test.webp deleted file mode 100644 index 3e4bca1d8..000000000 Binary files a/old/src/ImageProcessor.Playground/images/input/test.webp and /dev/null differ diff --git a/old/src/ImageProcessor.Playground/images/input/test2.png.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/test2.png.REMOVED.git-id deleted file mode 100644 index a2d067191..000000000 --- a/old/src/ImageProcessor.Playground/images/input/test2.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -64bcd395a5b08c75a48cc21db2668cfb7fe5364e \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/test5.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/test5.jpg.REMOVED.git-id deleted file mode 100644 index 07cea85c0..000000000 --- a/old/src/ImageProcessor.Playground/images/input/test5.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -04f8079eef57529bd63ff1e8227703acbb45aa15 \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/tower.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/tower.jpg.REMOVED.git-id deleted file mode 100644 index d45f646a2..000000000 --- a/old/src/ImageProcessor.Playground/images/input/tower.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -98c3f8fce4fdd9eebafe12431c8e014fd39d243f \ No newline at end of file diff --git a/old/src/ImageProcessor.Playground/images/input/tree.jpg.REMOVED.git-id b/old/src/ImageProcessor.Playground/images/input/tree.jpg.REMOVED.git-id deleted file mode 100644 index 013af9f99..000000000 --- a/old/src/ImageProcessor.Playground/images/input/tree.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -f5e8e6f09d2e518da37e698b6113b82e8f21dcd1 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/AssertionHelpers.cs b/old/src/ImageProcessor.UnitTests/AssertionHelpers.cs deleted file mode 100644 index fe394a543..000000000 --- a/old/src/ImageProcessor.UnitTests/AssertionHelpers.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.UnitTests -{ - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - using System.Linq; - - using FluentAssertions; - - /// - /// Provides helpers for asserting - /// - public class AssertionHelpers - { - /// - /// Asserts that two images are identical - /// - /// - /// The expected result - /// - /// - /// The tested image - /// - /// - /// The because message. - /// - /// - /// The because arguments. - /// - public static void AssertImagesAreIdentical(Image expected, Image tested, string because, params object[] becauseArgs) - { - ToByteArray(expected).SequenceEqual(ToByteArray(tested)).Should().BeTrue(because, becauseArgs); - } - - /// - /// Asserts that two images are different - /// - /// - /// The not-expected result - /// - /// - /// The tested image - /// - /// - /// The because message. - /// - /// - /// The because arguments. - /// - public static void AssertImagesAreDifferent(Image expected, Image tested, string because, params object[] becauseArgs) - { - ToByteArray(expected).SequenceEqual(ToByteArray(tested)).Should().BeFalse(because, becauseArgs); - } - - /// - /// Converts an image to a byte array - /// - /// The image to convert - /// An array of bytes representing the image - public static byte[] ToByteArray(Image imageIn) - { - using (MemoryStream ms = new MemoryStream()) - { - imageIn.Save(ms, ImageFormat.Jpeg); - return ms.ToArray(); - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Configuration/ImageProcessorBootstrapperTests.cs b/old/src/ImageProcessor.UnitTests/Configuration/ImageProcessorBootstrapperTests.cs deleted file mode 100644 index ab7df4e57..000000000 --- a/old/src/ImageProcessor.UnitTests/Configuration/ImageProcessorBootstrapperTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Test harness for the ImageProcessor bootstrapper tests -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.UnitTests.Configuration -{ - using System; - using System.Linq; - - using FluentAssertions; - - using ImageProcessor.Configuration; - - using NUnit.Framework; - - /// - /// Test harness for the ImageProcessor bootstrapper tests - /// - [TestFixture] - public class ImageProcessorBootstrapperTests - { - /// - /// Test to see that the bootstrapper singleton is instantiated. - /// - [Test] - public void BootstrapperSingletonIsInstantiated() - { - ImageProcessorBootstrapper.Instance.SupportedImageFormats.Count().Should().BeGreaterThan(0, "because there should be supported image formats"); - - ImageProcessorBootstrapper.Instance.NativeBinaryFactory.Is64BitEnvironment.Should().Be(Environment.Is64BitProcess); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Extensions/DoubleExtensionsUnitTests.cs b/old/src/ImageProcessor.UnitTests/Extensions/DoubleExtensionsUnitTests.cs deleted file mode 100644 index f4a7d2f88..000000000 --- a/old/src/ImageProcessor.UnitTests/Extensions/DoubleExtensionsUnitTests.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Runs unit tests on the extension methods -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.UnitTests.Extensions -{ - using Common.Extensions; - using NUnit.Framework; - - /// - /// Test harness for the DoubleExtensions extension methods - /// - [TestFixture] - public class DoubleExtensionsUnitTests - { - /// - /// Tests the double to byte conversion - /// - /// Double input - /// Expected result - [Test] - [TestCase(-10, 0)] - [TestCase(1.5, 2)] - [TestCase(25.7, 26)] - [TestCase(1289047, 255)] - public void DoubleIsConvertedToByte(double input, byte expected) - { - byte result = input.ToByte(); - Assert.AreEqual(expected, result); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Extensions/IntegerExtensionsUnitTests.cs b/old/src/ImageProcessor.UnitTests/Extensions/IntegerExtensionsUnitTests.cs deleted file mode 100644 index d8f74f3cb..000000000 --- a/old/src/ImageProcessor.UnitTests/Extensions/IntegerExtensionsUnitTests.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Runs unit tests on the extension methods -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.UnitTests.Extensions -{ - using Common.Extensions; - using NUnit.Framework; - - /// - /// Provides a test harness for the integer extension class - /// - [TestFixture] - public class IntegerExtensionsUnitTests - { - /// - /// Tests the "ToByte" extension - /// - /// Integer input - /// Expected result - [Test] - [TestCase(21, 0x15)] - [TestCase(190, 0xBE)] - [TestCase(3156, 0xFF)] - public void IntegerIsConvertedToByte(int input, byte expected) - { - byte result = input.ToByte(); - Assert.AreEqual(expected, result); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/ImageFactoryUnitTests.cs b/old/src/ImageProcessor.UnitTests/ImageFactoryUnitTests.cs deleted file mode 100644 index ac3f9cdb6..000000000 --- a/old/src/ImageProcessor.UnitTests/ImageFactoryUnitTests.cs +++ /dev/null @@ -1,772 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- -namespace ImageProcessor.UnitTests -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.IO; - using System.Linq; - - using FluentAssertions; - - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Filters.EdgeDetection; - using ImageProcessor.Imaging.Filters.Photo; - - using NUnit.Framework; - - /// - /// Test harness for the image factory - /// - [TestFixture] - public class ImageFactoryUnitTests - { - /// - /// The list of images. Designed to speed up the tests a little. - /// - private IEnumerable imagesInfos; - - /// - /// The list of ImageFactories. Designed to speed up the test a bit more. - /// - private List imagesFactories; - - /// - /// Tests the loading of image from a file - /// - [Test] - public void ImageIsLoadedFromFile() - { - foreach (FileInfo file in this.ListInputFiles()) - { - using (ImageFactory imageFactory = new ImageFactory()) - { - imageFactory.Load(file.FullName); - - imageFactory.ImagePath.Should().Be(file.FullName, "because the path should have been memorized"); - imageFactory.Image.Should().NotBeNull("because the image should have been loaded"); - } - } - } - - /// - /// Tests the loading of image from a memory stream - /// - [Test] - public void ImageIsLoadedFromMemoryStream() - { - foreach (FileInfo file in this.ListInputFiles()) - { - byte[] photoBytes = File.ReadAllBytes(file.FullName); - - using (MemoryStream inStream = new MemoryStream(photoBytes)) - { - using (ImageFactory imageFactory = new ImageFactory()) - { - imageFactory.Load(inStream); - - imageFactory.ImagePath.Should().BeNull("because an image loaded from stream should not have a file path"); - imageFactory.Image.Should().NotBeNull("because the image should have been loaded"); - } - } - } - } - - /// - /// Tests that the save method actually saves a file - /// - [Test] - public void ImageIsSavedToDisk() - { - foreach (FileInfo file in this.ListInputFiles()) - { - string outputFileName = string.Format("./output/{0}", file.Name); - using (ImageFactory imageFactory = new ImageFactory()) - { - imageFactory.Load(file.FullName); - imageFactory.Save(outputFileName); - - File.Exists(outputFileName).Should().BeTrue("because the file should have been saved on disk"); - - File.Delete(outputFileName); - } - } - } - - /// - /// Tests that the save method actually writes to memory - /// - [Test] - public void ImageIsSavedToMemory() - { - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - using (MemoryStream s = new MemoryStream()) - { - imageFactory.Save(s); - s.Seek(0, SeekOrigin.Begin); - - s.Capacity.Should().BeGreaterThan(0, "because the stream should contain the image"); - } - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void AlphaIsModified() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Alpha(50); - AssertionHelpers.AssertImagesAreDifferent( - original, - imageFactory.Image, - "because the alpha operation should have been applied on {0}", - imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/alpha-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that brightness changes is really applied by checking that the image is modified - /// - [Test] - public void BrightnessIsModified() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Brightness(50); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the brightness operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/brightness-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that background color changes are really applied by checking that the image is modified - /// - [Test] - public void BackgroundColorIsChanged() - { - ImageFactory imageFactory = new ImageFactory(); - imageFactory.Load(@"Images\text.png"); - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.BackgroundColor(Color.Yellow); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the background color operation should have been applied on {0}", imageFactory.ImagePath); - } - - /// - /// Tests that a contrast change is really applied by checking that the image is modified - /// - [Test] - public void ContrastIsModified() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Contrast(50); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the contrast operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/contrast-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a saturation change is really applied by checking that the image is modified - /// - [Test] - public void SaturationIsModified() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Saturation(50); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the saturation operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/saturation-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a tint change is really applied by checking that the image is modified - /// - [Test] - public void TintIsModified() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Tint(Color.FromKnownColor(KnownColor.AliceBlue)); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the tint operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/tint-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a vignette change is really applied by checking that the image is modified - /// - [Test] - public void VignetteEffectIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Vignette(Color.FromKnownColor(KnownColor.AliceBlue)); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the vignette operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/vignette-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void WatermarkIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Watermark(new TextLayer - { - FontFamily = new FontFamily("Arial"), - FontSize = 10, - Position = new Point(10, 10), - Text = "Lorem ipsum dolor" - }); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the watermark operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/watermark-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void BlurEffectIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.GaussianBlur(5); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the blur operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/blur-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void BlurWithLayerIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.GaussianBlur(new GaussianLayer { Sigma = 10, Size = 5, Threshold = 2 }); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the layered blur operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/blurlayer-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void SharpenEffectIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.GaussianSharpen(5); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the sharpen operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/sharpen-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void SharpenWithLayerIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.GaussianSharpen(new GaussianLayer { Sigma = 10, Size = 5, Threshold = 2 }); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the layered sharpen operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/sharpenlayer-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that all filters can be applied - /// - [Test] - public void FilterIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - - List filters = new List - { - MatrixFilters.BlackWhite, - MatrixFilters.Comic, - MatrixFilters.Gotham, - MatrixFilters.GreyScale, - MatrixFilters.HiSatch, - MatrixFilters.Invert, - MatrixFilters.Lomograph, - MatrixFilters.LoSatch, - MatrixFilters.Polaroid, - MatrixFilters.Sepia - }; - - int j = 0; - foreach (IMatrixFilter filter in filters) - { - imageFactory.Filter(filter); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the filter operation should have been applied on {0}", imageFactory.ImagePath); - imageFactory.Reset(); - AssertionHelpers.AssertImagesAreIdentical(original, imageFactory.Image, "because the image should be reset"); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/filter-" + j++.ToString() + "-image-" + i.ToString() + ".jpg"); - } - - i++; - } - } - - /// - /// Tests that a filter is really applied by checking that the image is modified - /// - [Test] - public void RoundedCornersAreApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.RoundedCorners(new RoundedCornerLayer(5)); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the rounded corners operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/roundedcorners-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is well resized using constraints - /// - [Test] - public void ImageIsResizedWithinConstraints() - { - int i = 0; - const int MaxSize = 200; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - imageFactory.Constrain(new Size(MaxSize, MaxSize)); - imageFactory.Image.Width.Should().BeLessOrEqualTo(MaxSize, "because the image size should have been reduced"); - imageFactory.Image.Height.Should().BeLessOrEqualTo(MaxSize, "because the image size should have been reduced"); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/resizedcontraints-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is well cropped - /// - [Test] - public void ImageIsCropped() - { - int i = 0; - const int MaxSize = 20; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Crop(new Rectangle(0, 0, MaxSize, MaxSize)); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the crop operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Image.Width.Should().Be(MaxSize, "because the cropped image should be {0}x{0}", MaxSize); - imageFactory.Image.Height.Should().Be(MaxSize, "because the cropped image should be {0}x{0}", MaxSize); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/crop-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is well cropped - /// - [Test] - public void ImageIsCroppedWithLayer() - { - int i = 0; - const int MaxSize = 20; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Crop(new CropLayer(0, 0, MaxSize, MaxSize, CropMode.Pixels)); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the layered crop operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Image.Width.Should().Be(MaxSize, "because the cropped image should be {0}x{0}", MaxSize); - imageFactory.Image.Height.Should().Be(MaxSize, "because the cropped image should be {0}x{0}", MaxSize); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/croplayer-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is flipped - /// - [Test] - public void ImageIsFlipped() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Flip(true); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the vertical flip operation should have been applied on {0}", imageFactory.ImagePath); - imageFactory.Image.Width.Should().Be(original.Width, "because the dimensions should not have changed"); - imageFactory.Image.Height.Should().Be(original.Height, "because the dimensions should not have changed"); - imageFactory.Reset(); - AssertionHelpers.AssertImagesAreIdentical(original, imageFactory.Image, "because the image should be reset"); - - imageFactory.Flip(); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the horizontal flip operation should have been applied on {0}", imageFactory.ImagePath); - imageFactory.Image.Width.Should().Be(original.Width, "because the dimensions should not have changed"); - imageFactory.Image.Height.Should().Be(original.Height, "because the dimensions should not have changed"); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/flip-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is resized - /// - [Test] - public void ImageIsResized() - { - int i = 0; - const int NewSize = 150; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - imageFactory.Resize(new Size(NewSize, NewSize)); - - imageFactory.Image.Width.Should().Be(NewSize, "because the new image's size should be {0}x{0}", NewSize); - imageFactory.Image.Height.Should().Be(NewSize, "because the new image's size should be {0}x{0}", NewSize); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/resized-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is resized - /// - [Test] - public void ImageIsResizedWithLayer() - { - int i = 0; - const int NewSize = 150; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - imageFactory.Resize(new ResizeLayer(new Size(NewSize, NewSize), ResizeMode.Stretch, AnchorPosition.Left)); - - imageFactory.Image.Width.Should().Be(NewSize, "because the new image's size should be {0}x{0}", NewSize); - imageFactory.Image.Height.Should().Be(NewSize, "because the new image's size should be {0}x{0}", NewSize); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/resizedlayer-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image is resized - /// - [Test] - public void ImageIsRotated() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Rotate(90); - - imageFactory.Image.Width.Should().Be(original.Height, "because the rotated image dimensions should have been switched"); - imageFactory.Image.Height.Should().Be(original.Width, "because the rotated image dimensions should have been switched"); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/rotated-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image's inside is rotated - /// - [Test] - public void ImageIsRotatedInside() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.RotateBounded(45, true); - - imageFactory.Image.Width.Should().Be(original.Width, "because the rotated image dimensions should not have changed"); - imageFactory.Image.Height.Should().Be(original.Height, "because the rotated image dimensions should not have changed"); - - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the inside image should have been rotated on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/rotatebounded-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image's inside is rotated counter-clockwise - /// - [Test] - public void ImageIsRotatedInsideCounterClockwise() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.RotateBounded(-45, true); - - imageFactory.Image.Width.Should().Be(original.Width, "because the rotated image dimensions should not have changed"); - imageFactory.Image.Height.Should().Be(original.Height, "because the rotated image dimensions should not have changed"); - - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the inside image should have been rotated on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/rotateboundedccw-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image's inside is rotated and resized - /// - [Test] - public void ImageIsRotatedInsideAndResized() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.RotateBounded(45); - - imageFactory.Image.Width.Should().NotBe(original.Width, "because the rotated image dimensions should have changed"); - imageFactory.Image.Height.Should().NotBe(original.Height, "because the rotated image dimensions should have changed"); - - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the inside image should have been rotated on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/rotateboundedresized-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the images hue has been altered. - /// - [Test] - public void HueIsModified() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Hue(90); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the hue operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Reset(); - AssertionHelpers.AssertImagesAreIdentical(original, imageFactory.Image, "because the image should be reset"); - - imageFactory.Hue(116, true); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the hue+rotate operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/hue-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the image has been pixelated. - /// - [Test] - public void PixelateEffectIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.Pixelate(8); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the pixelate operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/pixelate-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the images quality has been set. - /// - [Test] - public void ImageQualityIsModified() - { - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - int original = imageFactory.CurrentImageFormat.Quality; - imageFactory.Quality(69); - int updated = imageFactory.CurrentImageFormat.Quality; - - updated.Should().NotBe(original, "because the quality should have been changed"); - } - } - - /// - /// Tests that the image has had a color replaced. - /// - [Test] - public void ColorIsReplaced() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - imageFactory.ReplaceColor(Color.White, Color.Black, 90); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the color replace operation should have been applied on {0}", imageFactory.ImagePath); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/colorreplace-" + i++.ToString() + ".jpg"); - } - } - - /// - /// Tests that the various edge detection algorithms are applied. - /// - [Test] - public void EdgeDetectionEffectIsApplied() - { - int i = 0; - foreach (ImageFactory imageFactory in this.ListInputImages()) - { - Image original = (Image)imageFactory.Image.Clone(); - - List filters = new List - { - new KayyaliEdgeFilter(), - new KirschEdgeFilter(), - new Laplacian3X3EdgeFilter(), - new Laplacian5X5EdgeFilter(), - new LaplacianOfGaussianEdgeFilter(), - new PrewittEdgeFilter(), - new RobertsCrossEdgeFilter(), - new ScharrEdgeFilter(), - new SobelEdgeFilter() - }; - - int j = 0; - foreach (IEdgeFilter filter in filters) - { - imageFactory.DetectEdges(filter); - AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the edge operation should have been applied on {0}", imageFactory.ImagePath); - imageFactory.Reset(); - AssertionHelpers.AssertImagesAreIdentical(original, imageFactory.Image, "because the image should be reset"); - - imageFactory.Format(new ImageProcessor.Imaging.Formats.JpegFormat()).Save("./output/edgefilter-" + j++.ToString() + "-image-" + i.ToString() + ".jpg"); - } - - i++; - } - } - - /// - /// Gets the files matching the given extensions. - /// - /// - /// The . - /// - /// - /// The extensions. - /// - /// - /// A collection of - /// - /// - /// The extensions variable is null. - /// - private static IEnumerable GetFilesByExtensions(DirectoryInfo dir, params string[] extensions) - { - if (extensions == null) - { - throw new ArgumentNullException("extensions"); - } - - IEnumerable files = dir.EnumerateFiles(); - return files.Where(f => extensions.Contains(f.Extension, StringComparer.OrdinalIgnoreCase)); - } - - /// - /// Lists the input files in the Images folder - /// - /// The list of files. - private IEnumerable ListInputFiles() - { - if (this.imagesInfos != null) - { - return this.imagesInfos; - } - - DirectoryInfo directoryInfo = new DirectoryInfo("./Images"); - - this.imagesInfos = GetFilesByExtensions(directoryInfo, new[] { ".jpg", ".jpeg", ".png", ".gif", ".tiff", ".bmp", ".webp" }); - - return this.imagesInfos; - } - - /// - /// Lists the input images to use from the Images folder - /// - /// The list of images - private IEnumerable ListInputImages() - { - if (this.imagesFactories == null || !this.imagesFactories.Any()) - { - this.imagesFactories = new List(); - foreach (FileInfo fi in this.ListInputFiles()) - { - this.imagesFactories.Add((new ImageFactory()).Load(fi.FullName)); - } - } - - // reset all the images whenever we call this - foreach (ImageFactory image in this.imagesFactories) - { - image.Reset(); - } - - return this.imagesFactories; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/ImageProcessor.UnitTests.csproj b/old/src/ImageProcessor.UnitTests/ImageProcessor.UnitTests.csproj deleted file mode 100644 index b01589d57..000000000 --- a/old/src/ImageProcessor.UnitTests/ImageProcessor.UnitTests.csproj +++ /dev/null @@ -1,156 +0,0 @@ - - - - Debug - AnyCPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C} - Library - ImageProcessor.UnitTests - ImageProcessor.UnitTests - Client - ..\ - true - - - ..\ - true - v4.5 - - - true - full - false - bin\Debug - DEBUG; - prompt - 4 - false - false - - - full - true - bin\Release - prompt - 4 - false - false - - - - False - ..\packages\FluentAssertions.3.3.0\lib\net45\FluentAssertions.dll - - - False - ..\packages\FluentAssertions.3.3.0\lib\net45\FluentAssertions.Core.dll - - - - - ..\packages\NUnit.2.6.3\lib\nunit.framework.dll - - - - - - - - - - - PreserveNewest - - - - - - - - - - - - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E} - ImageProcessor - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/color-modes/cmyk.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/color-modes/cmyk.jpg.REMOVED.git-id deleted file mode 100644 index 9ba0b9f39..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/color-modes/cmyk.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9160894da31fedebb1fcd64eb57ca173187c63a6 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/color-modes/srgb.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/color-modes/srgb.jpg.REMOVED.git-id deleted file mode 100644 index e8e54439b..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/color-modes/srgb.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9a2d827e3629449426fdbc53725ab2d30c684c21 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/color-modes/srgb.png.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/color-modes/srgb.png.REMOVED.git-id deleted file mode 100644 index d86ab294d..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/color-modes/srgb.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -7c92aa5bc23660a76c8dca5c88b0c376ced36a29 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-color.png b/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-color.png deleted file mode 100644 index 2ac0f7629..000000000 Binary files a/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-color.png and /dev/null differ diff --git a/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-contrast.jpg b/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-contrast.jpg deleted file mode 100644 index a425cbc9e..000000000 Binary files a/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-contrast.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-saturation.jpg b/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-saturation.jpg deleted file mode 100644 index e4c58f3ed..000000000 Binary files a/old/src/ImageProcessor.UnitTests/Images/color-tests/hi-saturation.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.UnitTests/Images/exif/autorotate.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/exif/autorotate.jpg.REMOVED.git-id deleted file mode 100644 index 1b5e335ff..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/exif/autorotate.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -75b37593bb2e505bf4fbe874eaf30debd6161c2e \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/exif/exif-Tulips.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/exif/exif-Tulips.jpg.REMOVED.git-id deleted file mode 100644 index 20704f4a9..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/exif/exif-Tulips.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9d7e7964a2285363171929315b15ec69f14831ef \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/exif/exif-rocks.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/exif/exif-rocks.jpg.REMOVED.git-id deleted file mode 100644 index 2e03e238f..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/exif/exif-rocks.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -be31c9c0dea90586e2965208611fad024f6a5b08 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-Penguins-8bit.png.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-Penguins-8bit.png.REMOVED.git-id deleted file mode 100644 index c48cdc177..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-Penguins-8bit.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -51ccec74a0351599de104f166b32d2860acaf089 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.bmp.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-Penguins.bmp.REMOVED.git-id deleted file mode 100644 index 9ba53bc67..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.bmp.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d7adbea2db4e3388541e31a229e5741677aaa7fd \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.gif.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-Penguins.gif.REMOVED.git-id deleted file mode 100644 index 225d59af3..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b301e58d431a78d3f17be53be1cdc94c86286389 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-Penguins.jpg.REMOVED.git-id deleted file mode 100644 index 06482dbd9..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -ee5a15e7f8fc2655d5c1fc736a05857ab3d885bd \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.png.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-Penguins.png.REMOVED.git-id deleted file mode 100644 index 4ab6b372b..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b6434b5a35e989d4fa71ede1a8316fedeee7ae5f \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.tif.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-Penguins.tif.REMOVED.git-id deleted file mode 100644 index 5f7b97e71..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-Penguins.tif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c789aaec248568c24394b05c02db4233e0c5a4eb \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/format-animated.gif.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/format-animated.gif.REMOVED.git-id deleted file mode 100644 index ac3664d5f..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/format-animated.gif.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -a41fb1117e1d730a4a488dcb67e0b867aa3c614e \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/icc-profiles/cmyk-profile-euroscale.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/icc-profiles/cmyk-profile-euroscale.jpg.REMOVED.git-id deleted file mode 100644 index 11eb19931..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/icc-profiles/cmyk-profile-euroscale.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -d0a1a39a6729e826098ae5e987c22c34c989b7e3 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/icc-profiles/profile-adobe-rgb.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/icc-profiles/profile-adobe-rgb.jpg.REMOVED.git-id deleted file mode 100644 index 8064ffb21..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/icc-profiles/profile-adobe-rgb.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -189f79f9b9604c5413aba928662d84edd426142d \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/icc-profiles/profile-srgb.jpg.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/icc-profiles/profile-srgb.jpg.REMOVED.git-id deleted file mode 100644 index 101151778..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/icc-profiles/profile-srgb.jpg.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -f731bdf700d2718f528317263264e5466374c5e5 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/imageprocessor/mask/mask.png b/old/src/ImageProcessor.UnitTests/Images/imageprocessor/mask/mask.png deleted file mode 100644 index f86272dc3..000000000 Binary files a/old/src/ImageProcessor.UnitTests/Images/imageprocessor/mask/mask.png and /dev/null differ diff --git a/old/src/ImageProcessor.UnitTests/Images/imageprocessor/overlay/monster.png.REMOVED.git-id b/old/src/ImageProcessor.UnitTests/Images/imageprocessor/overlay/monster.png.REMOVED.git-id deleted file mode 100644 index c13b65e9e..000000000 --- a/old/src/ImageProcessor.UnitTests/Images/imageprocessor/overlay/monster.png.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -4edf74a6857665c8efe2d3282c25907f5b20ca81 \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Images/stretched.jpg b/old/src/ImageProcessor.UnitTests/Images/stretched.jpg deleted file mode 100644 index 891b9f690..000000000 Binary files a/old/src/ImageProcessor.UnitTests/Images/stretched.jpg and /dev/null differ diff --git a/old/src/ImageProcessor.UnitTests/Images/text.png b/old/src/ImageProcessor.UnitTests/Images/text.png deleted file mode 100644 index 44bfdd6c6..000000000 Binary files a/old/src/ImageProcessor.UnitTests/Images/text.png and /dev/null differ diff --git a/old/src/ImageProcessor.UnitTests/Imaging/ColorUnitTests.cs b/old/src/ImageProcessor.UnitTests/Imaging/ColorUnitTests.cs deleted file mode 100644 index 9370142a8..000000000 --- a/old/src/ImageProcessor.UnitTests/Imaging/ColorUnitTests.cs +++ /dev/null @@ -1,200 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Test harness for the color classes. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.UnitTests.Imaging -{ - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Drawing; - - using FluentAssertions; - - using ImageProcessor.Imaging.Colors; - - using NUnit.Framework; - - /// - /// Test harness for the color classes. - /// - [TestFixture] - public class ColorUnitTests - { - /// - /// Tests the struct equality operators. - /// - [Test] - public void RgbaColorImplementsEquals() - { - RgbaColor first = RgbaColor.FromColor(Color.White); - RgbaColor second = RgbaColor.FromColor(Color.White); - - first.Equals(second).Should().BeTrue("because the color structure should implement Equals()"); - } - - /// - /// Tests the struct equality operators. - /// - [Test] - public void HslaColorImplementsEquals() - { - HslaColor first = HslaColor.FromColor(Color.White); - HslaColor second = HslaColor.FromColor(Color.White); - - first.Equals(second).Should().BeTrue("because the color structure should implement Equals()"); - } - - /// - /// Tests the struct equality operators. - /// - [Test] - public void YCbCrColorImplementsEquals() - { - YCbCrColor first = YCbCrColor.FromColor(Color.White); - YCbCrColor second = YCbCrColor.FromColor(Color.White); - - first.Equals(second).Should().BeTrue("because the color structure should implement Equals()"); - } - - /// - /// Tests the struct equality operators. - /// - [Test] - public void CmykColorImplementsEquals() - { - CmykColor first = CmykColor.FromColor(Color.White); - CmykColor second = CmykColor.FromColor(Color.White); - - first.Equals(second).Should().BeTrue("because the color structure should implement Equals()"); - } - - /// - /// Test conversion to and from a . - /// - /// - /// The expected output. - /// - [Test] - [TestCase("#FFFFFF")] - [TestCase("#FEFFFE")] - [TestCase("#F0F8FF")] - [TestCase("#000000")] - [TestCase("#CCFF33")] - [TestCase("#00FF00")] - [TestCase("#FF00FF")] - [TestCase("#990000")] - [TestCase("#5C955C")] - [TestCase("#5C5C95")] - [TestCase("#3F3F66")] - [TestCase("#FFFFBB")] - [TestCase("#FF002B")] - [TestCase("#00ABFF")] - public void HslaColorShouldConvertToAndFromString(string expected) - { - Color color = ColorTranslator.FromHtml(expected); - HslaColor hslaColor = HslaColor.FromColor(color); - string result = ColorTranslator.ToHtml(hslaColor); - - result.Should().Be(expected); - } - - /// - /// Test conversion to and from a . - /// - /// - /// The expected output. - /// - [Test] - [TestCase("#FFFFFF")] - [TestCase("#FEFFFE")] - [TestCase("#F0F8FF")] - [TestCase("#000000")] - [TestCase("#CCFF33")] - [TestCase("#00FF00")] - [TestCase("#FF00FF")] - [TestCase("#990000")] - [TestCase("#5C955C")] - [TestCase("#5C5C95")] - [TestCase("#3F3F66")] - [TestCase("#FFFFBB")] - [TestCase("#FF002B")] - [TestCase("#00ABFF")] - public void CmykColorShouldConvertToAndFromString(string expected) - { - Color color = ColorTranslator.FromHtml(expected); - CmykColor cmykColor = CmykColor.FromColor(color); - - Debug.Print(cmykColor.ToString()); - - string result = ColorTranslator.ToHtml(cmykColor); - - result.Should().Be(expected); - } - - /// - /// Test conversion to and from a . - /// - /// - /// The expected output. - /// - [Test] - [TestCase("#FFFFFF")] - [TestCase("#FEFFFE")] - [TestCase("#F0F8FF")] - [TestCase("#000000")] - [TestCase("#CCFF33")] - [TestCase("#00FF00")] - [TestCase("#FF00FF")] - [TestCase("#990000")] - [TestCase("#5C955C")] - [TestCase("#5C5C95")] - [TestCase("#3F3F66")] - [TestCase("#FFFFBB")] - [TestCase("#FF002B")] - [TestCase("#00ABFF")] - public void RgbaColorShouldConvertToAndFromString(string expected) - { - Color color = ColorTranslator.FromHtml(expected); - RgbaColor rgbaColor = RgbaColor.FromColor(color); - string result = ColorTranslator.ToHtml(rgbaColor); - - result.Should().Be(expected); - } - - /// - /// Test conversion to and from a . - /// - /// - /// The expected output. - /// - [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed. Suppression is OK here."), Test] - [TestCase("#FFFFFF")] - [TestCase("#FEFFFE")] - [TestCase("#F0F8FF")] - [TestCase("#000000")] - [TestCase("#CCFF33")] - [TestCase("#00FF00")] - [TestCase("#FF00FF")] - [TestCase("#990000")] - [TestCase("#5C955C")] - [TestCase("#5C5C95")] - [TestCase("#3F3F66")] - [TestCase("#FFFFBB")] - [TestCase("#FF002B")] - [TestCase("#00ABFF")] - public void YCbCrColorShouldConvertToAndFromString(string expected) - { - Color color = ColorTranslator.FromHtml(expected); - YCbCrColor yCbCrColor = YCbCrColor.FromColor(color); - string result = ColorTranslator.ToHtml(yCbCrColor); - - result.Should().Be(expected); - } - } -} diff --git a/old/src/ImageProcessor.UnitTests/Imaging/CropLayerUnitTests.cs b/old/src/ImageProcessor.UnitTests/Imaging/CropLayerUnitTests.cs deleted file mode 100644 index f1db63d01..000000000 --- a/old/src/ImageProcessor.UnitTests/Imaging/CropLayerUnitTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- -namespace ImageProcessor.UnitTests.Imaging -{ - using ImageProcessor.Imaging; - using FluentAssertions; - using NUnit.Framework; - - /// - /// Test harness for the class - /// - [TestFixture] - public class CropLayerUnitTests - { - /// - /// Tests that the constructor saves the provided data - /// - /// - /// The left position. - /// - /// - /// The top position. - /// - /// - /// The right position. - /// - /// - /// The bottom position. - /// - /// - /// The . - /// - [Test] - [TestCase(10.5F, 11.2F, 15.6F, 108.9F, CropMode.Percentage)] - [TestCase(15.1F, 20.7F, 65.8F, 156.7F, CropMode.Pixels)] - public void ConstructorSavesData(float left, float top, float right, float bottom, CropMode mode) - { - CropLayer cl = new CropLayer(left, top, right, bottom, mode); - - cl.Left.Should().Be(left); - cl.Top.Should().Be(top); - cl.Right.Should().Be(right); - cl.Bottom.Should().Be(bottom); - cl.CropMode.Should().Be(mode); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Imaging/FastBitmapUnitTests.cs b/old/src/ImageProcessor.UnitTests/Imaging/FastBitmapUnitTests.cs deleted file mode 100644 index 13c51a80b..000000000 --- a/old/src/ImageProcessor.UnitTests/Imaging/FastBitmapUnitTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- -namespace ImageProcessor.UnitTests.Imaging -{ - using System.Drawing; - using FluentAssertions; - using ImageProcessor.Imaging; - using NUnit.Framework; - - /// - /// Test harness for the class - /// - [TestFixture] - public class FastBitmapUnitTests - { - /// - /// Tests that the bitmap's data is read by the fast bitmap - /// - /// The path to the test file - [Test] - [TestCase(@"Images\format-Penguins.jpg")] - [TestCase(@"Images\format-Penguins.png")] - public void BitmapIsRead(string file) - { - Bitmap bmp = new Bitmap(file); - - using (FastBitmap fbmp = new FastBitmap(bmp)) - { - fbmp.Width.Should().Be(bmp.Width, "because the bitmap should have been read"); - fbmp.Height.Should().Be(bmp.Height, "because the bitmap should have been read"); - } - } - - /// - /// Tests that modifications on the fast bitmap's bitmap are actually done - /// - /// The path to the test file - [Test] - [TestCase(@"Images\format-Penguins.jpg")] - [TestCase(@"Images\format-Penguins.png")] - public void FastBitmapModificationsAreApplied(string file) - { - Bitmap bmp = new Bitmap(file); - Bitmap original = (Bitmap)bmp.Clone(); - - using (FastBitmap fbmp = new FastBitmap(bmp)) - { - // draw a pink diagonal line - for (int i = 0; i < 10; i++) - { - fbmp.SetPixel(i, i, Color.Pink); - } - } - - AssertionHelpers.AssertImagesAreDifferent(original, bmp, "because modifying the fast bitmap should have modified the original bitmap"); - } - } -} diff --git a/old/src/ImageProcessor.UnitTests/Imaging/Helpers/ImageMathsUnitTests.cs b/old/src/ImageProcessor.UnitTests/Imaging/Helpers/ImageMathsUnitTests.cs deleted file mode 100644 index 18e592ede..000000000 --- a/old/src/ImageProcessor.UnitTests/Imaging/Helpers/ImageMathsUnitTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Test harness for the image math unit tests -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.UnitTests.Imaging.Helpers -{ - using System.Drawing; - using FluentAssertions; - using ImageProcessor.Imaging.Helpers; - using NUnit.Framework; - - /// - /// Test harness for the image math unit tests - /// - public class ImageMathsUnitTests - { - /// - /// Tests that the bounding rectangle of a rotated image is calculated - /// - /// The width of the image. - /// The height of the image. - /// The rotation angle. - /// The expected width. - /// The expected height. - [Test] - [TestCase(100, 100, 45, 141, 141)] - [TestCase(100, 100, 30, 137, 137)] - [TestCase(100, 200, 50, 217, 205)] - [TestCase(100, 200, -50, 217, 205)] - public void BoundingRotatedRectangleIsCalculated(int width, int height, float angle, int expectedWidth, int expectedHeight) - { - Rectangle result = ImageMaths.GetBoundingRotatedRectangle(width, height, angle); - - result.Width.Should().Be(expectedWidth, "because the rotated width should have been calculated"); - result.Height.Should().Be(expectedHeight, "because the rotated height should have been calculated"); - } - - /// - /// Tests that the zoom needed for an "inside" rotation is calculated - /// - /// Width of the image. - /// Height of the image. - /// The rotation angle. - /// The expected zoom. - [Test] - [TestCase(100, 100, 45, 1.41f)] - [TestCase(100, 100, 15, 1.22f)] - [TestCase(100, 200, 45, 2.12f)] - [TestCase(200, 100, 45, 2.12f)] - [TestCase(600, 450, 20, 1.39f)] - [TestCase(600, 450, 45, 1.64f)] - [TestCase(100, 200, -45, 2.12f)] - public void RotationZoomIsCalculated(int imageWidth, int imageHeight, float angle, float expected) - { - float result = ImageMaths.ZoomAfterRotation(imageWidth, imageHeight, angle); - - result.Should().BeApproximately(expected, 0.01f, "because the zoom level after rotation should have been calculated"); - - result.Should().BePositive("because we're always zooming in so the zoom level should always be positive"); - - result.Should().BeGreaterOrEqualTo(1, "because the zoom should always increase the size and not reduce it"); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.UnitTests/Properties/AssemblyInfo.cs b/old/src/ImageProcessor.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index fb042a1d3..000000000 --- a/old/src/ImageProcessor.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.UnitTests2")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ImageProcessor.UnitTests2")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("3003f5a6-eb11-4eee-bfaa-448deb3a31d9")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/old/src/ImageProcessor.UnitTests/packages.config b/old/src/ImageProcessor.UnitTests/packages.config deleted file mode 100644 index 8c46e4859..000000000 --- a/old/src/ImageProcessor.UnitTests/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/ApplicationEvents.cs b/old/src/ImageProcessor.Web.PostProcessor/ApplicationEvents.cs deleted file mode 100644 index f272fb32a..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/ApplicationEvents.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Binds the PostProcessor to process any image requests within the web application. -// Many thanks to Azure Image Optimizer -// -// -------------------------------------------------------------------------------------------------------------------- - -using System.Web; - -[assembly: PreApplicationStartMethod(typeof(ImageProcessor.Web.PostProcessor.ApplicationEvents), "Start")] - -namespace ImageProcessor.Web.PostProcessor -{ - using ImageProcessor.Web.Helpers; - using ImageProcessor.Web.HttpModules; - - /// - /// Binds the PostProcessor to process any image requests within the web application. - /// Many thanks to Azure Image Optimizer - /// - public static class ApplicationEvents - { - /// - /// The initial startup method. - /// - public static void Start() - { - ImageProcessingModule.OnPostProcessing += PostProcessAsync; - } - - /// - /// Asynchronously post-processes cached images. - /// - /// - /// The source of the event. - /// - /// - /// An EventArgs that contains the event data. - /// - private static async void PostProcessAsync(object sender, PostProcessingEventArgs e) - { - await PostProcessor.PostProcessImageAsync(e.CachedImagePath); - } - } -} diff --git a/old/src/ImageProcessor.Web.PostProcessor/ImageProcessor.Web.PostProcessor.csproj b/old/src/ImageProcessor.Web.PostProcessor/ImageProcessor.Web.PostProcessor.csproj deleted file mode 100644 index fcfad149a..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/ImageProcessor.Web.PostProcessor.csproj +++ /dev/null @@ -1,78 +0,0 @@ - - - - - Debug - AnyCPU - {55D08737-7D7E-4995-8892-BD9F944329E6} - Library - Properties - ImageProcessor.Web.PostProcessor - ImageProcessor.Web.PostProcessor - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - {D011A778-59C8-4BFA-A770-C350216BF161} - ImageProcessor.Web - - - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E} - ImageProcessor - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/PostProcessingResultEventArgs.cs b/old/src/ImageProcessor.Web.PostProcessor/PostProcessingResultEventArgs.cs deleted file mode 100644 index 6f58686f6..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/PostProcessingResultEventArgs.cs +++ /dev/null @@ -1,103 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The post processing result event arguments. -// Many thanks to Azure Image Optimizer -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.PostProcessor -{ - using System; - using System.IO; - using System.Text; - - /// - /// The post processing result event arguments. - /// Many thanks to Azure Image Optimizer - /// - public class PostProcessingResultEventArgs : EventArgs - { - /// - /// Initializes a new instance of the class. - /// - /// The original file name. - /// The result file name. - public PostProcessingResultEventArgs(string originalFileName, string resultFileName) - { - FileInfo original = new FileInfo(originalFileName); - FileInfo result = new FileInfo(resultFileName); - - if (original.Exists) - { - this.OriginalFileName = original.FullName; - this.OriginalFileSize = original.Length; - } - - if (result.Exists) - { - this.ResultFileName = result.FullName; - this.ResultFileSize = result.Length; - } - } - - /// - /// Gets or sets the original file size in bytes. - /// - public long OriginalFileSize { get; set; } - - /// - /// Gets or sets the original file name. - /// - public string OriginalFileName { get; set; } - - /// - /// Gets or sets the result file size in bytes. - /// - public long ResultFileSize { get; set; } - - /// - /// Gets or sets the result file name. - /// - public string ResultFileName { get; set; } - - /// - /// Gets the difference in file size in bytes. - /// - public long Saving - { - get { return this.OriginalFileSize - this.ResultFileSize; } - } - - /// - /// Gets the difference in file size as a percentage. - /// - public double Percent - { - get - { - return Math.Round(100 - ((this.ResultFileSize / (double)this.OriginalFileSize) * 100), 1); - } - } - - /// - /// Returns a string that represents the current object. - /// - /// - /// A string that represents the current object. - /// - public override string ToString() - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("Optimized " + Path.GetFileName(this.OriginalFileName)); - stringBuilder.AppendLine("Before: " + this.OriginalFileSize + " bytes"); - stringBuilder.AppendLine("After: " + this.ResultFileSize + " bytes"); - stringBuilder.AppendLine("Saving: " + this.Saving + " bytes / " + this.Percent + "%"); - - return stringBuilder.ToString(); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/PostProcessor.cs b/old/src/ImageProcessor.Web.PostProcessor/PostProcessor.cs deleted file mode 100644 index 4144aea5b..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/PostProcessor.cs +++ /dev/null @@ -1,150 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The image postprocessor. -// Many thanks to Azure Image Optimizer -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.PostProcessor -{ - using System; - using System.Diagnostics; - using System.Globalization; - using System.IO; - using System.Threading.Tasks; - - /// - /// The image postprocessor. - /// Many thanks to Azure Image Optimizer - /// - internal static class PostProcessor - { - /// - /// Post processes the image asynchronously. - /// - /// - /// The source file. - /// - /// - /// The . - /// - public static async Task PostProcessImageAsync(string sourceFile) - { - if (!new Uri(sourceFile).IsFile) - { - return; - } - - string targetFile = Path.GetTempFileName(); - PostProcessingResultEventArgs result = await RunProcess(sourceFile, targetFile); - - if (result != null && result.Saving > 0 && result.ResultFileSize > 0) - { - File.Copy(result.ResultFileName, result.OriginalFileName, true); - File.Delete(result.ResultFileName); - } - else - { - File.Delete(targetFile); - } - } - - /// - /// Runs the process to optimize the images. - /// - /// - /// The source file. - /// - /// - /// The target file. - /// - /// - /// The containing post-processing information. - /// - private static Task RunProcess(string sourceFile, string targetFile) - { - TaskCompletionSource tcs = new TaskCompletionSource(); - ProcessStartInfo start = new ProcessStartInfo("cmd") - { - WindowStyle = ProcessWindowStyle.Hidden, - WorkingDirectory = PostProcessorBootstrapper.WorkingPath, - Arguments = GetArguments(sourceFile, targetFile), - UseShellExecute = false, - CreateNoWindow = true, - }; - - if (string.IsNullOrWhiteSpace(start.Arguments)) - { - tcs.SetResult(null); - return tcs.Task; - } - - Process process = new Process - { - StartInfo = start, - EnableRaisingEvents = true - }; - - process.Exited += (sender, args) => - { - tcs.SetResult(new PostProcessingResultEventArgs(sourceFile, targetFile)); - process.Dispose(); - }; - - process.Start(); - - return tcs.Task; - } - - /// - /// Gets the correct arguments to pass to the post-processor. - /// - /// - /// The source file. - /// - /// - /// The target file. - /// - /// - /// The containing the correct command arguments. - /// - private static string GetArguments(string sourceFile, string targetFile) - { - if (!Uri.IsWellFormedUriString(sourceFile, UriKind.RelativeOrAbsolute) && !File.Exists(sourceFile)) - { - return null; - } - - string ext; - - string extension = Path.GetExtension(sourceFile); - if (extension != null) - { - ext = extension.ToLowerInvariant(); - } - else - { - return null; - } - - switch (ext) - { - case ".png": - return string.Format(CultureInfo.CurrentCulture, "/c png.cmd \"{0}\" \"{1}\"", sourceFile, targetFile); - - case ".jpg": - case ".jpeg": - return string.Format(CultureInfo.CurrentCulture, "/c jpegtran -copy all -optimize -progressive \"{0}\" \"{1}\"", sourceFile, targetFile); - - case ".gif": - return string.Format(CultureInfo.CurrentCulture, "/c gifsicle --crop-transparency --no-comments --no-extensions --no-names --optimize=3 --batch \"{0}\" --output=\"{1}\"", sourceFile, targetFile); - } - - return null; - } - } -} diff --git a/old/src/ImageProcessor.Web.PostProcessor/PostProcessorBootstrapper.cs b/old/src/ImageProcessor.Web.PostProcessor/PostProcessorBootstrapper.cs deleted file mode 100644 index 86e6bfc3b..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/PostProcessorBootstrapper.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The postprocessor bootstrapper. -// Many thanks to Azure Image Optimizer -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.PostProcessor -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Reflection; - - using ImageProcessor.Configuration; - - /// - /// The postprocessor bootstrapper. - /// Many thanks to Azure Image Optimizer - /// - internal static class PostProcessorBootstrapper - { - /// - /// Initializes static members of the class. - /// - static PostProcessorBootstrapper() - { - RegisterExecutables(); - } - - /// - /// Gets the working directory path. - /// - public static string WorkingPath { get; private set; } - - /// - /// Registers the embedded executables. - /// - public static void RegisterExecutables() - { - // None of the tools used here are called using dllimport so we don't go through the normal registration channel. - string folder = ImageProcessorBootstrapper.Instance.NativeBinaryFactory.Is64BitEnvironment ? "x64" : "x86"; - Assembly assembly = Assembly.GetExecutingAssembly(); - WorkingPath = Path.GetFullPath(Path.Combine(new Uri(assembly.Location).LocalPath, "..\\imageprocessor.postprocessor\\")); - - // Create the folder for storing temporary images. - // ReSharper disable once AssignNullToNotNullAttribute - DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(WorkingPath)); - if (!directoryInfo.Exists) - { - directoryInfo.Create(); - } - - // Get the resources and copy them across. - Dictionary resources = new Dictionary - { - { "gifsicle.exe", "ImageProcessor.Web.PostProcessor.Resources.Unmanaged." + folder + ".gifsicle.exe" }, - { "jpegtran.exe", "ImageProcessor.Web.PostProcessor.Resources.Unmanaged.x86.jpegtran.exe" }, - { "optipng.exe", "ImageProcessor.Web.PostProcessor.Resources.Unmanaged.x86.optipng.exe" }, - { "pngout.exe", "ImageProcessor.Web.PostProcessor.Resources.Unmanaged.x86.pngout.exe" }, - { "png.cmd", "ImageProcessor.Web.PostProcessor.Resources.Unmanaged.x86.png.cmd" } - }; - - // Write the files out to the bin folder. - foreach (KeyValuePair resource in resources) - { - using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource.Value)) - { - if (resourceStream != null) - { - using (FileStream fileStream = File.OpenWrite(Path.Combine(WorkingPath, resource.Key))) - { - resourceStream.CopyTo(fileStream); - } - } - } - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Properties/AssemblyInfo.cs b/old/src/ImageProcessor.Web.PostProcessor/Properties/AssemblyInfo.cs deleted file mode 100644 index 8b1c6855d..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.Web.PostProcessor")] -[assembly: AssemblyDescription("Post-processes cached images to further reduce file size.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("James South")] -[assembly: AssemblyProduct("ImageProcessor.Web.PostProcessor")] -[assembly: AssemblyCopyright("Copyright © James South")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("089f0bac-b115-4c40-a955-64da08aa0989")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.3.0")] -[assembly: AssemblyVersion("1.0.3.0")] -[assembly: AssemblyFileVersion("1.0.3.0")] diff --git a/old/src/ImageProcessor.Web.PostProcessor/README.md b/old/src/ImageProcessor.Web.PostProcessor/README.md deleted file mode 100644 index c91c7eb72..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/README.md +++ /dev/null @@ -1,13 +0,0 @@ -#Resource locations - -###gifsicle -[http://www.lcdf.org/gifsicle/](http://www.lcdf.org/gifsicle/) - -###jpegtran -[http://jpegclub.org/jpegtran/](http://jpegclub.org/jpegtran/) - -###optipng -[http://optipng.sourceforge.net/](http://optipng.sourceforge.net/) - -###pngout -[http://advsys.net/ken/utils.htm](http://advsys.net/ken/utils.htm) \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x64/gifsicle.exe.REMOVED.git-id b/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x64/gifsicle.exe.REMOVED.git-id deleted file mode 100644 index 1e5525042..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x64/gifsicle.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -8fdba772314bc58249bc68118054cadfabf200ba \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/gifsicle.exe.REMOVED.git-id b/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/gifsicle.exe.REMOVED.git-id deleted file mode 100644 index ffc8d42a9..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/gifsicle.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -58c7376ac5c2b3f95a36c286d35d4151abc8fafc \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/jpegtran.exe.REMOVED.git-id b/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/jpegtran.exe.REMOVED.git-id deleted file mode 100644 index a934efad1..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/jpegtran.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c4b33334d3a5ce903fee18d9573571d93ac81bd4 \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/optipng.exe.REMOVED.git-id b/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/optipng.exe.REMOVED.git-id deleted file mode 100644 index 3e52481dd..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/optipng.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -81cff3c5fe3cf669ef6e158240cc0034ed3711fd \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/png.cmd b/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/png.cmd deleted file mode 100644 index 9308f218b..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/png.cmd +++ /dev/null @@ -1,2 +0,0 @@ -optipng %1 -out %2 -o3 -i0 -quiet -clobber -pngout %2 %2 /s1 /y /v /q \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/pngout.exe b/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/pngout.exe deleted file mode 100644 index 0a0d7d3fa..000000000 Binary files a/old/src/ImageProcessor.Web.PostProcessor/Resources/Unmanaged/x86/pngout.exe and /dev/null differ diff --git a/old/src/ImageProcessor.Web.PostProcessor/Settings.StyleCop b/old/src/ImageProcessor.Web.PostProcessor/Settings.StyleCop deleted file mode 100644 index 8e2713ede..000000000 --- a/old/src/ImageProcessor.Web.PostProcessor/Settings.StyleCop +++ /dev/null @@ -1,7 +0,0 @@ - - - - executables - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.UnitTests/Extensions/StringExtensionsUnitTests.cs b/old/src/ImageProcessor.Web.UnitTests/Extensions/StringExtensionsUnitTests.cs deleted file mode 100644 index 3e9053aed..000000000 --- a/old/src/ImageProcessor.Web.UnitTests/Extensions/StringExtensionsUnitTests.cs +++ /dev/null @@ -1,160 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Test harness for the string extensions -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.UnitTests.Extensions -{ - using System; - using System.Collections.Generic; - - using ImageProcessor.Web.Extensions; - using NUnit.Framework; - - /// - /// Test harness for the string extensions - /// - [TestFixture] - public class StringExtensionsUnitTests - { - /// - /// Tests the passing to an integer array - /// - [Test] - public void TestToIntegerArray() - { - Dictionary data = new Dictionary - { - { - "123-456,78-90", - new[] { 123, 456, 78, 90 } - }, - { - "87390174,741897498,74816,748297,57355", - new[] - { - 87390174, 741897498, 74816, - 748297, 57355 - } - }, - { "1-2-3", new[] { 1, 2, 3 } } - }; - - foreach (KeyValuePair item in data) - { - int[] result = item.Key.ToPositiveIntegerArray(); - Assert.AreEqual(item.Value, result); - } - } - - /// - /// Tests the passing to an float array - /// - [Test] - public void TestToFloatArray() - { - Dictionary data = new Dictionary - { - { - "12.3-4.56,78-9.0", - new[] { 12.3F, 4.56F, 78, 9 } - }, - { - "87390.174,7.41897498,748.16,748297,5.7355", - new[] - { - 87390.174F, 7.41897498F, - 748.16F, 748297, 5.7355F - } - }, - { "1-2-3", new float[] { 1, 2, 3 } } - }; - - foreach (KeyValuePair item in data) - { - float[] result = item.Key.ToPositiveFloatArray(); - Assert.AreEqual(item.Value, result); - } - } - - /// - /// Tests the MD5 fingerprint - /// - /// The input value - /// The expected output of the hash - [Test] - [TestCase("test input", "2e7f7a62eabf0993239ca17c78c464d9")] - [TestCase("lorem ipsum dolor", "96ee002fee25e8b675a477c9750fa360")] - [TestCase("LoReM IpSuM DoLoR", "41e201da794c7fbdb8ce5526a71c8c83")] - [TestCase("1234567890", "e15e31c3d8898c92ab172a4311be9e84")] - public void TestToMd5Fingerprint(string input, string expected) - { - string result = input.ToMD5Fingerprint(); - bool comparison = result.Equals(expected, StringComparison.InvariantCultureIgnoreCase); - Assert.True(comparison); - } - - /// - /// Tests the SHA-1 fingerprint - /// - /// The input value - /// The expected output of the hash - [Test] - [TestCase("test input", "49883b34e5a0f48224dd6230f471e9dc1bdbeaf5")] - [TestCase("lorem ipsum dolor", "75899ad8827a32493928903aecd6e931bf36f967")] - [TestCase("LoReM IpSuM DoLoR", "2f44519afae72fc0837b72c6b53cb11338a1f916")] - [TestCase("1234567890", "01b307acba4f54f55aafc33bb06bbbf6ca803e9a")] - public void TestToSHA1Fingerprint(string input, string expected) - { - string result = input.ToSHA1Fingerprint(); - bool comparison = result.Equals(expected, StringComparison.InvariantCultureIgnoreCase); - Assert.True(comparison); - } - - /// - /// Tests if the value is a valid URI path name. I.E the path part of a uri. - /// - /// The value to test - /// Whether the value is correct - /// - /// The full RFC3986 does not seem to pass the test with the square brackets - /// ':' is failing for some reason in VS but not elsewhere. Could be a build issue. - /// - [Test] - [TestCase("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", true)] - [TestCase("-", true)] - [TestCase(".", true)] - [TestCase("_", true)] - [TestCase("~", true)] - [TestCase(":", true)] - [TestCase("/", true)] - [TestCase("?", true)] - [TestCase("#", false)] - [TestCase("[", false)] - [TestCase("]", false)] - [TestCase("@", true)] - [TestCase("!", true)] - [TestCase("$", true)] - [TestCase("&", true)] - [TestCase("'", true)] - [TestCase("(", true)] - [TestCase(")", true)] - [TestCase("*", true)] - [TestCase("+", true)] - [TestCase(",", true)] - [TestCase(";", true)] - [TestCase("=", true)] - [TestCase("lorem ipsum", false)] - [TestCase("é", false)] - public void TestIsValidUriPathName(string input, bool expected) - { - bool result = input.IsValidVirtualPathName(); - Assert.AreEqual(expected, result); - } - } -} diff --git a/old/src/ImageProcessor.Web.UnitTests/ImageProcessor.Web.UnitTests.csproj b/old/src/ImageProcessor.Web.UnitTests/ImageProcessor.Web.UnitTests.csproj deleted file mode 100644 index de05afdfe..000000000 --- a/old/src/ImageProcessor.Web.UnitTests/ImageProcessor.Web.UnitTests.csproj +++ /dev/null @@ -1,114 +0,0 @@ - - - - Debug - AnyCPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260} - Library - Properties - ImageProcessor.Web.UnitTests - ImageProcessor.Web.UnitTests - v4.5 - 512 - {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages - False - UnitTest - ..\ - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - ..\packages\NUnit.2.6.3\lib\nunit.framework.dll - - - - - - - - - - - - - - - - - - - - - - - - - {d011a778-59c8-4bfa-a770-c350216bf161} - ImageProcessor.Web - - - {3b5dd734-fb7a-487d-8ce6-55e7af9aea7e} - ImageProcessor - - - {2cf69699-959a-44dc-a281-4e2596c25043} - ImageProcessor.Plugins.WebP - - - - - - - False - - - False - - - False - - - False - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.UnitTests/Properties/AssemblyInfo.cs b/old/src/ImageProcessor.Web.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index db6aa3c94..000000000 --- a/old/src/ImageProcessor.Web.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.Web.UnitTests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ImageProcessor.Web.UnitTests")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("74919969-6a75-4d26-b1b8-0626aa10af6d")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/old/src/ImageProcessor.Web.UnitTests/QueryParamParserUnitTests.cs b/old/src/ImageProcessor.Web.UnitTests/QueryParamParserUnitTests.cs deleted file mode 100644 index 2ab57c1f9..000000000 --- a/old/src/ImageProcessor.Web.UnitTests/QueryParamParserUnitTests.cs +++ /dev/null @@ -1,181 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The query parameter parser unit tests. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.UnitTests -{ - using System; - using System.Collections.Specialized; - using System.Drawing; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Web.Helpers; - - using NUnit.Framework; - - /// - /// The query parameter parser unit tests. - /// - [TestFixture] - public class QueryParamParserUnitTests - { - [Test] - public void SingleParamOutputNotNull() - { - const string Param = "query=1"; - NameValueCollection query = HttpUtility.ParseQueryString(Param); - string result = QueryParamParser.Instance.ParseValue(query["query"]); - Assert.IsNotNull(result); - } - - [Test] - [TestCase("foo=4.5&foo=2.3", "foo")] - [TestCase("query=1.5&query=2.5", "query")] - public void MultipleParamOutputNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - float[] result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("", "entropycrop")] - [TestCase("entropycrop=0", "entropycrop")] - [TestCase("entropycrop=128", "entropycrop")] - public void IntNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - int result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("", "entropycrop", 0)] - [TestCase("entropycrop=0", "entropycrop", 0)] - [TestCase("entropycrop=128", "entropycrop", 128)] - [TestCase("entropycrop=128.4", "entropycrop", 128)] - [TestCase("entropycrop=128.5", "entropycrop", 129)] - public void IntRounded(string queryString, string parameter, int expected) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - int result = (int)Math.Round(QueryParamParser.Instance.ParseValue(query[parameter]), MidpointRounding.AwayFromZero); - Assert.AreEqual(result, expected); - } - - [TestCase("", "entropycrop")] - [TestCase("entropycrop=0", "entropycrop")] - [TestCase("entropycrop=128", "entropycrop")] - [TestCase("entropycrop=256", "entropycrop")] - public void ByteNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - byte result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("", "greyscale")] - [TestCase("greyscale=false", "greyscale")] - [TestCase("greyscale=true", "greyscale")] - public void BoolNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - bool result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - //[TestCase("", "rect")] - [TestCase("rect=0,0,100,100", "rect")] - public void RectangleNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - Rectangle result = QueryParamParser.Instance.ParseValue(query[parameter]); - - Assert.IsNotNull(result); - } - - [TestCase("", "size")] - [TestCase("size=1,1", "size")] - [TestCase("size=1", "size")] - public void SizeNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - Size result = QueryParamParser.Instance.ParseValue(query[parameter]); - - Assert.IsNotNull(result); - } - - [TestCase("", "point")] - [TestCase("point=1,1", "point")] - public void PointNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - Point result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("point=1.5,1.5", "point")] - public void PointFNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - PointF result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("resizemode=foo", "resizemode")] - [TestCase("resizemode=Max", "resizemode")] - [TestCase("resizemode=max", "resizemode")] - public void EnumNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - ResizeMode result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("", "resizemode")] - [TestCase("resizemode=foo", "resizemode")] - public void EnumIsDefault(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - ResizeMode result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.AreEqual(result, ResizeMode.Pad); - } - - [TestCase("resizemode=Max", "resizemode", ResizeMode.Max)] - [TestCase("resizemode=max", "resizemode", ResizeMode.Max)] - [TestCase("resizemode=crop", "resizemode", ResizeMode.Crop)] - public void EnumMatch(string queryString, string parameter, ResizeMode expected) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - ResizeMode result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.AreEqual(result, expected); - } - - [TestCase("color=white", "color")] - public void ColorNotNull(string queryString, string parameter) - { - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - Color result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.IsNotNull(result); - } - - [TestCase("color=255,255,255,255", "color")] - [TestCase("color=#fff", "color")] - [TestCase("color=#ffffff", "color")] - [TestCase("color=fff", "color")] - [TestCase("color=ffffff", "color")] - [TestCase("color=white", "color")] - [TestCase("color=White", "color")] - public void ColorMatch(string queryString, string parameter) - { - Color expected = Color.White; - NameValueCollection query = HttpUtility.ParseQueryString(queryString); - Color result = QueryParamParser.Instance.ParseValue(query[parameter]); - Assert.AreEqual(result.ToArgb(), expected.ToArgb()); - } - } -} diff --git a/old/src/ImageProcessor.Web.UnitTests/RegularExpressionUnitTests.cs b/old/src/ImageProcessor.Web.UnitTests/RegularExpressionUnitTests.cs deleted file mode 100644 index eb5962dbb..000000000 --- a/old/src/ImageProcessor.Web.UnitTests/RegularExpressionUnitTests.cs +++ /dev/null @@ -1,487 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Unit tests for the ImageProcessor regular expressions -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.UnitTests -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Filters.Photo; - using ImageProcessor.Imaging.Formats; - using ImageProcessor.Plugins.WebP.Imaging.Formats; - - using NUnit.Framework; - - /// - /// Test harness for the regular expressions - /// - [TestFixture] - public class RegularExpressionUnitTests - { - /// - /// The alpha regex unit test. - /// - /// - /// The input string. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("alpha=66", 66)] - [TestCase("alpha=101", 100)] - [TestCase("alpha=000053", 53)] - public void TestAlphaRegex(string input, int expected) - { - Processors.Alpha alpha = new Processors.Alpha(); - alpha.MatchRegexIndex(input); - int result = alpha.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The contrast regex unit test. - /// - /// - /// The input string. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("brightness=56", 56)] - [TestCase("brightness=84", 84)] - [TestCase("brightness=66", 66)] - [TestCase("brightness=101", 100)] - [TestCase("brightness=00001", 1)] - [TestCase("brightness=-50", -50)] - [TestCase("brightness=0", 0)] - public void TestBrightnesstRegex(string input, int expected) - { - Processors.Brightness brightness = new Processors.Brightness(); - brightness.MatchRegexIndex(input); - int result = brightness.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The contrast regex unit test. - /// - /// - /// The input string. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("contrast=56", 56)] - [TestCase("contrast=84", 84)] - [TestCase("contrast=66", 66)] - [TestCase("contrast=101", 100)] - [TestCase("contrast=00001", 1)] - [TestCase("contrast=-50", -50)] - [TestCase("contrast=0", 0)] - public void TestContrastRegex(string input, int expected) - { - Processors.Contrast contrast = new Processors.Contrast(); - contrast.MatchRegexIndex(input); - int result = contrast.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The rotate regex unit test. - /// - [Test] - public void TestCropRegex() - { - Dictionary data = new Dictionary - { - { - "crop=0,0,150,300", new CropLayer(0, 0, 150, 300, CropMode.Pixels) - }, - { - "crop=0.1,0.1,.2,.2&cropmode=percentage", new CropLayer(0.1f, 0.1f, 0.2f, 0.2f, CropMode.Percentage) - } - }; - - Processors.Crop crop = new Processors.Crop(); - - foreach (KeyValuePair item in data) - { - crop.MatchRegexIndex(item.Key); - CropLayer result = crop.Processor.DynamicParameter; - Assert.AreEqual(item.Value, result); - } - } - - /// - /// The filter regex unit test. - /// - [Test] - - public void TestFilterRegex() - { - Dictionary data = new Dictionary - { - { - "filter=lomograph", MatrixFilters.Lomograph - }, - { - "filter=polaroid", MatrixFilters.Polaroid - }, - { - "filter=comic", MatrixFilters.Comic - }, - { - "filter=greyscale", MatrixFilters.GreyScale - }, - { - "filter=blackwhite", MatrixFilters.BlackWhite - }, - { - "filter=invert", MatrixFilters.Invert - }, - { - "filter=gotham", MatrixFilters.Gotham - }, - { - "filter=hisatch", MatrixFilters.HiSatch - }, - { - "filter=losatch", MatrixFilters.LoSatch - }, - { - "filter=sepia", MatrixFilters.Sepia - } - }; - - Processors.Filter filter = new Processors.Filter(); - foreach (KeyValuePair item in data) - { - filter.MatchRegexIndex(item.Key); - IMatrixFilter result = filter.Processor.DynamicParameter; - Assert.AreEqual(item.Value, result); - } - } - - /// - /// The format regex unit test. - /// - /// - /// The input querystring. - /// - /// - /// The expected type. - /// - [Test] - [TestCase("format=bmp", typeof(BitmapFormat))] - [TestCase("format=png", typeof(PngFormat))] - [TestCase("format=png8", typeof(PngFormat))] - [TestCase("format=jpeg", typeof(JpegFormat))] - [TestCase("format=jpg", typeof(JpegFormat))] - [TestCase("format=gif", typeof(GifFormat))] - [TestCase("format=webp", typeof(WebPFormat))] - public void TestFormatRegex(string input, Type expected) - { - Processors.Format format = new Processors.Format(); - format.MatchRegexIndex(input); - Type result = format.Processor.DynamicParameter.GetType(); - - Assert.AreEqual(expected, result); - } - - /// - /// The quality regex unit test. - /// - /// - /// The input. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("quality=56", 56)] - [TestCase("quality=84", 84)] - [TestCase("quality=66", 66)] - [TestCase("quality=101", 100)] - [TestCase("quality=00001", 1)] - [TestCase("quality=0", 0)] - public void TestQualityRegex(string input, int expected) - { - Processors.Quality quality = new Processors.Quality(); - quality.MatchRegexIndex(input); - int result = quality.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The meta regex unit test. - /// - /// - /// The input. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("meta=true", true)] - [TestCase("meta=false", false)] - public void TestMetaRegex(string input, bool expected) - { - Processors.Meta meta = new Processors.Meta(); - meta.MatchRegexIndex(input); - bool result = meta.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The resize regex unit test. - /// - [Test] - public void TestResizeRegex() - { - Dictionary data = new Dictionary - { - { - "width=300", new ResizeLayer(new Size(300, 0)) - }, - { - "height=300", new ResizeLayer(new Size(0, 300)) - }, - { - "height=300.6", new ResizeLayer(new Size(0, 301)) - }, - { - "height=300&mode=crop", new ResizeLayer(new Size(0, 300), ResizeMode.Crop) - }, - { - "width=300&mode=crop", new ResizeLayer(new Size(300, 0), ResizeMode.Crop) - }, - { - "width=300.2&mode=crop", new ResizeLayer(new Size(300, 0), ResizeMode.Crop) - }, - { - "width=600&heightratio=0.416", new ResizeLayer(new Size(600, 250)) - }, - { - "width=600&height=250&mode=max", new ResizeLayer(new Size(600, 250), ResizeMode.Max) - } - }; - - Processors.Resize resize = new Processors.Resize(); - foreach (KeyValuePair item in data) - { - resize.MatchRegexIndex(item.Key); - ResizeLayer result = resize.Processor.DynamicParameter; - Assert.AreEqual(item.Value, result); - } - } - - /// - /// The rotate regex unit test. - /// - /// - /// The input string. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("rotate=0", 0F)] - [TestCase("rotate=270", 270F)] - [TestCase("rotate=-270", -270F)] - [TestCase("rotate=28", 28F)] - [TestCase("rotate=28.7", 28.7F)] - public void TestRotateRegex(string input, float expected) - { - Processors.Rotate rotate = new Processors.Rotate(); - rotate.MatchRegexIndex(input); - - float result = rotate.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The rounded corners regex unit test. - /// - [Test] - public void TestRoundedCornersRegex() - { - Dictionary data = new Dictionary - { - { - "roundedcorners=30", new RoundedCornerLayer(30) - }, - { - "roundedcorners=26&tl=true&tr=false&bl=true&br=false", new RoundedCornerLayer(26, true, false, true, false) - } - }; - - Processors.RoundedCorners roundedCorners = new Processors.RoundedCorners(); - foreach (KeyValuePair item in data) - { - roundedCorners.MatchRegexIndex(item.Key); - RoundedCornerLayer result = roundedCorners.Processor.DynamicParameter; - Assert.AreEqual(item.Value, result); - } - } - - /// - /// The saturation regex unit test. - /// - /// - /// The input string. - /// - /// - /// The expected result. - /// - [Test] - [TestCase("saturation=56", 56)] - [TestCase("saturation=84", 84)] - [TestCase("saturation=66", 66)] - [TestCase("saturation=101", 100)] - [TestCase("saturation=00001", 1)] - [TestCase("saturation=-50", -50)] - [TestCase("saturation=0", 0)] - public void TestSaturationRegex(string input, int expected) - { - Processors.Saturation saturation = new Processors.Saturation(); - saturation.MatchRegexIndex(input); - int result = saturation.Processor.DynamicParameter; - - Assert.AreEqual(expected, result); - } - - /// - /// The tint regex unit test. - /// - [Test] - public void TestTintRegex() - { - Dictionary data = new Dictionary - { - { - "tint=6aa6cc", ColorTranslator.FromHtml("#" + "6aa6cc") - }, - { - "tint=106,166,204,255", Color.FromArgb(255, 106, 166, 204) - }, - { - "tint=fff", Color.FromArgb(255, 255, 255, 255) - }, - { - "tint=white", Color.White - } - }; - - Processors.Tint tint = new Processors.Tint(); - foreach (KeyValuePair item in data) - { - tint.MatchRegexIndex(item.Key); - Color result = tint.Processor.DynamicParameter; - Assert.AreEqual(item.Value.ToArgb(), result.ToArgb()); - } - } - - /// - /// The vignette regex unit test. - /// - [Test] - public void TestVignetteRegex() - { - Dictionary data = new Dictionary - { - { - "vignette", Color.Black - }, - { - "vignette=true", Color.Black - }, - { - "vignette=6aa6cc", ColorTranslator.FromHtml("#" + "6aa6cc") - }, - { - "vignette=106,166,204,255", Color.FromArgb(255, 106, 166, 204) - }, - { - "vignette=fff", Color.FromArgb(255, 255, 255, 255) - }, - { - "vignette=white", Color.White - } - }; - - Processors.Vignette vignette = new Processors.Vignette(); - foreach (KeyValuePair item in data) - { - vignette.MatchRegexIndex(item.Key); - Color result = vignette.Processor.DynamicParameter; - Assert.AreEqual(item.Value, result); - } - } - - /// - /// The watermark regex unit test. - /// - [Test] - public void TestWaterMarkRegex() - { - Dictionary data = new Dictionary - { - { - "watermark=watermark goodness&color=fff&fontsize=36&fontstyle=italic&fontopacity=80&textposition=30,150&dropshadow=true&fontfamily=arial", - new TextLayer - { - Text = "watermark goodness", - FontColor = ColorTranslator.FromHtml("#" + "ffffff"), - FontSize = 36, - Style = FontStyle.Italic, - Opacity = 80, - Position = new Point(30, 150), - DropShadow = true, - FontFamily = new FontFamily("arial") - } - }, - { - "watermark=لا أحد يحب الألم بذاته، يسعى ورائه أو يبتغيه، ببساطة لأنه الألم&color=fff&fontsize=36&fontstyle=italic&fontopacity=80&textposition=30,150&dropshadow=true&fontfamily=arial&vertical=true&rtl=true", - new TextLayer - { - Text = "لا أحد يحب الألم بذاته، يسعى ورائه أو يبتغيه، ببساطة لأنه الألم", - FontColor = ColorTranslator.FromHtml("#" + "ffffff"), - FontSize = 36, - Style = FontStyle.Italic, - Opacity = 80, - Position = new Point(30, 150), - DropShadow = true, - FontFamily = new FontFamily("arial"), - Vertical = true, - RightToLeft = true - } - } - }; - - Processors.Watermark watermark = new Processors.Watermark(); - foreach (KeyValuePair item in data) - { - watermark.MatchRegexIndex(item.Key); - TextLayer result = watermark.Processor.DynamicParameter; - Assert.AreEqual(item.Value, result); - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web.UnitTests/packages.config b/old/src/ImageProcessor.Web.UnitTests/packages.config deleted file mode 100644 index 139d5138c..000000000 --- a/old/src/ImageProcessor.Web.UnitTests/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Caching/CacheIndexer.cs b/old/src/ImageProcessor.Web/Caching/CacheIndexer.cs deleted file mode 100644 index e872366f1..000000000 --- a/old/src/ImageProcessor.Web/Caching/CacheIndexer.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents an in memory collection of keys and values whose operations are concurrent. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Caching -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Runtime.Caching; - - /// - /// Represents an in memory collection of cached images whose operations are concurrent. - /// - public static class CacheIndexer - { - /// - /// Gets the associated with the specified key. - /// - /// - /// The cached path of the value to get. - /// - /// - /// The matching the given key if the contains an element with - /// the specified key; otherwise, null. - /// - public static CachedImage Get(string cachedPath) - { - string key = Path.GetFileNameWithoutExtension(cachedPath); - CachedImage cachedImage = (CachedImage)MemCache.GetItem(key); - return cachedImage; - } - - /// - /// Removes the value associated with the specified key. - /// - /// - /// The key of the item to remove. - /// - /// - /// true if the removes an element with - /// the specified key; otherwise, false. - /// - public static bool Remove(string cachedPath) - { - string key = Path.GetFileNameWithoutExtension(cachedPath); - return MemCache.RemoveItem(key); - } - - /// - /// Adds the specified key and value to the dictionary or returns the value if it exists. - /// - /// - /// The cached image to add. - /// - /// - /// The value of the item to add or get. - /// - public static CachedImage Add(CachedImage cachedImage) - { - // Add the CachedImage with a sliding expiration of 10 minutes. - CacheItemPolicy policy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(0, 10, 0) }; - - if (new Uri(cachedImage.Path).IsFile) - { - policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List { cachedImage.Path })); - - MemCache.AddItem(Path.GetFileNameWithoutExtension(cachedImage.Key), cachedImage, policy); - } - else - { - MemCache.AddItem(Path.GetFileNameWithoutExtension(cachedImage.Key), cachedImage, policy); - } - - return cachedImage; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Caching/CachedImage.cs b/old/src/ImageProcessor.Web/Caching/CachedImage.cs deleted file mode 100644 index 25519fcc4..000000000 --- a/old/src/ImageProcessor.Web/Caching/CachedImage.cs +++ /dev/null @@ -1,35 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Describes a cached image -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Caching -{ - using System; - - /// - /// Describes a cached image - /// - public sealed class CachedImage - { - /// - /// Gets or sets the key identifying the cached image. - /// - public string Key { get; set; } - - /// - /// Gets or sets the value of the cached image. - /// - public string Path { get; set; } - - /// - /// Gets or sets the creation time of the cached image. - /// - public DateTime CreationTimeUtc { get; set; } - } -} diff --git a/old/src/ImageProcessor.Web/Caching/DiskCache.cs b/old/src/ImageProcessor.Web/Caching/DiskCache.cs deleted file mode 100644 index 1c9040e40..000000000 --- a/old/src/ImageProcessor.Web/Caching/DiskCache.cs +++ /dev/null @@ -1,232 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides an implementation that is file system based. -// The cache is self healing and cleaning. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Caching -{ - using System.Collections.Generic; - using System.Configuration; - using System.IO; - using System.Linq; - using System.Threading.Tasks; - using System.Web; - using System.Web.Hosting; - - using ImageProcessor.Web.Extensions; - - /// - /// Provides an implementation that is file system based. - /// The cache is self healing and cleaning. - /// - public class DiskCache : ImageCacheBase - { - /// - /// The maximum number of files allowed in the directory. - /// - /// - /// NTFS directories can handle up to 10,000 files in the directory before slowing down. - /// This will help us to ensure that don't go over that limit. - /// - /// - /// - /// - private const int MaxFilesCount = 100; - - /// - /// The virtual cache path. - /// - private readonly string virtualCachePath; - - /// - /// The absolute path to virtual cache path on the server. - /// - private readonly string absoluteCachePath; - - /// - /// The virtual path to the cached file. - /// - private string virtualCachedFilePath; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The request path for the image. - /// - /// - /// The full path for the image. - /// - /// - /// The querystring containing instructions. - /// - public DiskCache(string requestPath, string fullPath, string querystring) - : base(requestPath, fullPath, querystring) - { - string virtualPath = this.Settings["VirtualCachePath"]; - - if (!virtualPath.IsValidVirtualPathName()) - { - throw new ConfigurationErrorsException("DiskCache 'VirtualCachePath' is not a valid virtual path."); - } - - this.virtualCachePath = virtualPath; - - this.absoluteCachePath = HostingEnvironment.MapPath(this.virtualCachePath); - } - - /// - /// Gets a value indicating whether the image is new or updated in an asynchronous manner. - /// - /// - /// The . - /// - public override async Task IsNewOrUpdatedAsync() - { - string cachedFileName = await this.CreateCachedFileNameAsync(); - - // Collision rate of about 1 in 10000 for the folder structure. - // That gives us massive scope to store millions of files. - string pathFromKey = string.Join("\\", cachedFileName.ToCharArray().Take(6)); - string virtualPathFromKey = pathFromKey.Replace(@"\", "/"); - this.CachedPath = Path.Combine(this.absoluteCachePath, pathFromKey, cachedFileName); - this.virtualCachedFilePath = Path.Combine(this.virtualCachePath, virtualPathFromKey, cachedFileName).Replace(@"\", "/"); - - bool isUpdated = false; - CachedImage cachedImage = CacheIndexer.Get(this.CachedPath); - - if (cachedImage == null) - { - FileInfo fileInfo = new FileInfo(this.CachedPath); - - if (fileInfo.Exists) - { - // Pull the latest info. - fileInfo.Refresh(); - - cachedImage = new CachedImage - { - Key = Path.GetFileNameWithoutExtension(this.CachedPath), - Path = this.CachedPath, - CreationTimeUtc = fileInfo.CreationTimeUtc - }; - - CacheIndexer.Add(cachedImage); - } - } - - if (cachedImage == null) - { - // Nothing in the cache so we should return true. - isUpdated = true; - } - else - { - // Check to see if the cached image is set to expire. - if (this.IsExpired(cachedImage.CreationTimeUtc)) - { - CacheIndexer.Remove(this.CachedPath); - isUpdated = true; - } - } - - return isUpdated; - } - - /// - /// Adds the image to the cache in an asynchronous manner. - /// - /// - /// The stream containing the image data. - /// - /// - /// The content type of the image. - /// - /// - /// The representing an asynchronous operation. - /// - public override async Task AddImageToCacheAsync(Stream stream, string contentType) - { - // ReSharper disable once AssignNullToNotNullAttribute - DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(this.CachedPath)); - if (!directoryInfo.Exists) - { - directoryInfo.Create(); - } - - using (FileStream fileStream = File.Create(this.CachedPath)) - { - await stream.CopyToAsync(fileStream); - } - } - - /// - /// Trims the cache of any expired items in an asynchronous manner. - /// - /// - /// The asynchronous representing an asynchronous operation. - /// - public override async Task TrimCacheAsync() - { - string directory = Path.GetDirectoryName(this.CachedPath); - - if (directory != null) - { - DirectoryInfo directoryInfo = new DirectoryInfo(directory); - DirectoryInfo parentDirectoryInfo = directoryInfo.Parent; - - if (parentDirectoryInfo != null) - { - // UNC folders can throw exceptions if the file doesn't exist. - foreach (DirectoryInfo enumerateDirectory in await parentDirectoryInfo.SafeEnumerateDirectoriesAsync()) - { - IEnumerable files = enumerateDirectory.EnumerateFiles().OrderBy(f => f.CreationTimeUtc); - int count = files.Count(); - - foreach (FileInfo fileInfo in files) - { - try - { - // If the group count is equal to the max count minus 1 then we know we - // have reduced the number of items below the maximum allowed. - // We'll cleanup any orphaned expired files though. - if (!this.IsExpired(fileInfo.CreationTimeUtc) && count <= MaxFilesCount - 1) - { - break; - } - - // Remove from the cache and delete each CachedImage. - CacheIndexer.Remove(fileInfo.Name); - fileInfo.Delete(); - count -= 1; - } - // ReSharper disable once EmptyGeneralCatchClause - catch - { - // Do nothing; skip to the next file. - } - } - } - } - } - } - - /// - /// Rewrites the path to point to the cached image. - /// - /// - /// The encapsulating all information about the request. - /// - public override void RewritePath(HttpContext context) - { - // The cached file is valid so just rewrite the path. - context.RewritePath(this.virtualCachedFilePath, false); - } - } -} diff --git a/old/src/ImageProcessor.Web/Caching/IImageCache.cs b/old/src/ImageProcessor.Web/Caching/IImageCache.cs deleted file mode 100644 index cff12b47b..000000000 --- a/old/src/ImageProcessor.Web/Caching/IImageCache.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Defines properties and methods for allowing caching of images to different sources. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Caching -{ - using System.Collections.Generic; - using System.IO; - using System.Threading.Tasks; - using System.Web; - - /// - /// Defines properties and methods for allowing caching of images to different sources. - /// - public interface IImageCache - { - /// - /// Gets or sets any additional settings required by the cache. - /// - Dictionary Settings { get; set; } - - /// - /// Gets the path to the cached image. - /// - string CachedPath { get; } - - /// - /// Gets or sets the maximum number of days to store the image. - /// - int MaxDays { get; set; } - - /// - /// Gets a value indicating whether the image is new or updated in an asynchronous manner. - /// - /// - /// The asynchronous returning the value. - /// - Task IsNewOrUpdatedAsync(); - - /// - /// Adds the image to the cache in an asynchronous manner. - /// - /// - /// The stream containing the image data. - /// - /// - /// The content type of the image. - /// - /// - /// The representing an asynchronous operation. - /// - Task AddImageToCacheAsync(Stream stream, string contentType); - - /// - /// Trims the cache of any expired items in an asynchronous manner. - /// - /// - /// The asynchronous representing an asynchronous operation. - /// - Task TrimCacheAsync(); - - /// - /// Gets a string identifying the cached file name in an asynchronous manner. - /// - /// - /// The asynchronous returning the value. - /// - Task CreateCachedFileNameAsync(); - - /// - /// Rewrites the path to point to the cached image. - /// - /// - /// The encapsulating all information about the request. - /// - void RewritePath(HttpContext context); - } -} diff --git a/old/src/ImageProcessor.Web/Caching/ImageCacheBase.cs b/old/src/ImageProcessor.Web/Caching/ImageCacheBase.cs deleted file mode 100644 index cec6886ab..000000000 --- a/old/src/ImageProcessor.Web/Caching/ImageCacheBase.cs +++ /dev/null @@ -1,183 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The image cache base provides methods for implementing the interface. -// It is recommended that any implementations inherit from this class. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Caching -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.IO; - using System.Threading.Tasks; - using System.Web; - - using ImageProcessor.Web.Configuration; - using ImageProcessor.Web.Extensions; - using ImageProcessor.Web.Helpers; - - /// - /// The image cache base provides methods for implementing the interface. - /// It is recommended that any implementations inherit from this class. - /// - public abstract class ImageCacheBase : IImageCache - { - /// - /// The request path for the image. - /// - protected readonly string RequestPath; - - /// - /// The full path for the image. - /// - protected readonly string FullPath; - - /// - /// The querystring containing processing instructions. - /// - protected readonly string Querystring; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The request path for the image. - /// - /// - /// The full path for the image. - /// - /// - /// The querystring containing instructions. - /// - protected ImageCacheBase(string requestPath, string fullPath, string querystring) - { - this.RequestPath = requestPath; - this.FullPath = fullPath; - this.Querystring = querystring; - this.Settings = ImageProcessorConfiguration.Instance.ImageCacheSettings; - this.MaxDays = ImageProcessorConfiguration.Instance.ImageCacheMaxDays; - } - - /// - /// Gets or sets any additional settings required by the cache. - /// - public Dictionary Settings { get; set; } - - /// - /// Gets or sets the path to the cached image. - /// - public string CachedPath { get; set; } - - /// - /// Gets or sets the maximum number of days to store the image. - /// - public int MaxDays { get; set; } - - /// - /// Gets a value indicating whether the image is new or updated in an asynchronous manner. - /// - /// - /// The . - /// - public abstract Task IsNewOrUpdatedAsync(); - - /// - /// Adds the image to the cache in an asynchronous manner. - /// - /// - /// The stream containing the image data. - /// - /// - /// The content type of the image. - /// - /// - /// The representing an asynchronous operation. - /// - public abstract Task AddImageToCacheAsync(Stream stream, string contentType); - - /// - /// Trims the cache of any expired items in an asynchronous manner. - /// - /// - /// The asynchronous representing an asynchronous operation. - /// - public abstract Task TrimCacheAsync(); - - /// - /// Gets a string identifying the cached file name. - /// - /// - /// The asynchronous returning the value. - /// - public virtual async Task CreateCachedFileNameAsync() - { - string streamHash = string.Empty; - - try - { - if (new Uri(this.RequestPath).IsFile) - { - // Get the hash for the filestream. That way we can ensure that if the image is - // updated but has the same name we will know. - FileInfo imageFileInfo = new FileInfo(this.RequestPath); - if (imageFileInfo.Exists) - { - // Pull the latest info. - imageFileInfo.Refresh(); - - // Checking the stream itself is far too processor intensive so we make a best guess. - string creation = imageFileInfo.CreationTimeUtc.ToString(CultureInfo.InvariantCulture); - string length = imageFileInfo.Length.ToString(CultureInfo.InvariantCulture); - streamHash = string.Format("{0}{1}", creation, length); - } - } - } - catch - { - streamHash = string.Empty; - } - - // Use an sha1 hash of the full path including the querystring to create the image name. - // That name can also be used as a key for the cached image and we should be able to use - // The characters of that hash as sub-folders. - string parsedExtension = ImageHelpers.GetExtension(this.FullPath, this.Querystring); - string encryptedName = (streamHash + this.FullPath).ToSHA1Fingerprint(); - - string cachedFileName = string.Format( - "{0}.{1}", - encryptedName, - !string.IsNullOrWhiteSpace(parsedExtension) ? parsedExtension.Replace(".", string.Empty) : "jpg"); - - return await Task.FromResult(cachedFileName); - } - - /// - /// Rewrites the path to point to the cached image. - /// - /// - /// The encapsulating all information about the request. - /// - public abstract void RewritePath(HttpContext context); - - /// - /// Gets a value indicating whether the given images creation date is out with - /// the prescribed limit. - /// - /// - /// The creation date. - /// - /// - /// The true if the date is out with the limit, otherwise; false. - /// - protected virtual bool IsExpired(DateTime creationDate) - { - return creationDate.AddDays(this.MaxDays) < DateTime.UtcNow.AddDays(-this.MaxDays); - } - } -} diff --git a/old/src/ImageProcessor.Web/Caching/MemCache.cs b/old/src/ImageProcessor.Web/Caching/MemCache.cs deleted file mode 100644 index 060a3e805..000000000 --- a/old/src/ImageProcessor.Web/Caching/MemCache.cs +++ /dev/null @@ -1,246 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods that allow the caching and retrieval of objects from the in memory cache. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Caching -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Runtime.Caching; - using System.Threading; - - using ImageProcessor.Common.Helpers; - - /// - /// Encapsulates methods that allow the caching and retrieval of objects from the in memory cache. - /// - internal static class MemCache - { - /// - /// The cache - /// - private static readonly ObjectCache Cache = MemoryCache.Default; - - /// - /// The reader-writer lock implementation. - /// - private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); - - /// - /// An internal list of cache keys to allow bulk removal. - /// - private static readonly ConcurrentDictionary CacheItems = new ConcurrentDictionary(); - - /// - /// Adds an item to the cache. - /// - /// - /// A unique identifier for the cache entry. - /// - /// - /// The object to insert. - /// - /// - /// Optional. An object that contains eviction details for the cache entry. This object - /// provides more options for eviction than a simple absolute expiration. The default value for the optional parameter - /// is null. - /// - /// - /// Optional. A named region in the cache to which the cache entry can be added, - /// if regions are implemented. The default value for the optional parameter - /// is null. - /// - /// - /// True if the insertion try succeeds, or false if there is an already an entry - /// in the cache with the same key as key. - /// - public static bool AddItem(string key, object value, CacheItemPolicy policy = null, string regionName = null) - { - bool isAdded; - using (new WriteLock(Locker)) - { - if (policy == null) - { - // Create a new cache policy with the default values - policy = new CacheItemPolicy(); - } - - try - { - Cache.Set(key, value, policy, regionName); - isAdded = true; - } - catch - { - isAdded = false; - } - - if (isAdded) - { - CacheItems[key] = regionName; - } - } - - return isAdded; - } - - /// - /// Fetches an item matching the given key from the cache. - /// - /// - /// A unique identifier for the cache entry. - /// - /// - /// Optional. A named region in the cache to which the cache entry can be added, - /// if regions are implemented. The default value for the optional parameter - /// is null. - /// - /// - /// The cache entry that is identified by key. - /// - public static object GetItem(string key, string regionName = null) - { - using (new UpgradeableReadLock(Locker)) - { - return Cache.Get(key, regionName); - } - } - - /// - /// Updates an item to the cache. - /// - /// - /// A unique identifier for the cache entry. - /// - /// - /// The object to insert. - /// - /// - /// Optional. An object that contains eviction details for the cache entry. This object - /// provides more options for eviction than a simple absolute expiration. The default value for the optional parameter - /// is null. - /// - /// - /// Optional. A named region in the cache to which the cache entry can be added, - /// if regions are implemented. The default value for the optional parameter - /// is null. - /// - /// - /// True if the update try succeeds, or false if there is an already an entry - /// in the cache with the same key as key. - /// - public static bool UpdateItem(string key, object value, CacheItemPolicy policy = null, string regionName = null) - { - bool isUpDated = true; - - // Remove the item from the cache if it already exists. MemoryCache will - // not add an item with an existing name. - if (GetItem(key, regionName) != null) - { - isUpDated = RemoveItem(key, regionName); - } - - if (policy == null) - { - // Create a new cache policy with the default values - policy = new CacheItemPolicy(); - } - - if (isUpDated) - { - isUpDated = AddItem(key, value, policy, regionName); - } - - return isUpDated; - } - - /// - /// Removes an item matching the given key from the cache. - /// - /// - /// A unique identifier for the cache entry. - /// - /// - /// Optional. A named region in the cache to which the cache entry can be added, - /// if regions are implemented. The default value for the optional parameter - /// is null. - /// - /// - /// True if the removal try succeeds, or false if there is an already an entry - /// in the cache with the same key as key. - /// - public static bool RemoveItem(string key, string regionName = null) - { - bool isRemoved; - - using (new WriteLock(Locker)) - { - isRemoved = Cache.Remove(key, regionName) != null; - - if (isRemoved) - { - string removedValue; - CacheItems.TryRemove(key, out removedValue); - } - } - - return isRemoved; - } - - /// - /// Clears the cache. - /// - /// - /// The region name. - /// - /// - /// The . - /// - public static bool Clear(string regionName = null) - { - bool isCleared = false; - - using (new WriteLock(Locker)) - { - // You can't remove items from a collection whilst you are iterating over it so you need to - // create a collection to store the items to remove. - ConcurrentDictionary tempDictionary = new ConcurrentDictionary(); - - foreach (KeyValuePair cacheItem in CacheItems) - { - // Does the cached key come with a region. - if ((cacheItem.Value == null) || (cacheItem.Value != null && cacheItem.Value.Equals(regionName, StringComparison.OrdinalIgnoreCase))) - { - isCleared = RemoveItem(cacheItem.Key, cacheItem.Value); - - if (isCleared) - { - string key = cacheItem.Key; - string value = cacheItem.Value; - tempDictionary.AddOrUpdate(key, value, (oldkey, oldValue) => value); - } - } - } - - if (isCleared) - { - // Loop through and clear out the dictionary of cache keys. - foreach (KeyValuePair cacheItem in tempDictionary) - { - string removedValue; - CacheItems.TryRemove(cacheItem.Key, out removedValue); - } - } - } - - return isCleared; - } - } -} diff --git a/old/src/ImageProcessor.Web/Configuration/ImageCacheSection.cs b/old/src/ImageProcessor.Web/Configuration/ImageCacheSection.cs deleted file mode 100644 index e365b0fba..000000000 --- a/old/src/ImageProcessor.Web/Configuration/ImageCacheSection.cs +++ /dev/null @@ -1,220 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents an image cache section within a configuration file. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Configuration -{ - using System.Configuration; - using System.IO; - using System.Xml; - - using ImageProcessor.Web.Helpers; - - /// - /// Represents an image cache section within a configuration file. - /// - public sealed class ImageCacheSection : ConfigurationSection - { - /// - /// Gets or sets the name of the current cache provider. - /// - /// The name of the cache folder. - [ConfigurationProperty("currentCache", DefaultValue = "DiskCache", IsRequired = true)] - public string CurrentCache - { - get - { - return (string)this["currentCache"]; - } - - set - { - this["currentCache"] = value; - } - } - - /// - /// Gets the - /// - /// The - [ConfigurationProperty("caches", IsRequired = true)] - public CacheElementCollection ImageCaches - { - get - { - object o = this["caches"]; - return o as CacheElementCollection; - } - } - - /// - /// Retrieves the cache configuration section from the current application configuration. - /// - /// The cache configuration section from the current application configuration. - public static ImageCacheSection GetConfiguration() - { - ImageCacheSection imageCacheSection = ConfigurationManager.GetSection("imageProcessor/caching") as ImageCacheSection; - - if (imageCacheSection != null) - { - return imageCacheSection; - } - - string section = ResourceHelpers.ResourceAsString("ImageProcessor.Web.Configuration.Resources.cache.config.transform"); - XmlReader reader = new XmlTextReader(new StringReader(section)); - imageCacheSection = new ImageCacheSection(); - imageCacheSection.DeserializeSection(reader); - - return imageCacheSection; - } - - /// - /// Represents a CacheElement configuration element within the configuration. - /// - public class CacheElement : ConfigurationElement - { - /// - /// Gets or sets the name of the cache. - /// - /// The name of the service. - [ConfigurationProperty("name", DefaultValue = "", IsRequired = true)] - public string Name - { - get { return (string)this["name"]; } - - set { this["name"] = value; } - } - - /// - /// Gets or sets the type of the cache. - /// - /// The full Type definition of the service - [ConfigurationProperty("type", DefaultValue = "", IsRequired = true)] - public string Type - { - get { return (string)this["type"]; } - - set { this["type"] = value; } - } - - /// - /// Gets or sets the maximum number of days to store an image in the cache. - /// - /// The maximum number of days to store an image in the cache. - /// Defaults to 365 if not set. - [ConfigurationProperty("maxDays", DefaultValue = "365", IsRequired = true)] - [IntegerValidator(ExcludeRange = false, MinValue = 0)] - public int MaxDays - { - get - { - return (int)this["maxDays"]; - } - - set - { - this["maxDays"] = value; - } - } - - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("settings", IsRequired = false)] - public SettingElementCollection Settings - { - get - { - return this["settings"] as SettingElementCollection; - } - } - } - - /// - /// Represents a collection of elements within the configuration. - /// - public class CacheElementCollection : ConfigurationElementCollection - { - /// - /// Gets the type of the . - /// - /// - /// The of this collection. - /// - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.BasicMap; } - } - - /// - /// Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. - /// - /// - /// The name of the collection; otherwise, an empty string. The default is an empty string. - /// - protected override string ElementName - { - get { return "cache"; } - } - - /// - /// Gets or sets the - /// at the specified index within the collection. - /// - /// The index at which to get the specified object. - /// - /// The - /// at the specified index within the collection. - /// - public CacheElement this[int index] - { - get - { - return (CacheElement)BaseGet(index); - } - - set - { - if (this.BaseGet(index) != null) - { - this.BaseRemoveAt(index); - } - - this.BaseAdd(index, value); - } - } - - /// - /// When overridden in a derived class, creates a new . - /// - /// - /// A new . - /// - protected override ConfigurationElement CreateNewElement() - { - return new CacheElement(); - } - - /// - /// Gets the element key for a specified configuration element when overridden in a derived class. - /// - /// - /// An that acts as the key for the specified . - /// - /// The to return the key for. - protected override object GetElementKey(ConfigurationElement element) - { - return ((CacheElement)element).Name; - } - } - } -} diff --git a/old/src/ImageProcessor.Web/Configuration/ImageProcessingSection.cs b/old/src/ImageProcessor.Web/Configuration/ImageProcessingSection.cs deleted file mode 100644 index 94598dd20..000000000 --- a/old/src/ImageProcessor.Web/Configuration/ImageProcessingSection.cs +++ /dev/null @@ -1,335 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents an image processing section within a configuration file. -// Nested syntax adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Configuration -{ - using System.Configuration; - using System.IO; - using System.Xml; - - using ImageProcessor.Web.Helpers; - - /// - /// Represents an image processing section within a configuration file. - /// Nested syntax adapted from - /// - public sealed class ImageProcessingSection : ConfigurationSection - { - /// - /// Gets or sets a value indicating whether to preserve exif meta data. - /// - [ConfigurationProperty("preserveExifMetaData", IsRequired = false, DefaultValue = false)] - public bool PreserveExifMetaData - { - get { return (bool)this["preserveExifMetaData"]; } - set { this["preserveExifMetaData"] = value; } - } - - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("presets", IsRequired = true)] - public PresetElementCollection Presets - { - get - { - return this["presets"] as PresetElementCollection; - } - } - - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("plugins", IsRequired = true)] - public PluginElementCollection Plugins - { - get - { - return this["plugins"] as PluginElementCollection; - } - } - - /// - /// Gets or sets a value indicating whether to auto load plugins. - /// - public bool AutoLoadPlugins { get; set; } - - /// - /// Retrieves the processing configuration section from the current application configuration. - /// - /// The processing configuration section from the current application configuration. - public static ImageProcessingSection GetConfiguration() - { - ImageProcessingSection imageProcessingSection = - ConfigurationManager.GetSection("imageProcessor/processing") as ImageProcessingSection; - - if (imageProcessingSection != null) - { - imageProcessingSection.AutoLoadPlugins = false; - return imageProcessingSection; - } - - string section = ResourceHelpers.ResourceAsString("ImageProcessor.Web.Configuration.Resources.processing.config.transform"); - XmlReader reader = new XmlTextReader(new StringReader(section)); - imageProcessingSection = new ImageProcessingSection(); - imageProcessingSection.DeserializeSection(reader); - imageProcessingSection.AutoLoadPlugins = true; - return imageProcessingSection; - } - - /// - /// Represents a PresetElement configuration element within the configuration. - /// - public class PresetElement : ConfigurationElement - { - /// - /// Gets or sets the name of the preset. - /// - /// The name of the plugin. - [ConfigurationProperty("name", DefaultValue = "", IsRequired = true)] - public string Name - { - get { return (string)this["name"]; } - - set { this["name"] = value; } - } - - /// - /// Gets or sets the value of the preset. - /// - /// The full Type definition of the plugin - [ConfigurationProperty("value", DefaultValue = "", IsRequired = true)] - public string Value - { - get { return (string)this["value"]; } - - set { this["value"] = value; } - } - } - - /// - /// Represents a PresetElementCollection collection configuration element within the configuration. - /// - public class PresetElementCollection : ConfigurationElementCollection - { - /// - /// Gets the type of the . - /// - /// - /// The of this collection. - /// - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.BasicMap; } - } - - /// - /// Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. - /// - /// - /// The name of the collection; otherwise, an empty string. The default is an empty string. - /// - protected override string ElementName - { - get { return "preset"; } - } - - /// - /// Gets or sets the - /// at the specified index within the collection. - /// - /// - /// The index at which to get the specified object. - /// - /// - /// The - /// at the specified index within the collection. - /// - public PresetElement this[int index] - { - get - { - return (PresetElement)BaseGet(index); - } - - set - { - if (this.BaseGet(index) != null) - { - this.BaseRemoveAt(index); - } - - this.BaseAdd(index, value); - } - } - - /// - /// Creates a new Preset configuration element. - /// - /// - /// A new PluginConfig configuration element. - /// - protected override ConfigurationElement CreateNewElement() - { - return new PresetElement(); - } - - /// - /// Gets the element key for a specified PluginElement configuration element. - /// - /// - /// The ConfigurationElement - /// to return the key for. - /// - /// - /// The element key for a specified PluginElement configuration element. - /// - protected override object GetElementKey(ConfigurationElement element) - { - return ((PresetElement)element).Name; - } - } - - /// - /// Represents a PluginElement configuration element within the configuration. - /// - public class PluginElement : ConfigurationElement - { - /// - /// Gets or sets the name of the plugin file. - /// - /// The name of the plugin. - [ConfigurationProperty("name", DefaultValue = "", IsRequired = true)] - public string Name - { - get { return (string)this["name"]; } - - set { this["name"] = value; } - } - - /// - /// Gets or sets the type of the plugin file. - /// - /// The full Type definition of the plugin - [ConfigurationProperty("type", DefaultValue = "", IsRequired = true)] - public string Type - { - get { return (string)this["type"]; } - - set { this["type"] = value; } - } - - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("settings", IsRequired = false)] - public SettingElementCollection Settings - { - get - { - return this["settings"] as SettingElementCollection; - } - } - } - - /// - /// Represents a PluginElementCollection collection configuration element within the configuration. - /// - public class PluginElementCollection : ConfigurationElementCollection - { - /// - /// Gets the type of the . - /// - /// - /// The of this collection. - /// - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.BasicMap; } - } - - /// - /// Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. - /// - /// - /// The name of the collection; otherwise, an empty string. The default is an empty string. - /// - protected override string ElementName - { - get { return "plugin"; } - } - - /// - /// Gets or sets the - /// at the specified index within the collection. - /// - /// - /// The index at which to get the specified object. - /// - /// - /// The - /// at the specified index within the collection. - /// - public PluginElement this[int index] - { - get - { - return (PluginElement)BaseGet(index); - } - - set - { - if (this.BaseGet(index) != null) - { - this.BaseRemoveAt(index); - } - - this.BaseAdd(index, value); - } - } - - /// - /// Creates a new Plugin configuration element. - /// - /// - /// A new Plugin configuration element. - /// - protected override ConfigurationElement CreateNewElement() - { - return new PluginElement(); - } - - /// - /// Gets the element key for a specified PluginElement configuration element. - /// - /// - /// The ConfigurationElement - /// to return the key for. - /// - /// - /// The element key for a specified PluginElement configuration element. - /// - protected override object GetElementKey(ConfigurationElement element) - { - return ((PluginElement)element).Name; - } - } - } -} diff --git a/old/src/ImageProcessor.Web/Configuration/ImageProcessorConfiguration.cs b/old/src/ImageProcessor.Web/Configuration/ImageProcessorConfiguration.cs deleted file mode 100644 index 06ef9434d..000000000 --- a/old/src/ImageProcessor.Web/Configuration/ImageProcessorConfiguration.cs +++ /dev/null @@ -1,454 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to allow the retrieval of ImageProcessor settings. -// -// -// -------------------------------------------------------------------------------------------------------------------- -namespace ImageProcessor.Web.Configuration -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Reflection; - using System.Web.Compilation; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Processors; - using ImageProcessor.Web.Caching; - using ImageProcessor.Web.Processors; - using ImageProcessor.Web.Services; - - /// - /// Encapsulates methods to allow the retrieval of ImageProcessor settings. - /// - /// - public sealed class ImageProcessorConfiguration - { - #region Fields - /// - /// A new instance of the class. - /// with lazy initialization. - /// - private static readonly Lazy Lazy = - new Lazy(() => new ImageProcessorConfiguration()); - - /// - /// A collection of the processing presets defined in the configuration. - /// for available plugins. - /// - private static readonly ConcurrentDictionary PresetSettings = new ConcurrentDictionary(); - - /// - /// The processing configuration section from the current application configuration. - /// - private static ImageProcessingSection imageProcessingSection; - - /// - /// The cache configuration section from the current application configuration. - /// - private static ImageCacheSection imageCacheSection; - - /// - /// The security configuration section from the current application configuration. - /// - private static ImageSecuritySection imageSecuritySection; - #endregion - - #region Constructors - /// - /// Prevents a default instance of the class from being created. - /// - private ImageProcessorConfiguration() - { - this.LoadGraphicsProcessors(); - this.LoadImageServices(); - this.LoadImageCache(); - } - #endregion - - #region Properties - /// - /// Gets the current instance of the class. - /// - public static ImageProcessorConfiguration Instance - { - get - { - return Lazy.Value; - } - } - - /// - /// Gets the list of available GraphicsProcessors. - /// - public IList GraphicsProcessors { get; private set; } - - /// - /// Gets the list of available ImageServices. - /// - public IList ImageServices { get; private set; } - - /// - /// Gets the current image cache. - /// - public Type ImageCache { get; private set; } - - /// - /// Gets the image cache max days. - /// - public int ImageCacheMaxDays { get; private set; } - - /// - /// Gets the image cache settings. - /// - public Dictionary ImageCacheSettings { get; private set; } - - /// - /// Gets a value indicating whether to preserve exif meta data. - /// - public bool PreserveExifMetaData - { - get - { - return GetImageProcessingSection().PreserveExifMetaData; - } - } - #endregion - - #region Methods - /// - /// Returns the processing instructions matching the preset defined in the configuration. - /// - /// - /// The name of the plugin to get the settings for. - /// - /// - /// The the processing instructions. - /// - public string GetPresetSettings(string name) - { - return PresetSettings.GetOrAdd( - name, - n => - { - ImageProcessingSection.PresetElement presetElement = GetImageProcessingSection() - .Presets - .Cast() - .FirstOrDefault(x => x.Name == n); - return presetElement != null ? presetElement.Value : null; - }); - } - - /// - /// Retrieves the security configuration section from the current application configuration. - /// - /// The security configuration section from the current application configuration. - internal ImageSecuritySection GetImageSecuritySection() - { - return imageSecuritySection ?? (imageSecuritySection = ImageSecuritySection.GetConfiguration()); - } - - /// - /// Retrieves the processing configuration section from the current application configuration. - /// - /// The processing configuration section from the current application configuration. - private static ImageProcessingSection GetImageProcessingSection() - { - return imageProcessingSection ?? (imageProcessingSection = ImageProcessingSection.GetConfiguration()); - } - - /// - /// Retrieves the caching configuration section from the current application configuration. - /// - /// The caching configuration section from the current application configuration. - private static ImageCacheSection GetImageCacheSection() - { - return imageCacheSection ?? (imageCacheSection = ImageCacheSection.GetConfiguration()); - } - - #region GraphicesProcessors - /// - /// Gets the list of available GraphicsProcessors. - /// - private void LoadGraphicsProcessors() - { - if (this.GraphicsProcessors == null) - { - if (GetImageProcessingSection().AutoLoadPlugins) - { - Type type = typeof(IWebGraphicsProcessor); - try - { - // Build a list of native IGraphicsProcessor instances. - List availableTypes = BuildManager.GetReferencedAssemblies() - .Cast() - .SelectMany(s => s.GetLoadableTypes()) - .Where(t => type.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract) - .ToList(); - - // Create them and add. - this.GraphicsProcessors = availableTypes.Select(x => (Activator.CreateInstance(x) as IWebGraphicsProcessor)).ToList(); - - // Add the available settings. - foreach (IWebGraphicsProcessor webProcessor in this.GraphicsProcessors) - { - webProcessor.Processor.Settings = this.GetPluginSettings(webProcessor.GetType().Name); - } - } - catch (ReflectionTypeLoadException) - { - this.LoadGraphicsProcessorsFromConfiguration(); - } - } - else - { - this.LoadGraphicsProcessorsFromConfiguration(); - } - } - } - - /// - /// Loads graphics processors from configuration. - /// - /// - /// Thrown when an cannot be loaded. - /// - private void LoadGraphicsProcessorsFromConfiguration() - { - ImageProcessingSection.PluginElementCollection pluginConfigs = imageProcessingSection.Plugins; - this.GraphicsProcessors = new List(); - foreach (ImageProcessingSection.PluginElement pluginConfig in pluginConfigs) - { - Type type = Type.GetType(pluginConfig.Type); - - if (type == null) - { - throw new TypeLoadException("Couldn't load IWebGraphicsProcessor: " + pluginConfig.Type); - } - - this.GraphicsProcessors.Add(Activator.CreateInstance(type) as IWebGraphicsProcessor); - } - - // Add the available settings. - foreach (IWebGraphicsProcessor webProcessor in this.GraphicsProcessors) - { - webProcessor.Processor.Settings = this.GetPluginSettings(webProcessor.GetType().Name); - } - } - - /// - /// Returns the for the given plugin. - /// - /// - /// The name of the plugin to get the settings for. - /// - /// - /// The for the given plugin. - /// - private Dictionary GetPluginSettings(string name) - { - ImageProcessingSection.PluginElement pluginElement = GetImageProcessingSection() - .Plugins - .Cast() - .FirstOrDefault(x => x.Name == name); - - Dictionary settings; - - if (pluginElement != null) - { - settings = pluginElement.Settings - .Cast() - .ToDictionary(setting => setting.Key, setting => setting.Value); - } - else - { - settings = new Dictionary(); - } - - return settings; - } - #endregion - - #region ImageServices - /// - /// Gets the list of available ImageServices. - /// - private void LoadImageServices() - { - if (this.ImageServices == null) - { - if (this.GetImageSecuritySection().AutoLoadServices) - { - Type type = typeof(IImageService); - try - { - // Build a list of native IGraphicsProcessor instances. - List availableTypes = BuildManager.GetReferencedAssemblies() - .Cast() - .SelectMany(s => s.GetLoadableTypes()) - .Where(t => type.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract) - .ToList(); - - // Create them and add. - this.ImageServices = availableTypes.Select(x => (Activator.CreateInstance(x) as IImageService)).ToList(); - - // Add the available settings. - foreach (IImageService service in this.ImageServices) - { - string name = service.GetType().Name; - service.Settings = this.GetServiceSettings(name); - service.WhiteList = this.GetServiceWhitelist(name); - } - } - catch (ReflectionTypeLoadException) - { - this.LoadImageServicesFromConfiguration(); - } - } - else - { - this.LoadImageServicesFromConfiguration(); - } - } - } - - /// - /// Loads image services from configuration. - /// - /// - /// Thrown when an cannot be loaded. - /// - private void LoadImageServicesFromConfiguration() - { - ImageSecuritySection.ServiceElementCollection services = imageSecuritySection.ImageServices; - this.ImageServices = new List(); - foreach (ImageSecuritySection.ServiceElement config in services) - { - Type type = Type.GetType(config.Type); - - if (type == null) - { - throw new TypeLoadException("Couldn't load IImageService: " + config.Type); - } - - IImageService imageService = Activator.CreateInstance(type) as IImageService; - if (!string.IsNullOrWhiteSpace(config.Prefix)) - { - if (imageService != null) - { - imageService.Prefix = config.Prefix; - } - } - - this.ImageServices.Add(imageService); - } - - // Add the available settings. - foreach (IImageService service in this.ImageServices) - { - string name = service.GetType().Name; - service.Settings = this.GetServiceSettings(name); - service.WhiteList = this.GetServiceWhitelist(name); - } - } - - /// - /// Returns the for the given plugin. - /// - /// - /// The name of the plugin to get the settings for. - /// - /// - /// The for the given plugin. - /// - private Dictionary GetServiceSettings(string name) - { - ImageSecuritySection.ServiceElement serviceElement = this.GetImageSecuritySection() - .ImageServices - .Cast() - .FirstOrDefault(x => x.Name == name); - - Dictionary settings; - - if (serviceElement != null) - { - settings = serviceElement.Settings - .Cast() - .ToDictionary(setting => setting.Key, setting => setting.Value); - } - else - { - settings = new Dictionary(); - } - - return settings; - } - - /// - /// Gets the whitelist of for the given service. - /// - /// - /// The name of the service to return the whitelist for. - /// - /// - /// The array containing the whitelist. - /// - private Uri[] GetServiceWhitelist(string name) - { - ImageSecuritySection.ServiceElement serviceElement = this.GetImageSecuritySection() - .ImageServices - .Cast() - .FirstOrDefault(x => x.Name == name); - - Uri[] whitelist = { }; - if (serviceElement != null) - { - whitelist = serviceElement.WhiteList.Cast() - .Select(s => s.Url).ToArray(); - } - - return whitelist; - } - #endregion - - #region ImageCaches - /// - /// Gets the currently assigned . - /// - private void LoadImageCache() - { - if (this.ImageCache == null) - { - string curentCache = GetImageCacheSection().CurrentCache; - ImageCacheSection.CacheElementCollection caches = imageCacheSection.ImageCaches; - - foreach (ImageCacheSection.CacheElement cache in caches) - { - if (cache.Name == curentCache) - { - Type type = Type.GetType(cache.Type); - - if (type == null) - { - throw new TypeLoadException("Couldn't load IImageCache: " + cache.Type); - } - - this.ImageCache = type; - this.ImageCacheMaxDays = cache.MaxDays; - this.ImageCacheSettings = cache.Settings - .Cast() - .ToDictionary(setting => setting.Key, setting => setting.Value); - break; - } - } - } - } - #endregion - #endregion - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Configuration/ImageSecuritySection.cs b/old/src/ImageProcessor.Web/Configuration/ImageSecuritySection.cs deleted file mode 100644 index 9cceb317a..000000000 --- a/old/src/ImageProcessor.Web/Configuration/ImageSecuritySection.cs +++ /dev/null @@ -1,319 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents an image security section within a configuration file. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Configuration -{ - using System; - using System.Configuration; - using System.IO; - using System.Xml; - - using ImageProcessor.Web.Helpers; - - /// - /// Represents an image security section within a configuration file. - /// - public sealed class ImageSecuritySection : ConfigurationSection - { - /// - /// Gets the - /// - /// The - [ConfigurationProperty("cors", IsRequired = false)] - public CORSOriginElement CORSOrigin - { - get - { - object o = this["cors"]; - return o as CORSOriginElement; - } - } - - /// - /// Gets the - /// - /// The - [ConfigurationProperty("services", IsRequired = true)] - public ServiceElementCollection ImageServices - { - get - { - object o = this["services"]; - return o as ServiceElementCollection; - } - } - - /// - /// Gets or sets a value indicating whether to auto load services. - /// - public bool AutoLoadServices { get; set; } - - /// - /// Retrieves the security configuration section from the current application configuration. - /// - /// The cache configuration section from the current application configuration. - public static ImageSecuritySection GetConfiguration() - { - ImageSecuritySection imageSecuritySection = ConfigurationManager.GetSection("imageProcessor/security") as ImageSecuritySection; - - if (imageSecuritySection != null) - { - imageSecuritySection.AutoLoadServices = false; - return imageSecuritySection; - } - - string section = ResourceHelpers.ResourceAsString("ImageProcessor.Web.Configuration.Resources.security.config.transform"); - XmlReader reader = new XmlTextReader(new StringReader(section)); - imageSecuritySection = new ImageSecuritySection(); - imageSecuritySection.DeserializeSection(reader); - imageSecuritySection.AutoLoadServices = true; - return imageSecuritySection; - } - - /// - /// Represents a ServiceElement configuration element within the configuration. - /// - public class ServiceElement : ConfigurationElement - { - /// - /// Gets or sets the name of the service. - /// - /// The name of the service. - [ConfigurationProperty("name", DefaultValue = "", IsRequired = true)] - public string Name - { - get { return (string)this["name"]; } - - set { this["name"] = value; } - } - - /// - /// Gets or sets the prefix of the service. - /// - /// The prefix of the service. - [ConfigurationProperty("prefix", DefaultValue = "", IsRequired = false)] - public string Prefix - { - get { return (string)this["prefix"]; } - - set { this["prefix"] = value; } - } - - /// - /// Gets or sets the type of the service. - /// - /// The full Type definition of the service - [ConfigurationProperty("type", DefaultValue = "", IsRequired = true)] - public string Type - { - get { return (string)this["type"]; } - - set { this["type"] = value; } - } - - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("settings", IsRequired = false)] - public SettingElementCollection Settings - { - get - { - return this["settings"] as SettingElementCollection; - } - } - - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("whitelist", IsRequired = false)] - public WhiteListElementCollection WhiteList - { - get - { - return this["whitelist"] as WhiteListElementCollection; - } - } - } - - /// - /// Represents a collection of elements within the configuration. - /// - public class ServiceElementCollection : ConfigurationElementCollection - { - /// - /// Gets the type of the . - /// - /// - /// The of this collection. - /// - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.BasicMap; } - } - - /// - /// Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. - /// - /// - /// The name of the collection; otherwise, an empty string. The default is an empty string. - /// - protected override string ElementName - { - get { return "service"; } - } - - /// - /// Gets or sets the - /// at the specified index within the collection. - /// - /// The index at which to get the specified object. - /// - /// The - /// at the specified index within the collection. - /// - public ServiceElement this[int index] - { - get - { - return (ServiceElement)BaseGet(index); - } - - set - { - if (this.BaseGet(index) != null) - { - this.BaseRemoveAt(index); - } - - this.BaseAdd(index, value); - } - } - - /// - /// When overridden in a derived class, creates a new . - /// - /// - /// A new . - /// - protected override ConfigurationElement CreateNewElement() - { - return new ServiceElement(); - } - - /// - /// Gets the element key for a specified configuration element when overridden in a derived class. - /// - /// - /// An that acts as the key for the specified . - /// - /// The to return the key for. - protected override object GetElementKey(ConfigurationElement element) - { - return ((ServiceElement)element).Name; - } - } - - /// - /// Represents a CORSOriginsElement configuration element within the configuration. - /// - public class CORSOriginElement : ConfigurationElement - { - /// - /// Gets the . - /// - /// - /// The . - /// - [ConfigurationProperty("whitelist", IsRequired = false)] - public WhiteListElementCollection WhiteList - { - get - { - return this["whitelist"] as WhiteListElementCollection; - } - } - } - - /// - /// Represents a whitelist collection configuration element within the configuration. - /// - public class WhiteListElementCollection : ConfigurationElementCollection - { - /// - /// Gets or sets the whitelist item at the given index. - /// - /// The index of the whitelist item to get. - /// The whitelist item at the given index. - public SafeUrl this[int index] - { - get - { - return this.BaseGet(index) as SafeUrl; - } - - set - { - if (this.BaseGet(index) != null) - { - this.BaseRemoveAt(index); - } - - this.BaseAdd(index, value); - } - } - - /// - /// Creates a new SafeURL configuration element. - /// - /// - /// A new SafeURL configuration element. - /// - protected override ConfigurationElement CreateNewElement() - { - return new SafeUrl(); - } - - /// - /// Gets the element key for a specified whitelist configuration element. - /// - /// The ConfigurationElement to return the key for. - /// The element key for a specified whitelist configuration element. - protected override object GetElementKey(ConfigurationElement element) - { - return ((SafeUrl)element).Url; - } - } - - /// - /// Represents a whitelist configuration element within the configuration. - /// - public class SafeUrl : ConfigurationElement - { - /// - /// Gets or sets the url of the white listed file. - /// - /// The url of the white listed file. - [ConfigurationProperty("url", DefaultValue = "", IsRequired = true)] - public Uri Url - { - get { return new Uri(this["url"].ToString(), UriKind.RelativeOrAbsolute); } - - set { this["url"] = value; } - } - } - } -} diff --git a/old/src/ImageProcessor.Web/Configuration/Resources/cache.config.transform b/old/src/ImageProcessor.Web/Configuration/Resources/cache.config.transform deleted file mode 100644 index 8cad5133d..000000000 --- a/old/src/ImageProcessor.Web/Configuration/Resources/cache.config.transform +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/old/src/ImageProcessor.Web/Configuration/Resources/processing.config.transform b/old/src/ImageProcessor.Web/Configuration/Resources/processing.config.transform deleted file mode 100644 index a908e46c5..000000000 --- a/old/src/ImageProcessor.Web/Configuration/Resources/processing.config.transform +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Configuration/Resources/security.config.transform b/old/src/ImageProcessor.Web/Configuration/Resources/security.config.transform deleted file mode 100644 index 1160ce63b..000000000 --- a/old/src/ImageProcessor.Web/Configuration/Resources/security.config.transform +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/old/src/ImageProcessor.Web/Configuration/Shared/SettingElement.cs b/old/src/ImageProcessor.Web/Configuration/Shared/SettingElement.cs deleted file mode 100644 index 804d77ec0..000000000 --- a/old/src/ImageProcessor.Web/Configuration/Shared/SettingElement.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents a SettingElement configuration element within the configuration. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Configuration -{ - using System.Configuration; - - /// - /// Represents a SettingElement configuration element within the configuration. - /// - public class SettingElement : ConfigurationElement - { - /// - /// Gets or sets the key of the plugin setting. - /// - /// The key of the plugin setting. - [ConfigurationProperty("key", IsRequired = true, IsKey = true)] - public string Key - { - get - { - return this["key"] as string; - } - - set - { - this["key"] = value; - } - } - - /// - /// Gets or sets the value of the plugin setting. - /// - /// The value of the plugin setting. - [ConfigurationProperty("value", IsRequired = true)] - public string Value - { - get - { - return (string)this["value"]; - } - - set - { - this["value"] = value; - } - } - } -} diff --git a/old/src/ImageProcessor.Web/Configuration/Shared/SettingElementCollection.cs b/old/src/ImageProcessor.Web/Configuration/Shared/SettingElementCollection.cs deleted file mode 100644 index d060a200e..000000000 --- a/old/src/ImageProcessor.Web/Configuration/Shared/SettingElementCollection.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents a SettingElementCollection collection configuration element within the configuration. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Configuration -{ - using System.Configuration; - using System.Linq; - - /// - /// Represents a SettingElementCollection collection configuration element within the configuration. - /// - public class SettingElementCollection : ConfigurationElementCollection - { - /// - /// Gets the type of the . - /// - /// - /// The of this collection. - /// - public override ConfigurationElementCollectionType CollectionType - { - get { return ConfigurationElementCollectionType.BasicMap; } - } - - /// - /// Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. - /// - /// - /// The name of the collection; otherwise, an empty string. The default is an empty string. - /// - protected override string ElementName - { - get { return "setting"; } - } - - /// - /// Gets or sets the - /// at the specified index within the collection. - /// - /// The index at which to get the specified object. - /// - /// The - /// at the specified index within the collection. - /// - public SettingElement this[int index] - { - get - { - return (SettingElement)BaseGet(index); - } - - set - { - if (this.BaseGet(index) != null) - { - this.BaseRemoveAt(index); - } - - this.BaseAdd(index, value); - } - } - - /// - /// Returns the setting element with the specified key. - /// - /// the key representing the element - /// the setting element - public new SettingElement this[string key] - { - get { return (SettingElement)BaseGet(key); } - } - - /// - /// Returns a value indicating whether the settings collection contains the - /// given object. - /// - /// The key to identify the setting. - /// True if the collection contains the key; otherwise false. - public bool ContainsKey(string key) - { - object[] keys = BaseGetAllKeys(); - - return keys.Any(obj => (string)obj == key); - } - - /// - /// Gets the element key for a specified PluginElement configuration element. - /// - /// - /// The ConfigurationElement - /// to return the key for. - /// - /// The element key for a specified PluginElement configuration element. - protected override object GetElementKey(ConfigurationElement element) - { - return ((SettingElement)element).Key; - } - - /// - /// Creates a new SettingElement configuration element. - /// - /// - /// A new SettingElement configuration element. - /// - protected override ConfigurationElement CreateNewElement() - { - return new SettingElement(); - } - } -} diff --git a/old/src/ImageProcessor.Web/Extensions/DirectoryInfoExtensions.cs b/old/src/ImageProcessor.Web/Extensions/DirectoryInfoExtensions.cs deleted file mode 100644 index 0ad55ca60..000000000 --- a/old/src/ImageProcessor.Web/Extensions/DirectoryInfoExtensions.cs +++ /dev/null @@ -1,86 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides extension methods to the type. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Extensions -{ - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Threading.Tasks; - - /// - /// Provides extension methods to the type. - /// - public static class DirectoryInfoExtensions - { - /// - /// Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option. - /// Will return an empty enumerable on exception. Quick and dirty but does what I need just now. - /// - /// - /// The that this method extends. - /// - /// - /// The search string to match against the names of directories. This parameter can contain a combination of valid literal path - /// and wildcard (* and ?) characters (see Remarks), but doesn't support regular expressions. The default pattern is "*", which returns all files. - /// - /// - /// One of the enumeration values that specifies whether the search operation should include only - /// the current directory or all subdirectories. The default value is TopDirectoryOnly. - /// - /// - /// An enumerable collection of directories that matches searchPattern and searchOption. - /// - public static Task> SafeEnumerateDirectoriesAsync( - this DirectoryInfo directoryInfo, - string searchPattern = "*", - SearchOption searchOption = SearchOption.TopDirectoryOnly) - { - return Task.Run(() => SafeEnumerateDirectories(directoryInfo, searchPattern, searchOption)); - } - - /// - /// Returns an enumerable collection of directory information that matches a specified search pattern and search subdirectory option. - /// Will return an empty enumerable on exception. Quick and dirty but does what I need just now. - /// - /// - /// The that this method extends. - /// - /// - /// The search string to match against the names of directories. This parameter can contain a combination of valid literal path - /// and wildcard (* and ?) characters (see Remarks), but doesn't support regular expressions. The default pattern is "*", which returns all files. - /// - /// - /// One of the enumeration values that specifies whether the search operation should include only - /// the current directory or all subdirectories. The default value is TopDirectoryOnly. - /// - /// - /// An enumerable collection of directories that matches searchPattern and searchOption. - /// - public static IEnumerable SafeEnumerateDirectories( - this DirectoryInfo directoryInfo, - string searchPattern = "*", - SearchOption searchOption = SearchOption.TopDirectoryOnly) - { - IEnumerable directories; - - try - { - directories = directoryInfo.EnumerateDirectories(searchPattern, searchOption); - } - catch - { - return Enumerable.Empty(); - } - - return directories; - } - } -} diff --git a/old/src/ImageProcessor.Web/Extensions/StringExtensions.cs b/old/src/ImageProcessor.Web/Extensions/StringExtensions.cs deleted file mode 100644 index 5ec1fdf4b..000000000 --- a/old/src/ImageProcessor.Web/Extensions/StringExtensions.cs +++ /dev/null @@ -1,143 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates a series of time saving extension methods to the class. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Extensions -{ - using System; - using System.Globalization; - using System.Linq; - using System.Security.Cryptography; - using System.Text; - using System.Text.RegularExpressions; - - /// - /// Encapsulates a series of time saving extension methods to the class. - /// - public static class StringExtensions - { - #region Cryptography - /// - /// Creates an MD5 fingerprint of the String. - /// - /// The String instance that this method extends. - /// An MD5 fingerprint of the String. - public static string ToMD5Fingerprint(this string expression) - { - byte[] bytes = Encoding.Unicode.GetBytes(expression.ToCharArray()); - - using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) - { - byte[] hash = md5.ComputeHash(bytes); - - // Concatenate the hash bytes into one long String. - return hash.Aggregate( - new StringBuilder(32), - (sb, b) => sb.Append(b.ToString("X2", CultureInfo.InvariantCulture))) - .ToString().ToLowerInvariant(); - } - } - - /// - /// Creates an SHA1 fingerprint of the String. - /// - /// The String instance that this method extends. - /// An SHA1 fingerprint of the String. - public static string ToSHA1Fingerprint(this string expression) - { - byte[] bytes = Encoding.ASCII.GetBytes(expression.ToCharArray()); - - using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) - { - byte[] hash = sha1.ComputeHash(bytes); - - // Concatenate the hash bytes into one long String. - return hash.Aggregate( - new StringBuilder(40), - (sb, b) => sb.Append(b.ToString("X2", CultureInfo.InvariantCulture))) - .ToString().ToLowerInvariant(); - } - } - #endregion - - #region Numbers - /// - /// Creates an array of integers scraped from the String. - /// - /// The String instance that this method extends. - /// An array of integers scraped from the String. - public static int[] ToPositiveIntegerArray(this string expression) - { - if (string.IsNullOrWhiteSpace(expression)) - { - throw new ArgumentNullException("expression"); - } - - Regex regex = new Regex(@"[\d+]+(?=[,-])|[\d+]+(?![,-])", RegexOptions.Compiled); - - MatchCollection matchCollection = regex.Matches(expression); - - // Get the collections. - int count = matchCollection.Count; - int[] matches = new int[count]; - - // Loop and parse the int values. - for (int i = 0; i < count; i++) - { - matches[i] = int.Parse(matchCollection[i].Value, CultureInfo.InvariantCulture); - } - - return matches; - } - - /// - /// Creates an array of floats scraped from the String. - /// - /// The String instance that this method extends. - /// An array of floats scraped from the String. - public static float[] ToPositiveFloatArray(this string expression) - { - if (string.IsNullOrWhiteSpace(expression)) - { - throw new ArgumentNullException("expression"); - } - - Regex regex = new Regex(@"[\d+\.]+(?=[,-])|[\d+\.]+(?![,-])", RegexOptions.Compiled); - - MatchCollection matchCollection = regex.Matches(expression); - - // Get the collections. - int count = matchCollection.Count; - float[] matches = new float[count]; - - // Loop and parse the int values. - for (int i = 0; i < count; i++) - { - matches[i] = float.Parse(matchCollection[i].Value, CultureInfo.InvariantCulture); - } - - return matches; - } - #endregion - - #region Files and Paths - /// - /// Checks the string to see whether the value is a valid virtual path name. - /// - /// The String instance that this method extends. - /// True if the given string is a valid virtual path name - public static bool IsValidVirtualPathName(this string expression) - { - Uri uri; - - return Uri.TryCreate(expression, UriKind.Relative, out uri) && uri.IsWellFormedOriginalString(); - } - #endregion - } -} diff --git a/old/src/ImageProcessor.Web/Extensions/TypeInitializationExtensions.cs b/old/src/ImageProcessor.Web/Extensions/TypeInitializationExtensions.cs deleted file mode 100644 index bd59d1b3b..000000000 --- a/old/src/ImageProcessor.Web/Extensions/TypeInitializationExtensions.cs +++ /dev/null @@ -1,180 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Extensions methods for for creating instances of types faster than -// using reflection. Modified from the original class at. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Extensions -{ - using System; - using System.Collections.Concurrent; - using System.Linq; - using System.Linq.Expressions; - using System.Reflection; - - /// - /// Extensions methods for for creating instances of types faster than - /// using reflection. Modified from the original class at. - /// - /// - internal static class TypeInitializationExtensions - { - /// - /// Returns an instance of the on which the method is invoked. - /// - /// The type on which the method was invoked. - /// An instance of the . - public static object GetInstance(this Type type) - { - // This is about as quick as it gets. - return Activator.CreateInstance(type); - } - - /// - /// Returns an instance of the on which the method is invoked. - /// - /// The type of the argument to pass to the constructor. - /// The type on which the method was invoked. - /// The argument to pass to the constructor. - /// An instance of the given . - public static object GetInstance(this Type type, TArg argument) - { - return GetInstance(type, argument, null); - } - - /// - /// Returns an instance of the on which the method is invoked. - /// - /// The type of the first argument to pass to the constructor. - /// The type of the second argument to pass to the constructor. - /// The type on which the method was invoked. - /// The first argument to pass to the constructor. - /// The second argument to pass to the constructor. - /// An instance of the given . - public static object GetInstance(this Type type, TArg1 argument1, TArg2 argument2) - { - return GetInstance(type, argument1, argument2, null); - } - - /// - /// Returns an instance of the on which the method is invoked. - /// - /// The type of the first argument to pass to the constructor. - /// The type of the second argument to pass to the constructor. - /// The type of the third argument to pass to the constructor. - /// The type on which the method was invoked. - /// The first argument to pass to the constructor. - /// The second argument to pass to the constructor. - /// The third argument to pass to the constructor. - /// An instance of the given . - public static object GetInstance( - this Type type, - TArg1 argument1, - TArg2 argument2, - TArg3 argument3) - { - return InstanceCreationFactory - .CreateInstanceOf(type, argument1, argument2, argument3); - } - - /// - /// The instance creation factory for creating instances. - /// - /// The type of the first argument to pass to the constructor. - /// The type of the second argument to pass to the constructor. - /// The type of the third argument to pass to the constructor. - private static class InstanceCreationFactory - { - /// - /// This dictionary will hold a cache of object-creation functions, keyed by the Type to create: - /// - private static readonly ConcurrentDictionary> InstanceCreationMethods = new ConcurrentDictionary>(); - - /// - /// The create instance of. - /// - /// - /// The type. - /// - /// The first argument to pass to the constructor. - /// The second argument to pass to the constructor. - /// The third argument to pass to the constructor. - /// - /// The . - /// - public static object CreateInstanceOf(Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3) - { - CacheInstanceCreationMethodIfRequired(type); - - return InstanceCreationMethods[type].Invoke(arg1, arg2, arg3); - } - - /// - /// Caches the instance creation method. - /// - /// - /// The who's constructor to cache. - /// - private static void CacheInstanceCreationMethodIfRequired(Type type) - { - // Bail out if we've already cached the instance creation method: - Func cached; - if (InstanceCreationMethods.TryGetValue(type, out cached)) - { - return; - } - - Type[] argumentTypes = { typeof(TArg1), typeof(TArg2), typeof(TArg3) }; - - // Get a collection of the constructor argument Types we've been given; ignore any - // arguments which are of the 'ignore this' Type: - Type[] constructorArgumentTypes = argumentTypes.Where(t => t != typeof(TypeToIgnore)).ToArray(); - - // Get the Constructor which matches the given argument Types: - ConstructorInfo constructor = type.GetConstructor( - BindingFlags.Instance | BindingFlags.Public, - null, - CallingConventions.HasThis, - constructorArgumentTypes, - new ParameterModifier[0]); - - // Get a set of Expressions representing the parameters which will be passed to the Func: - ParameterExpression[] lamdaParameterExpressions = - { - Expression.Parameter(typeof(TArg1), "param1"), - Expression.Parameter(typeof(TArg2), "param2"), - Expression.Parameter(typeof(TArg3), "param3") - }; - - // Get a set of Expressions representing the parameters which will be passed to the constructor: - ParameterExpression[] constructorParameterExpressions = - lamdaParameterExpressions.Take(constructorArgumentTypes.Length).ToArray(); - - // Get an Expression representing the constructor call, passing in the constructor parameters: - NewExpression constructorCallExpression = Expression.New(constructor, constructorParameterExpressions.Cast()); - - // Compile the Expression into a Func which takes three arguments and returns the constructed object: - Func constructorCallingLambda = - Expression.Lambda>( - constructorCallExpression, - lamdaParameterExpressions).Compile(); - - InstanceCreationMethods.TryAdd(type, constructorCallingLambda); - } - } - - /// - /// To allow for overloads with differing numbers of arguments, we flag arguments which should be - /// ignored by using this Type: - /// - private class TypeToIgnore - { - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/AsyncDuplicateLock.cs b/old/src/ImageProcessor.Web/Helpers/AsyncDuplicateLock.cs deleted file mode 100644 index 47f14c81c..000000000 --- a/old/src/ImageProcessor.Web/Helpers/AsyncDuplicateLock.cs +++ /dev/null @@ -1,134 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Throttles duplicate requests. -// -// -------------------------------------------------------------------------------------------------------------------- -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Collections.Concurrent; - using System.Threading; - using System.Threading.Tasks; - - /// - /// Throttles duplicate requests. - /// Based loosely on - /// - public sealed class AsyncDuplicateLock - { - /// - /// The collection of semaphore slims. - /// - private static readonly ConcurrentDictionary SemaphoreSlims - = new ConcurrentDictionary(); - - /// - /// Locks against the given key. - /// - /// - /// The key that identifies the current object. - /// - /// - /// The disposable . - /// - public IDisposable Lock(object key) - { - DisposableScope releaser = new DisposableScope( - key, - s => - { - SemaphoreSlim locker; - if (SemaphoreSlims.TryRemove(s, out locker)) - { - locker.Release(); - locker.Dispose(); - } - }); - - SemaphoreSlim semaphore = SemaphoreSlims.GetOrAdd(key, new SemaphoreSlim(1, 1)); - semaphore.Wait(); - return releaser; - } - - /// - /// Asynchronously locks against the given key. - /// - /// - /// The key that identifies the current object. - /// - /// - /// The disposable . - /// - public Task LockAsync(object key) - { - DisposableScope releaser = new DisposableScope( - key, - s => - { - SemaphoreSlim locker; - if (SemaphoreSlims.TryRemove(s, out locker)) - { - locker.Release(); - locker.Dispose(); - } - }); - - Task releaserTask = Task.FromResult(releaser as IDisposable); - SemaphoreSlim semaphore = SemaphoreSlims.GetOrAdd(key, new SemaphoreSlim(1, 1)); - - Task waitTask = semaphore.WaitAsync(); - - return waitTask.IsCompleted - ? releaserTask - : waitTask.ContinueWith( - (_, r) => (IDisposable)r, - releaser, - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - } - - /// - /// The disposable scope. - /// - private sealed class DisposableScope : IDisposable - { - /// - /// The key - /// - private readonly object key; - - /// - /// The close scope action. - /// - private readonly Action closeScopeAction; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The key. - /// - /// - /// The close scope action. - /// - public DisposableScope(object key, Action closeScopeAction) - { - this.key = key; - this.closeScopeAction = closeScopeAction; - } - - /// - /// The dispose. - /// - public void Dispose() - { - this.closeScopeAction(this.key); - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Helpers/CommonParameterParserUtility.cs b/old/src/ImageProcessor.Web/Helpers/CommonParameterParserUtility.cs deleted file mode 100644 index c47fc1611..000000000 --- a/old/src/ImageProcessor.Web/Helpers/CommonParameterParserUtility.cs +++ /dev/null @@ -1,158 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// // Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Globalization; - using System.Text; - using System.Text.RegularExpressions; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Web.Extensions; - - /// - /// Encapsulates methods to correctly parse querystring parameters. - /// - public static class CommonParameterParserUtility - { - /// - /// The collection of known colors. - /// - private static readonly Dictionary KnownColors = new Dictionary(); - - /// - /// The regular expression to search strings for colors. - /// - private static readonly Regex ColorRegex = BuildColorRegex(); - - /// - /// The regular expression to search strings for angles. - /// - private static readonly Regex AngleRegex = new Regex(@"(^(rotate(bounded)?|angle)|[^.](&,)?rotate(bounded)?|angle)(=|-)[^&|,]+", RegexOptions.Compiled); - - /// - /// The regular expression to search strings for values between 1 and 100. - /// - private static readonly Regex In100RangeRegex = new Regex(@"(-?0*(?:100|[1-9][0-9]?))", RegexOptions.Compiled); - - /// - /// Returns the correct containing the angle for the given string. - /// - /// - /// The input string containing the value to parse. - /// - /// - /// The correct containing the angle for the given string. - /// - public static float ParseAngle(string input) - { - foreach (Match match in AngleRegex.Matches(input)) - { - // Split on angle - float angle; - string value = match.Value; - value = match.Value.ToUpperInvariant().Contains("ANGLE") - ? value.Substring(value.IndexOf("-", StringComparison.Ordinal) + 1) - : match.Value.Split('=')[1]; - - float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out angle); - return angle; - } - - // No rotate - matches the RotateLayer default. - return 0; - } - - /// - /// Returns the correct for the given string. - /// - /// - /// The input string containing the value to parse. - /// - /// - /// The correct - /// - public static Color ParseColor(string input) - { - foreach (Match match in ColorRegex.Matches(input)) - { - string value = match.Value; - - if (KnownColors.ContainsKey(value)) - { - return Color.FromKnownColor(KnownColors[value]); - } - - if (value.Contains(",")) - { - int[] split = value.ToPositiveIntegerArray(); - byte red = split[0].ToByte(); - byte green = split[1].ToByte(); - byte blue = split[2].ToByte(); - byte alpha = split[3].ToByte(); - - return Color.FromArgb(alpha, red, green, blue); - } - - // Split on color-hex - return ColorTranslator.FromHtml("#" + value); - } - - return Color.Transparent; - } - - /// - /// Returns the correct for the given string. - /// - /// - /// The input string containing the value to parse. - /// - /// - /// The correct between -100 and 100. - /// - public static int ParseIn100Range(string input) - { - int value = 0; - foreach (Match match in In100RangeRegex.Matches(input)) - { - value = int.Parse(match.Value, CultureInfo.InvariantCulture); - } - - return value; - } - - /// - /// Builds a regular expression for the three main colour types. - /// - /// - /// The to match colors. - /// - private static Regex BuildColorRegex() - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(@"(\d+,\d+,\d+,\d+|([0-9a-fA-F]{3}){1,2}|("); - - KnownColor[] knownColors = (KnownColor[])Enum.GetValues(typeof(KnownColor)); - - for (int i = 0; i < knownColors.Length; i++) - { - KnownColor knownColor = knownColors[i]; - string name = knownColor.ToString().ToLowerInvariant(); - - KnownColors.Add(name, knownColor); - - stringBuilder.Append(i > 0 ? "|" + name : name); - } - - stringBuilder.Append("))"); - - return new Regex(stringBuilder.ToString(), RegexOptions.IgnoreCase); - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/ImageHelpers.cs b/old/src/ImageProcessor.Web/Helpers/ImageHelpers.cs deleted file mode 100644 index f784cccf6..000000000 --- a/old/src/ImageProcessor.Web/Helpers/ImageHelpers.cs +++ /dev/null @@ -1,143 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The image helpers. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System.Linq; - using System.Text; - using System.Text.RegularExpressions; - using ImageProcessor.Configuration; - using ImageProcessor.Imaging.Formats; - using ImageProcessor.Web.Configuration; - using ImageProcessor.Web.Processors; - - /// - /// The image helpers. - /// - public static class ImageHelpers - { - /// - /// The regex pattern. - /// - public static readonly string ExtensionRegexPattern = BuildExtensionRegexPattern(); - - /// - /// The image format regex. - /// - private static readonly Regex FormatRegex = new Regex(@"(\.?)(png8|" + ExtensionRegexPattern + ")", RegexOptions.IgnoreCase | RegexOptions.RightToLeft); - - /// - /// The image format regex for matching the file format at the end of a string. - /// - private static readonly Regex EndFormatRegex = new Regex(@"(\.)" + ExtensionRegexPattern + "$", RegexOptions.IgnoreCase | RegexOptions.RightToLeft); - - /// - /// Checks a given string to check whether the value contains a valid image extension. - /// - /// The string containing the filename to check. - /// True the value contains a valid image extension, otherwise false. - public static bool IsValidImageExtension(string fileName) - { - return EndFormatRegex.IsMatch(fileName); - } - - /// - /// Returns the correct file extension for the given string input - /// - /// - /// The string to parse. - /// - /// - /// The querystring containing instructions. - /// - /// - /// The correct file extension for the given string input if it can find one; otherwise an empty string. - /// - public static string GetExtension(string fullPath, string queryString) - { - Match match = null; - - // First check to see if the format processor is being used and test against that. - IWebGraphicsProcessor format = ImageProcessorConfiguration.Instance.GraphicsProcessors - .FirstOrDefault(p => typeof(Format) == p.GetType()); - - if (format != null) - { - match = format.RegexPattern.Match(queryString); - } - - if (match == null || !match.Success) - { - // Test against the path minus the querystring so any other - // processors don't interere. - string trimmed = fullPath; - if (queryString != null) - { - trimmed = trimmed.Replace(queryString, string.Empty); - } - - match = FormatRegex.Match(trimmed); - } - - if (match.Success) - { - string value = match.Value; - - // Clip if format processor match. - if (match.Value.Contains("=")) - { - value = value.Split('=')[1]; - } - - // Ah the enigma that is the png file. - if (value.ToLowerInvariant().EndsWith("png8")) - { - return "png"; - } - - return value; - } - - return string.Empty; - } - - /// - /// Builds a regular expression from the type, this allows extensibility. - /// - /// - /// The to match matrix filters. - /// - private static string BuildExtensionRegexPattern() - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append("("); - int counter = 0; - foreach (ISupportedImageFormat imageFormat in ImageProcessorBootstrapper.Instance.SupportedImageFormats) - { - foreach (string fileExtension in imageFormat.FileExtensions) - { - if (counter == 0) - { - stringBuilder.Append(fileExtension.ToLowerInvariant()); - } - else - { - stringBuilder.AppendFormat("|{0}", fileExtension.ToLowerInvariant()); - } - } - - counter++; - } - - stringBuilder.Append(")"); - return stringBuilder.ToString(); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Helpers/NativeMethods.cs b/old/src/ImageProcessor.Web/Helpers/NativeMethods.cs deleted file mode 100644 index 9e983438c..000000000 --- a/old/src/ImageProcessor.Web/Helpers/NativeMethods.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides access to unmanaged native methods. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Runtime.InteropServices; - - /// - /// Provides access to unmanaged native methods. - /// - internal class NativeMethods - { - /// - /// Loads the specified module into the address space of the calling process. - /// The specified module may cause other modules to be loaded. - /// - /// - /// The name of the module. This can be either a library module or - /// an executable module. - /// - /// If the function succeeds, the return value is a handle to the module; otherwise null. - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] - public static extern IntPtr LoadLibrary(string libname); - - /// - /// Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. - /// When the reference count reaches zero, the module is unloaded from the address space of the calling - /// process and the handle is no longer valid. - /// - /// A handle to the loaded library module. - /// The LoadLibrary, LoadLibraryEx, GetModuleHandle, or GetModuleHandleEx function returns this handle. - /// If the function succeeds, the return value is nonzero; otherwise zero. - [DllImport("kernel32.dll", CharSet = CharSet.Auto)] - public static extern bool FreeLibrary(IntPtr hModule); - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/PostProcessingEventArgs.cs b/old/src/ImageProcessor.Web/Helpers/PostProcessingEventArgs.cs deleted file mode 100644 index a11fbc069..000000000 --- a/old/src/ImageProcessor.Web/Helpers/PostProcessingEventArgs.cs +++ /dev/null @@ -1,25 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The post processing event arguments. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - - /// - /// The post processing event arguments. - /// - public class PostProcessingEventArgs : EventArgs - { - /// - /// Gets or sets the cached image path. - /// - public string CachedImagePath { get; set; } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/ProcessQueryStringEventArgs.cs b/old/src/ImageProcessor.Web/Helpers/ProcessQueryStringEventArgs.cs deleted file mode 100644 index 2fb90ebb8..000000000 --- a/old/src/ImageProcessor.Web/Helpers/ProcessQueryStringEventArgs.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The process querystring event arguments. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - - /// - /// The process querystring event arguments. - /// - public class ProcessQueryStringEventArgs : EventArgs - { - /// - /// Gets or sets the querystring. - /// - public string Querystring { get; set; } - - /// - /// Gets or sets the raw http request url. - /// - public string RawUrl { get; set; } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/ExtendedColorTypeConverter.cs b/old/src/ImageProcessor.Web/Helpers/QuerystringParser/ExtendedColorTypeConverter.cs deleted file mode 100644 index ffb1e6960..000000000 --- a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/ExtendedColorTypeConverter.cs +++ /dev/null @@ -1,248 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The extended color type converter allows conversion of system and web colors. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Collections; - using System.ComponentModel; - using System.Drawing; - using System.Globalization; - using System.Text; - using System.Text.RegularExpressions; - - /// - /// The extended color type converter allows conversion of system and web colors. - /// - public class ExtendedColorTypeConverter : ColorConverter - { - /// - /// The web color regex. - /// - private static readonly Regex HexColorRegex = new Regex("([0-9a-fA-F]{3}){1,2}", RegexOptions.Compiled); - - /// - /// The number color regex. - /// - private static readonly Regex NumberRegex = new Regex(@"\d+", RegexOptions.Compiled); - - /// - /// The html system color table map. - /// - private static Hashtable htmlSystemColorTable; - - /// - /// Converts the given object to the type of this converter, using the specified context and culture - /// information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// The to use as the current culture. - /// - /// The to convert. - /// The conversion cannot be performed. - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - string s = value as string; - if (s != null) - { - string colorText = s.Trim(); - Color c = Color.Empty; - - // Empty color - if (string.IsNullOrEmpty(colorText)) - { - return c; - } - - // Special case. HTML requires LightGrey, but System.Drawing.KnownColor has LightGray - if (colorText.Equals("LightGrey", StringComparison.OrdinalIgnoreCase)) - { - return Color.LightGray; - } - - // Handle a,r,g,b - char separator = culture.TextInfo.ListSeparator[0]; - if (colorText.Contains(separator.ToString())) - { - string[] components = colorText.Split(separator); - - bool convert = true; - foreach (string component in components) - { - if (!NumberRegex.IsMatch(component)) - { - convert = false; - } - } - - if (convert) - { - if (components.Length == 4) - { - return Color.FromArgb( - Convert.ToInt32(components[3]), - Convert.ToInt32(components[0]), - Convert.ToInt32(components[1]), - Convert.ToInt32(components[2])); - } - - return Color.FromArgb( - Convert.ToInt32(components[0]), - Convert.ToInt32(components[1]), - Convert.ToInt32(components[2])); - } - } - - // Hex based color values. - char hash = colorText[0]; - if (hash == '#' || HexColorRegex.IsMatch(colorText)) - { - if (hash != '#') - { - colorText = "#" + colorText; - } - - if (colorText.Length == 7) - { - return Color.FromArgb( - Convert.ToInt32(colorText.Substring(1, 2), 16), - Convert.ToInt32(colorText.Substring(3, 2), 16), - Convert.ToInt32(colorText.Substring(5, 2), 16)); - } - - // Length is 4 - string r = char.ToString(colorText[1]); - string g = char.ToString(colorText[2]); - string b = char.ToString(colorText[3]); - - return Color.FromArgb( - Convert.ToInt32(r + r, 16), - Convert.ToInt32(g + g, 16), - Convert.ToInt32(b + b, 16)); - } - - // System color - if (htmlSystemColorTable == null) - { - InitializeHtmlSystemColorTable(); - } - - if (htmlSystemColorTable != null) - { - object o = htmlSystemColorTable[colorText]; - if (o != null) - { - return (Color)o; - } - } - } - - // ColorConverter handles all named and KnownColors - return base.ConvertFrom(context, culture, value); - } - - /// - /// Converts the given value object to the specified type, using the specified context and culture - /// information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// A . If null is passed, the current culture is assumed. - /// - /// The to convert. - /// - /// The to convert the parameter to. - /// - /// - /// The parameter is null. - /// - /// The conversion cannot be performed. - /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } - - if (destinationType == typeof(string)) - { - if (value != null) - { - Color color = (Color)value; - - if (color == Color.Empty) - { - return string.Empty; - } - - if (color.IsKnownColor == false) - { - // In the Web scenario, colors should be formatted in #RRGGBB notation - StringBuilder sb = new StringBuilder("#", 7); - sb.Append(color.R.ToString("X2", CultureInfo.InvariantCulture)); - sb.Append(color.G.ToString("X2", CultureInfo.InvariantCulture)); - sb.Append(color.B.ToString("X2", CultureInfo.InvariantCulture)); - return sb.ToString(); - } - } - } - - return base.ConvertTo(context, culture, value, destinationType); - } - - /// - /// Initializes color table mapping system colors to known colors. - /// - private static void InitializeHtmlSystemColorTable() - { - Hashtable hashTable = new Hashtable(StringComparer.OrdinalIgnoreCase); - hashTable["activeborder"] = Color.FromKnownColor(KnownColor.ActiveBorder); - hashTable["activecaption"] = Color.FromKnownColor(KnownColor.ActiveCaption); - hashTable["appworkspace"] = Color.FromKnownColor(KnownColor.AppWorkspace); - hashTable["background"] = Color.FromKnownColor(KnownColor.Desktop); - hashTable["buttonface"] = Color.FromKnownColor(KnownColor.Control); - hashTable["buttonhighlight"] = Color.FromKnownColor(KnownColor.ControlLightLight); - hashTable["buttonshadow"] = Color.FromKnownColor(KnownColor.ControlDark); - hashTable["buttontext"] = Color.FromKnownColor(KnownColor.ControlText); - hashTable["captiontext"] = Color.FromKnownColor(KnownColor.ActiveCaptionText); - hashTable["graytext"] = Color.FromKnownColor(KnownColor.GrayText); - hashTable["highlight"] = Color.FromKnownColor(KnownColor.Highlight); - hashTable["highlighttext"] = Color.FromKnownColor(KnownColor.HighlightText); - hashTable["inactiveborder"] = Color.FromKnownColor(KnownColor.InactiveBorder); - hashTable["inactivecaption"] = Color.FromKnownColor(KnownColor.InactiveCaption); - hashTable["inactivecaptiontext"] = Color.FromKnownColor(KnownColor.InactiveCaptionText); - hashTable["infobackground"] = Color.FromKnownColor(KnownColor.Info); - hashTable["infotext"] = Color.FromKnownColor(KnownColor.InfoText); - hashTable["menu"] = Color.FromKnownColor(KnownColor.Menu); - hashTable["menutext"] = Color.FromKnownColor(KnownColor.MenuText); - hashTable["scrollbar"] = Color.FromKnownColor(KnownColor.ScrollBar); - hashTable["threeddarkshadow"] = Color.FromKnownColor(KnownColor.ControlDarkDark); - hashTable["threedface"] = Color.FromKnownColor(KnownColor.Control); - hashTable["threedhighlight"] = Color.FromKnownColor(KnownColor.ControlLight); - hashTable["threedlightshadow"] = Color.FromKnownColor(KnownColor.ControlLightLight); - hashTable["window"] = Color.FromKnownColor(KnownColor.Window); - hashTable["windowframe"] = Color.FromKnownColor(KnownColor.WindowFrame); - hashTable["windowtext"] = Color.FromKnownColor(KnownColor.WindowText); - htmlSystemColorTable = hashTable; - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/FontFamilyConverter.cs b/old/src/ImageProcessor.Web/Helpers/QuerystringParser/FontFamilyConverter.cs deleted file mode 100644 index e3705cdcc..000000000 --- a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/FontFamilyConverter.cs +++ /dev/null @@ -1,141 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// FontFamilyConverter - converter class for converting between the -// and types. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.ComponentModel; - using System.Drawing; - using System.Globalization; - - /// - /// FontFamilyConverter - converter class for converting between the - /// and types. - /// - public class FontFamilyConverter : TypeConverter - { - /// - /// Returns whether this converter can convert an object of the given type to the type of - /// this converter, using the specified context. - /// - /// - /// true if this converter can perform the conversion; otherwise, false. - /// - /// - /// An that provides a format context. - /// - /// - /// A that represents the type you want to convert from. - /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - { - return true; - } - - return base.CanConvertFrom(context, sourceType); - } - - /// - /// Returns whether this converter can convert the object to the specified type, using - /// the specified context. - /// - /// - /// true if this converter can perform the conversion; otherwise, false. - /// - /// - /// An that provides a format context. - /// - /// - /// A that represents the type you want to convert to. - /// - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(string) || destinationType == typeof(FontFamily)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - /// - /// Converts the given object to the type of this converter, using the specified context and - /// culture information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// The to use as the current culture. - /// - /// The to convert. - /// The conversion cannot be performed. - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - string s = value as string; - if (!string.IsNullOrWhiteSpace(s)) - { - return new FontFamily(s); - } - - return base.ConvertFrom(context, culture, value); - } - - /// - /// Converts the given value object to the specified type, using the specified context and culture - /// information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// A . If null is passed, the current culture is assumed. - /// The to convert. - /// - /// The to convert the parameter to. - /// - /// The parameter is null. - /// The conversion cannot be performed. - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (null == value) - { - throw new ArgumentNullException("value"); - } - - FontFamily fontFamily = value as FontFamily; - if (fontFamily == null) - { - throw new ArgumentException("value"); - } - - if (null == destinationType) - { - throw new ArgumentNullException("destinationType"); - } - - if (destinationType == typeof(string)) - { - return fontFamily.Name; - } - - return base.ConvertTo(context, culture, value, destinationType); - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/GenericArrayTypeConverter.cs b/old/src/ImageProcessor.Web/Helpers/QuerystringParser/GenericArrayTypeConverter.cs deleted file mode 100644 index 8e8ea1063..000000000 --- a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/GenericArrayTypeConverter.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Converts the value of an string to and from a Array{T}. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System.Collections.Generic; - using System.ComponentModel; - using System.Globalization; - using System.Linq; - - /// - /// Converts the value of an string to and from a Array{T}. - /// - /// - /// The type to convert from. - /// - public class GenericArrayTypeConverter : GenericListTypeConverter - { - /// - /// Converts the given object to the type of this converter, using the specified context and culture - /// information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// The to use as the current culture. - /// - /// The to convert. - /// The conversion cannot be performed. - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - object result = base.ConvertFrom(context, culture, value); - IList list = result as IList; - return list != null ? list.ToArray() : result; - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/GenericListTypeConverter.cs b/old/src/ImageProcessor.Web/Helpers/QuerystringParser/GenericListTypeConverter.cs deleted file mode 100644 index e48aff70e..000000000 --- a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/GenericListTypeConverter.cs +++ /dev/null @@ -1,175 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Converts the value of an string to and from a List{T}. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Globalization; - using System.Linq; - - /// - /// Converts the value of an string to and from a List{T}. - /// - /// - /// The type to convert from. - /// - public class GenericListTypeConverter : TypeConverter - { - /// - /// The type converter. - /// - private readonly TypeConverter typeConverter; - - /// - /// Initializes a new instance of the class. - /// - /// - /// Thrown if no converter exists for the given type. - /// - public GenericListTypeConverter() - { - Type type = typeof(T); - this.typeConverter = TypeDescriptor.GetConverter(type); - if (this.typeConverter == null) - { - throw new InvalidOperationException("No type converter exists for type " + type.FullName); - } - } - - /// - /// Returns whether this converter can convert an object of the given type to the type of this converter, - /// using the specified context. - /// - /// - /// true if this converter can perform the conversion; otherwise, false. - /// - /// - /// An that provides a - /// format context. - /// - /// A that represents the type you want to convert from. - /// - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - if (sourceType == typeof(string)) - { - return true; - } - - return base.CanConvertFrom(context, sourceType); - } - - /// - /// Converts the given object to the type of this converter, using the specified context and culture - /// information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// The to use as the current culture. - /// - /// The to convert. - /// The conversion cannot be performed. - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) - { - string input = value as string; - if (input != null) - { - string[] items = this.GetStringArray(input, culture); - - List result = new List(); - - Array.ForEach( - items, - s => - { - object item = this.typeConverter.ConvertFromInvariantString(s); - if (item != null) - { - result.Add((T)item); - } - }); - - return result; - } - - return base.ConvertFrom(context, culture, value); - } - - /// - /// Converts the given value object to the specified type, using the specified context and culture - /// information. - /// - /// - /// An that represents the converted value. - /// - /// - /// An that provides a format context. - /// - /// - /// A . If null is passed, the current culture is assumed. - /// - /// The to convert. - /// - /// The to convert the parameter to. - /// - /// - /// The parameter is null. - /// - /// The conversion cannot be performed. - /// - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) - { - if (destinationType == typeof(string)) - { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } - - string separator = culture.TextInfo.ListSeparator; - return string.Join(separator, (IList)value); - } - - return base.ConvertTo(context, culture, value, destinationType); - } - - /// - /// Splits a string by comma to return an array of string values. - /// - /// - /// The input string to split. - /// - /// - /// A . The current culture to split string by. - /// - /// - /// The array from the comma separated values. - /// - protected string[] GetStringArray(string input, CultureInfo culture) - { - if (culture == null) - { - culture = CultureInfo.CurrentCulture; - } - - char separator = culture.TextInfo.ListSeparator[0]; - string[] result = input.Split(separator).Select(s => s.Trim()).ToArray(); - - return result; - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/QueryParamParser.cs b/old/src/ImageProcessor.Web/Helpers/QuerystringParser/QueryParamParser.cs deleted file mode 100644 index b6758f633..000000000 --- a/old/src/ImageProcessor.Web/Helpers/QuerystringParser/QueryParamParser.cs +++ /dev/null @@ -1,234 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The query parameter parser that converts string values to different types. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.ComponentModel; - using System.Drawing; - using System.Globalization; - using System.Linq.Expressions; - using System.Web; - - /// - /// The query parameter parser that converts string values to different types. - /// - public class QueryParamParser - { - /// - /// A new instance of the class. - /// with lazy initialization. - /// - private static readonly Lazy Lazy = new Lazy(() => new QueryParamParser()); - - /// - /// The cache for storing created default types. - /// - private static readonly ConcurrentDictionary TypeDefaultsCache = new ConcurrentDictionary(); - - /// - /// Prevents a default instance of the class from being created. - /// - private QueryParamParser() - { - this.AddColorConverters(); - this.AddFontFamilyConverters(); - this.AddListConverters(); - this.AddArrayConverters(); - } - - /// - /// Gets the current instance. - /// - public static QueryParamParser Instance - { - get - { - return Lazy.Value; - } - } - - /// - /// Parses the given string value converting it to the given type. - /// - /// - /// The value to parse. - /// - /// - /// The to use as the current culture. - /// If not set will parse using - /// - /// - /// The to convert the string to. - /// - /// - /// The . - /// - public T ParseValue(string value, CultureInfo culture = null) - { - return (T)this.ParseValue(typeof(T), value, culture); - } - - /// - /// Parses the given string value converting it to the given type. - /// - /// - /// The to convert the string to. - /// - /// - /// The value to parse. - /// - /// - /// The to use as the current culture. - /// If not set will parse using - /// - /// - /// The . - /// - public object ParseValue(Type type, string value, CultureInfo culture = null) - { - if (culture == null) - { - culture = CultureInfo.InvariantCulture; - } - - TypeConverter converter = TypeDescriptor.GetConverter(type); - try - { - // ReSharper disable once AssignNullToNotNullAttribute - return converter.ConvertFrom(null, culture, HttpUtility.UrlDecode(value)); - } - catch - { - // Return the default value - return TypeDefaultsCache.GetOrAdd(type, t => this.GetDefaultValue(type)); - } - } - - /// - /// Adds a type converter to the parser. - /// - /// - /// The to add a converter for. - /// - /// - /// The type of to add. - /// - /// - /// The . - /// - public TypeDescriptionProvider AddTypeConverter(Type type, Type converterType) - { - return TypeDescriptor.AddAttributes(type, new TypeConverterAttribute(converterType)); - } - - /// - /// Adds color converters. - /// - private void AddColorConverters() - { - this.AddTypeConverter(typeof(Color), typeof(ExtendedColorTypeConverter)); - } - - /// - /// Adds font family converters. - /// - private void AddFontFamilyConverters() - { - this.AddTypeConverter(typeof(FontFamily), typeof(FontFamilyConverter)); - } - - /// - /// Adds a selection of default list type converters. - /// - private void AddListConverters() - { - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - - this.AddTypeConverter(typeof(List), typeof(GenericListTypeConverter)); - } - - /// - /// Adds a selection of default array type converters. - /// - private void AddArrayConverters() - { - this.AddTypeConverter(typeof(sbyte[]), typeof(GenericArrayTypeConverter)); - this.AddTypeConverter(typeof(byte[]), typeof(GenericArrayTypeConverter)); - - this.AddTypeConverter(typeof(short[]), typeof(GenericArrayTypeConverter)); - this.AddTypeConverter(typeof(ushort[]), typeof(GenericArrayTypeConverter)); - - this.AddTypeConverter(typeof(int[]), typeof(GenericArrayTypeConverter)); - this.AddTypeConverter(typeof(uint[]), typeof(GenericArrayTypeConverter)); - - this.AddTypeConverter(typeof(long[]), typeof(GenericArrayTypeConverter)); - this.AddTypeConverter(typeof(ulong[]), typeof(GenericArrayTypeConverter)); - - this.AddTypeConverter(typeof(decimal[]), typeof(GenericArrayTypeConverter)); - this.AddTypeConverter(typeof(float[]), typeof(GenericArrayTypeConverter)); - this.AddTypeConverter(typeof(double[]), typeof(GenericArrayTypeConverter)); - - this.AddTypeConverter(typeof(string[]), typeof(GenericArrayTypeConverter)); - - this.AddTypeConverter(typeof(Color[]), typeof(GenericArrayTypeConverter)); - } - - /// - /// Returns the default value for the given type. - /// - /// - /// The to return. - /// - /// - /// The representing the default value. - /// - /// - /// Thrown if the given is null. - /// - private object GetDefaultValue(Type type) - { - // Validate parameters. - if (type == null) - { - throw new ArgumentNullException("type"); - } - - // We want an Func which returns the default. - // Create that expression here. - // Have to convert to object. - // The default value, always get what the *code* tells us. - Expression> e = - Expression.Lambda>( - Expression.Convert(Expression.Default(type), typeof(object))); - - // Compile and return the value. - return e.Compile()(); - } - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/RemoteFile.cs b/old/src/ImageProcessor.Web/Helpers/RemoteFile.cs deleted file mode 100644 index 0d866132a..000000000 --- a/old/src/ImageProcessor.Web/Helpers/RemoteFile.cs +++ /dev/null @@ -1,255 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods used to download files from a website address. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.Net; - using System.Security; - using System.Threading.Tasks; - using System.Web; - - /// - /// Encapsulates methods used to download files from a website address. - /// - /// - /// - /// The purpose of this class is so there's one core way of downloading remote files with url[s] that are from - /// outside users. There's various areas in application where an attacker could supply an external url to the server - /// and tie up resources. - /// - /// For example, the ImageProcessingModule accepts off-server addresses as a path. An attacker could, for instance, pass the url - /// to a file that's a few gigs in size, causing the server to get out-of-memory exceptions or some other errors. An attacker - /// could also use this same method to use one application instance to hammer another site by, again, passing an off-server - /// address of the victims site to the ImageProcessingModule. - /// This class will not throw an exception if the Uri supplied points to a resource local to the running application instance. - /// - /// There shouldn't be any security issues there, as the internal WebRequest instance is still calling it remotely. - /// Any local files that shouldn't be accessed by this won't be allowed by the remote call. - /// - /// Adapted from BlogEngine.Net - /// - internal sealed class RemoteFile - { - #region Fields - /// - /// The Uri of the remote file being downloaded. - /// - private readonly Uri url; - - /// - /// The maximum allowable download size in bytes. - /// - private int maxDownloadSize; - - /// - /// The length of time, in milliseconds, that a remote file download attempt can last before timing out. - /// - private int timeoutLength; - - /// - /// The WebResponse object used internally for this RemoteFile instance. - /// - private WebRequest webRequest; - #endregion - - #region Constructors - /// - /// Initializes a new instance of the RemoteFile class. - /// - /// The url of the file to be downloaded. - internal RemoteFile(Uri filePath) - { - if (filePath == null) - { - throw new ArgumentNullException("filePath"); - } - - this.url = filePath; - } - #endregion - - #region Properties - /// - /// Gets the Uri of the remote file being downloaded. - /// - public Uri Uri - { - get - { - return this.url; - } - } - - /// - /// Gets or sets the length of time, in milliseconds, that a remote file download attempt can - /// last before timing out. - /// - /// - /// This value can only be set if the instance is supposed to ignore the remote download settings set - /// in the current application instance. - /// - /// - /// Set this value to 0 if there should be no timeout. - /// - /// - /// - public int TimeoutLength - { - get - { - return this.timeoutLength; - } - - set - { - if (value < 0) - { - // ReSharper disable once NotResolvedInText - throw new ArgumentOutOfRangeException("TimeoutLength"); - } - - this.timeoutLength = value; - } - } - - /// - /// Gets or sets the maximum download size, in bytes, that a remote file download attempt can be. - /// - /// - /// This value can only be set if the instance is supposed to ignore the remote download settings set - /// in the current application instance. - /// - /// - /// Set this value to 0 if there should be no max bytes. - /// - /// - /// - public int MaxDownloadSize - { - get - { - return this.maxDownloadSize; - } - - set - { - if (value < 0) - { - // ReSharper disable once NotResolvedInText - throw new ArgumentOutOfRangeException("MaxDownloadSize"); - } - - this.maxDownloadSize = value; - } - } - #endregion - - #region Methods - #region Internal - /// - /// Returns the WebResponse used to download this file. - /// - /// - /// This method is meant for outside users who need specific access to the WebResponse this class - /// generates. They're responsible for disposing of it. - /// - /// - /// - /// The WebResponse used to download this file. - /// - /// The . - /// - internal async Task GetWebResponseAsync() - { - WebResponse response = null; - try - { - response = await this.GetWebRequest().GetResponseAsync(); - } - catch (WebException ex) - { - if (response != null) - { - HttpWebResponse errorResponse = (HttpWebResponse)ex.Response; - if (errorResponse.StatusCode == HttpStatusCode.NotFound) - { - throw new HttpException(404, "No image exists at " + this.Uri); - } - } - - throw; - } - - if (response != null) - { - long contentLength = response.ContentLength; - - // WebResponse.ContentLength doesn't always know the value, it returns -1 in this case. - if (contentLength == -1) - { - // Response headers may still have the Content-Length inside of it. - string headerContentLength = response.Headers["Content-Length"]; - - if (!string.IsNullOrWhiteSpace(headerContentLength)) - { - contentLength = long.Parse(headerContentLength, CultureInfo.InvariantCulture); - } - } - - // We don't need to check the url here since any external urls are available only from the web.config. - if ((this.MaxDownloadSize > 0) && (contentLength > this.MaxDownloadSize)) - { - response.Close(); - throw new SecurityException("An attempt to download a remote file has been halted because the file is larger than allowed."); - } - } - - return response; - } - #endregion - - #region Private - /// - /// Creates the WebRequest object used internally for this RemoteFile instance. - /// - /// - /// - /// The WebRequest should not be passed outside of this instance, as it will allow tampering. Anyone - /// that needs more fine control over the downloading process should probably be using the WebRequest - /// class on its own. - /// - /// - private WebRequest GetWebRequest() - { - if (this.webRequest == null) - { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Uri); - request.Headers["Accept-Encoding"] = "gzip"; - request.Headers["Accept-Language"] = "en-us"; - request.Credentials = CredentialCache.DefaultNetworkCredentials; - request.AutomaticDecompression = DecompressionMethods.GZip; - - if (this.TimeoutLength > 0) - { - request.Timeout = this.TimeoutLength; - } - - this.webRequest = request; - } - - return this.webRequest; - } - #endregion - #endregion - } -} diff --git a/old/src/ImageProcessor.Web/Helpers/ResourceHelpers.cs b/old/src/ImageProcessor.Web/Helpers/ResourceHelpers.cs deleted file mode 100644 index fe8dc523b..000000000 --- a/old/src/ImageProcessor.Web/Helpers/ResourceHelpers.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides helper methods for working with resources. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Helpers -{ - using System.IO; - using System.Reflection; - using System.Text; - - /// - /// Provides helper methods for working with resources. - /// - public class ResourceHelpers - { - /// - /// Converts an assembly resource into a string. - /// - /// - /// The resource. - /// - /// - /// The assembly. - /// - /// - /// The character encoding to return the resource in. - /// - /// - /// The . - /// - public static string ResourceAsString(string resource, Assembly assembly = null, Encoding encoding = null) - { - assembly = assembly ?? Assembly.GetExecutingAssembly(); - encoding = encoding ?? Encoding.UTF8; - - using (MemoryStream ms = new MemoryStream()) - { - using (Stream manifestResourceStream = assembly.GetManifestResourceStream(resource)) - { - if (manifestResourceStream != null) - { - manifestResourceStream.CopyTo(ms); - } - } - - return encoding.GetString(ms.GetBuffer()).Replace('\0', ' ').Trim(); - } - } - } -} diff --git a/old/src/ImageProcessor.Web/HttpModules/ImageProcessingModule.cs b/old/src/ImageProcessor.Web/HttpModules/ImageProcessingModule.cs deleted file mode 100644 index 15ebffb12..000000000 --- a/old/src/ImageProcessor.Web/HttpModules/ImageProcessingModule.cs +++ /dev/null @@ -1,672 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Processes any image requests within the web application. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.HttpModules -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Text.RegularExpressions; - using System.Threading.Tasks; - using System.Web; - using System.Web.Hosting; - - using ImageProcessor.Web.Caching; - using ImageProcessor.Web.Configuration; - using ImageProcessor.Web.Extensions; - using ImageProcessor.Web.Helpers; - using ImageProcessor.Web.Services; - - /// - /// Processes any image requests within the web application. - /// - public sealed class ImageProcessingModule : IHttpModule - { - #region Fields - - /// - /// The key for storing the response type of the current image. - /// - private const string CachedResponseTypeKey = "CACHED_IMAGE_RESPONSE_TYPE_054F217C-11CF-49FF-8D2F-698E8E6EB58F"; - - /// - /// The key for storing the cached path of the current image. - /// - private const string CachedPathKey = "CACHED_IMAGE_PATH_TYPE_E0741478-C17B-433D-96A8-6CDA797644E9"; - - /// - /// The key for storing the file dependency of the current image. - /// - private const string CachedResponseFileDependency = "CACHED_IMAGE_DEPENDENCY_054F217C-11CF-49FF-8D2F-698E8E6EB58F"; - - /// - /// The regular expression to search strings for presets with. - /// - private static readonly Regex PresetRegex = new Regex(@"preset=[^&]+", RegexOptions.Compiled); - - /// - /// The regular expression to search strings for protocols with. - /// - private static readonly Regex ProtocolRegex = new Regex("http(s)?://", RegexOptions.Compiled); - - /// - /// The assembly version. - /// - private static readonly string AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); - - /// - /// Whether to preserve exif meta data. - /// - private static bool? preserveExifMetaData; - - /// - /// The locker for preventing duplicate requests. - /// - private readonly AsyncDuplicateLock locker = new AsyncDuplicateLock(); - - /// - /// A value indicating whether this instance of the given entity has been disposed. - /// - /// if this instance has been disposed; otherwise, . - /// - /// If the entity is disposed, it must not be disposed a second - /// time. The isDisposed field is set the first time the entity - /// is disposed. If the isDisposed field is true, then the Dispose() - /// method will not dispose again. This help not to prolong the entity's - /// life in the Garbage Collector. - /// - private bool isDisposed; - - /// - /// The image cache. - /// - private IImageCache imageCache; - #endregion - - #region Destructors - - /// - /// Finalizes an instance of the class. - /// - /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// - ~ImageProcessingModule() - { - // Do not re-create Dispose clean-up code here. - // Calling Dispose(false) is optimal in terms of - // readability and maintainability. - this.Dispose(false); - } - - #endregion - - /// - /// The process querystring event handler. - /// - /// - /// The sender. - /// - /// - /// The . - /// - /// Returns the processed querystring. - public delegate string ProcessQuerystringEventHandler(object sender, ProcessQueryStringEventArgs e); - - /// - /// The event that is called when a new image is processed. - /// - public static event EventHandler OnPostProcessing; - - /// - /// The event that is called when a querystring is processed. - /// - public static event ProcessQuerystringEventHandler OnProcessQuerystring; - - #region IHttpModule Members - - /// - /// Initializes a module and prepares it to handle requests. - /// - /// - /// An that provides - /// access to the methods, properties, and events common to all - /// application objects within an ASP.NET application - /// - public void Init(HttpApplication context) - { - if (preserveExifMetaData == null) - { - preserveExifMetaData = ImageProcessorConfiguration.Instance.PreserveExifMetaData; - } - - EventHandlerTaskAsyncHelper postAuthorizeHelper = new EventHandlerTaskAsyncHelper(this.PostAuthorizeRequest); - context.AddOnPostAuthorizeRequestAsync(postAuthorizeHelper.BeginEventHandler, postAuthorizeHelper.EndEventHandler); - - EventHandlerTaskAsyncHelper postProcessHelper = new EventHandlerTaskAsyncHelper(this.PostProcessImage); - context.AddOnEndRequestAsync(postProcessHelper.BeginEventHandler, postProcessHelper.EndEventHandler); - - context.PreSendRequestHeaders += this.ContextPreSendRequestHeaders; - } - - /// - /// Disposes of the resources (other than memory) used by the module that implements . - /// - public void Dispose() - { - this.Dispose(true); - - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - /// - /// If true, the object gets disposed. - /// - private void Dispose(bool disposing) - { - if (this.isDisposed) - { - return; - } - - if (disposing) - { - // Dispose of any managed resources here. - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - // Note disposing is done. - this.isDisposed = true; - } - - #endregion - - /// - /// Occurs when the user for the current request has been authorized. - /// - /// - /// The source of the event. - /// - /// - /// An EventArgs that contains the event data. - /// - /// - /// The . - /// - private Task PostAuthorizeRequest(object sender, EventArgs e) - { - HttpContext context = ((HttpApplication)sender).Context; - return this.ProcessImageAsync(context); - } - - /// - /// Occurs when the ASP.NET event handler finishes execution. - /// - /// - /// The source of the event. - /// - /// - /// An EventArgs that contains the event data. - /// - /// - /// The . - /// - private async Task PostProcessImage(object sender, EventArgs e) - { - HttpContext context = ((HttpApplication)sender).Context; - object cachedPathObject = context.Items[CachedPathKey]; - - if (cachedPathObject != null) - { - // Trim the cache. - await this.imageCache.TrimCacheAsync(); - - string cachedPath = cachedPathObject.ToString(); - - // Fire the post processing event. - EventHandler handler = OnPostProcessing; - if (handler != null) - { - context.Items[CachedPathKey] = null; - await Task.Run(() => handler(this, new PostProcessingEventArgs { CachedImagePath = cachedPath })); - } - } - } - - /// - /// Occurs just before ASP.NET send HttpHeaders to the client. - /// - /// - /// The source of the event. - /// - /// - /// An EventArgs that contains the event data. - /// - private void ContextPreSendRequestHeaders(object sender, EventArgs e) - { - HttpContext context = ((HttpApplication)sender).Context; - - object responseTypeObject = context.Items[CachedResponseTypeKey]; - object dependencyFileObject = context.Items[CachedResponseFileDependency]; - - string responseType = responseTypeObject as string; - List dependencyFiles = dependencyFileObject as List; - - // Set the headers - this.SetHeaders(context, responseType, dependencyFiles); - } - - #region Private - /// - /// Processes the image. - /// - /// - /// the HttpContext object that provides - /// references to the intrinsic server objects - /// - /// - /// The . - /// - private async Task ProcessImageAsync(HttpContext context) - { - HttpRequest request = context.Request; - - // Should we ignore this request? - if (request.RawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE")) - { - return; - } - - IImageService currentService = this.GetImageServiceForRequest(request); - - if (currentService != null) - { - bool isFileLocal = currentService.IsFileLocalService; - string url = request.Url.ToString(); - bool isLegacy = ProtocolRegex.Matches(url).Count > 1; - bool hasMultiParams = url.Count(f => f == '?') > 1; - string requestPath; - string queryString = string.Empty; - string urlParameters = string.Empty; - - // Legacy support. I'd like to remove this asap. - if (isLegacy && hasMultiParams) - { - // We need to split the querystring to get the actual values we want. - string[] paths = url.Split('?'); - requestPath = paths[1]; - - // Handle extension-less urls. - if (paths.Length > 3) - { - queryString = paths[3]; - urlParameters = paths[2]; - } - else if (paths.Length > 1) - { - queryString = paths[2]; - } - } - else - { - if (string.IsNullOrWhiteSpace(currentService.Prefix)) - { - requestPath = HostingEnvironment.MapPath(request.Path); - queryString = request.QueryString.ToString(); - } - else - { - // Parse any protocol values from settings. - string protocol = currentService.Settings.ContainsKey("Protocol") - ? currentService.Settings["Protocol"] + "://" - : string.Empty; - - // Handle requests that require parameters. - if (hasMultiParams) - { - string[] paths = url.Split('?'); - requestPath = protocol - + request.Path.Replace(currentService.Prefix, string.Empty).TrimStart('/') - + "?" + paths[1]; - queryString = paths[2]; - } - else - { - requestPath = protocol + request.Path.Replace(currentService.Prefix, string.Empty).TrimStart('/'); - queryString = request.QueryString.ToString(); - } - } - } - - // Replace any presets in the querystring with the actual value. - queryString = this.ReplacePresetsInQueryString(queryString); - - // Execute the handler which can change the querystring - queryString = this.CheckQuerystringHandler(queryString, request.RawUrl); - - // If the current service doesn't require a prefix, don't fetch it. - // Let the static file handler take over. - if (string.IsNullOrWhiteSpace(currentService.Prefix) && string.IsNullOrWhiteSpace(queryString)) - { - return; - } - - if (string.IsNullOrWhiteSpace(requestPath)) - { - return; - } - - string parts = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty; - string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString); - object resourcePath; - - // More legacy support code. - if (hasMultiParams) - { - resourcePath = string.IsNullOrWhiteSpace(urlParameters) - ? new Uri(requestPath, UriKind.RelativeOrAbsolute) - : new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute); - } - else - { - resourcePath = requestPath; - } - - // Check whether the path is valid for other requests. - if (!currentService.IsValidRequest(resourcePath.ToString())) - { - return; - } - - // Create a new cache to help process and cache the request. - this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance - .ImageCache.GetInstance(requestPath, fullPath, queryString); - - // Is the file new or updated? - bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync(); - string cachedPath = this.imageCache.CachedPath; - - // Only process if the file has been updated. - if (isNewOrUpdated) - { - // Process the image. - using (ImageFactory imageFactory = new ImageFactory(preserveExifMetaData != null && preserveExifMetaData.Value)) - { - using (await this.locker.LockAsync(cachedPath)) - { - byte[] imageBuffer = await currentService.GetImage(resourcePath); - - using (MemoryStream inStream = new MemoryStream(imageBuffer)) - { - // Process the Image - using (MemoryStream outStream = new MemoryStream()) - { - imageFactory.Load(inStream).AutoProcess(queryString).Save(outStream); - - // Add to the cache. - await this.imageCache.AddImageToCacheAsync(outStream, imageFactory.CurrentImageFormat.MimeType); - } - } - - // Store the cached path, response type, and cache dependency in the context for later retrieval. - context.Items[CachedPathKey] = cachedPath; - context.Items[CachedResponseTypeKey] = imageFactory.CurrentImageFormat.MimeType; - bool isFileCached = new Uri(cachedPath).IsFile; - - if (isFileLocal) - { - if (isFileCached) - { - // Some services might only provide filename so we can't monitor for the browser. - context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath - ? new List { cachedPath } - : new List { requestPath, cachedPath }; - } - else - { - context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath - ? null - : new List { requestPath }; - } - } - else if (isFileCached) - { - context.Items[CachedResponseFileDependency] = new List { cachedPath }; - } - } - } - } - - // The cached file is valid so just rewrite the path. - this.imageCache.RewritePath(context); - - // Redirect if not a locally store file. - if (!new Uri(cachedPath).IsFile) - { - context.ApplicationInstance.CompleteRequest(); - } - } - } - - /// - /// This will make the browser and server keep the output - /// in its cache and thereby improve performance. - /// - /// - /// the HttpContext object that provides - /// references to the intrinsic server objects - /// - /// - /// The HTTP MIME type to send. - /// - /// - /// The dependency path for the cache dependency. - /// - private void SetHeaders(HttpContext context, string responseType, IEnumerable dependencyPaths) - { - if (this.imageCache != null) - { - HttpResponse response = context.Response; - - if (response.Headers["ImageProcessedBy"] == null) - { - response.AddHeader("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion); - } - - HttpCachePolicy cache = response.Cache; - cache.SetCacheability(HttpCacheability.Public); - cache.VaryByHeaders["Accept-Encoding"] = true; - - if (!string.IsNullOrWhiteSpace(responseType)) - { - response.ContentType = responseType; - } - - if (dependencyPaths != null) - { - context.Response.AddFileDependencies(dependencyPaths.ToArray()); - cache.SetLastModifiedFromFileDependencies(); - } - - int maxDays = this.imageCache.MaxDays; - - cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays)); - cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0)); - cache.SetRevalidation(HttpCacheRevalidation.AllCaches); - - this.imageCache = null; - - if (!string.IsNullOrEmpty(context.Request.Headers["Origin"])) - { - string origin = context.Request.Headers["Origin"]; - - if (this.IsValidCorsRequest(origin)) - { - response.AddHeader("Access-Control-Allow-Origin", origin); - } - } - } - } - - /// - /// Replaces preset values stored in the configuration in the querystring. - /// - /// - /// The query string. - /// - /// - /// The containing the updated querystring. - /// - private string ReplacePresetsInQueryString(string queryString) - { - if (!string.IsNullOrWhiteSpace(queryString)) - { - foreach (Match match in PresetRegex.Matches(queryString)) - { - if (match.Success) - { - string preset = match.Value.Split('=')[1]; - - // We use the processor config system to store the preset values. - string replacements = ImageProcessorConfiguration.Instance.GetPresetSettings(preset); - queryString = Regex.Replace(queryString, preset, replacements ?? string.Empty); - } - } - } - - return queryString; - } - - /// - /// Checks if there is a handler that changes the querystring and executes that handler. - /// - /// - /// The query string. - /// - /// - /// The raw request url. - /// - /// - /// The containing the updated querystring. - /// - private string CheckQuerystringHandler(string queryString, string rawUrl) - { - // Fire the process querystring event. - ProcessQuerystringEventHandler handler = OnProcessQuerystring; - if (handler != null) - { - ProcessQueryStringEventArgs args = new ProcessQueryStringEventArgs { Querystring = queryString ?? string.Empty, RawUrl = rawUrl ?? string.Empty }; - queryString = handler(this, args); - } - - return queryString; - } - - /// - /// Gets the correct for the given request. - /// - /// - /// The current image request. - /// - /// - /// The . - /// - private IImageService GetImageServiceForRequest(HttpRequest request) - { - IImageService imageService = null; - IList services = ImageProcessorConfiguration.Instance.ImageServices; - - string path = request.Path.TrimStart('/'); - foreach (IImageService service in services) - { - string key = service.Prefix; - if (!string.IsNullOrWhiteSpace(key) && path.StartsWith(key, StringComparison.InvariantCultureIgnoreCase)) - { - imageService = service; - } - } - - if (imageService != null) - { - return imageService; - } - - // Return the file based service - return services.FirstOrDefault(s => string.IsNullOrWhiteSpace(s.Prefix) && s.IsValidRequest(path)); - } - - /// - /// Gets a value indicating whether the current origin request passes sanitizing rules. - /// - /// - /// The image path. - /// - /// - /// True if the request is valid; otherwise, False. - /// - private bool IsValidCorsRequest(string path) - { - ImageSecuritySection.CORSOriginElement origins = - ImageProcessorConfiguration.Instance.GetImageSecuritySection().CORSOrigin; - - if (origins == null || origins.WhiteList == null) - { - return false; - } - - // Check the url is from a whitelisted location. - Uri url = new Uri(path); - string upper = url.Host.ToUpperInvariant(); - - // Check for root or sub domain. - bool validUrl = false; - foreach (Uri uri in origins.WhiteList) - { - if (uri.ToString() == "*") - { - return true; - } - - if (!uri.IsAbsoluteUri) - { - Uri rebaseUri = new Uri("http://" + uri.ToString().TrimStart('.', '/')); - validUrl = upper.StartsWith(rebaseUri.Host.ToUpperInvariant()) || upper.EndsWith(rebaseUri.Host.ToUpperInvariant()); - } - else - { - validUrl = upper.StartsWith(uri.Host.ToUpperInvariant()) || upper.EndsWith(uri.Host.ToUpperInvariant()); - } - - if (validUrl) - { - break; - } - } - - return validUrl; - } - #endregion - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/ImageFactoryExtensions.cs b/old/src/ImageProcessor.Web/ImageFactoryExtensions.cs deleted file mode 100644 index ee51be516..000000000 --- a/old/src/ImageProcessor.Web/ImageFactoryExtensions.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Extends the ImageFactory class to provide a fluent API. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web -{ - #region Using - using System.Collections.Generic; - using System.Linq; - using ImageProcessor.Web.Configuration; - using ImageProcessor.Web.Processors; - #endregion - - /// - /// Extends the ImageFactory class to provide a fluent API. - /// - public static class ImageFactoryExtensions - { - /// - /// The object to lock against. - /// - private static readonly object SyncRoot = new object(); - - /// - /// Auto processes image files based on any query string parameters added to the image path. - /// - /// - /// The current instance of the class - /// that this method extends. - /// - /// The collection of querystring parameters to process. - /// - /// The current instance of the class. - /// - public static ImageFactory AutoProcess(this ImageFactory factory, string queryString) - { - if (factory.ShouldProcess) - { - // It's faster to lock and run through our activated list than to create new instances. - lock (SyncRoot) - { - // Get a list of all graphics processors that have parsed and matched the query string. - List graphicsProcessors = - ImageProcessorConfiguration.Instance.GraphicsProcessors - .Where(x => x.MatchRegexIndex(queryString) != int.MaxValue) - .OrderBy(y => y.SortOrder) - .ToList(); - - // Loop through and process the image. - foreach (IWebGraphicsProcessor graphicsProcessor in graphicsProcessors) - { - factory.CurrentImageFormat.ApplyProcessor(graphicsProcessor.Processor.ProcessImage, factory); - } - } - } - - return factory; - } - } -} diff --git a/old/src/ImageProcessor.Web/ImageProcessor.Web.csproj b/old/src/ImageProcessor.Web/ImageProcessor.Web.csproj deleted file mode 100644 index c57b38b05..000000000 --- a/old/src/ImageProcessor.Web/ImageProcessor.Web.csproj +++ /dev/null @@ -1,137 +0,0 @@ - - - - - Debug - AnyCPU - {D011A778-59C8-4BFA-A770-C350216BF161} - Library - Properties - ImageProcessor.Web - ImageProcessor.Web - v4.5 - 512 - ..\..\ - true - - - true - full - false - bin\Debug - TRACE;DEBUG;USE_CSHARP_SQLITE, NET45 - prompt - 4 - - - pdbonly - true - bin\Release - TRACE;USE_CSHARP_SQLITE, NET45 - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {3b5dd734-fb7a-487d-8ce6-55e7af9aea7e} - ImageProcessor - - - - - Designer - - - Designer - - - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/ImageProcessor.Web.csproj.DotSettings b/old/src/ImageProcessor.Web/ImageProcessor.Web.csproj.DotSettings deleted file mode 100644 index bbce28395..000000000 --- a/old/src/ImageProcessor.Web/ImageProcessor.Web.csproj.DotSettings +++ /dev/null @@ -1,3 +0,0 @@ - - True - True \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Alpha.cs b/old/src/ImageProcessor.Web/Processors/Alpha.cs deleted file mode 100644 index 24f1e037e..000000000 --- a/old/src/ImageProcessor.Web/Processors/Alpha.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the alpha component of the image to effect its transparency. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to change the alpha component of the image to effect its transparency. - /// - public class Alpha : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"alpha=\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Alpha() - { - this.Processor = new ImageProcessor.Processors.Alpha(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int percentage = QueryParamParser.Instance.ParseValue(queryCollection["alpha"]); - percentage = ImageMaths.Clamp(percentage, 0, 100); - this.Processor.DynamicParameter = percentage; - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/AutoRotate.cs b/old/src/ImageProcessor.Web/Processors/AutoRotate.cs deleted file mode 100644 index 4f9887b2e..000000000 --- a/old/src/ImageProcessor.Web/Processors/AutoRotate.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Performs auto-rotation to ensure that EXIF defined rotation is reflected in -// the final image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Text.RegularExpressions; - using ImageProcessor.Processors; - - /// - /// Performs auto-rotation to ensure that EXIF defined rotation is reflected in - /// the final image. - /// - public class AutoRotate : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"autorotate=true", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public AutoRotate() - { - this.Processor = new ImageProcessor.Processors.AutoRotate(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder - { - get; - private set; - } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/BackgroundColor.cs b/old/src/ImageProcessor.Web/Processors/BackgroundColor.cs deleted file mode 100644 index e12c201c1..000000000 --- a/old/src/ImageProcessor.Web/Processors/BackgroundColor.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Changes the background color of an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Drawing; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Changes the background color of an image. - /// - public class BackgroundColor : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"bgcolor=[^&]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public BackgroundColor() - { - this.Processor = new ImageProcessor.Processors.BackgroundColor(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - Color color = QueryParamParser.Instance.ParseValue(queryCollection["bgcolor"]); - this.Processor.DynamicParameter = color; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Brightness.cs b/old/src/ImageProcessor.Web/Processors/Brightness.cs deleted file mode 100644 index b1ff158c4..000000000 --- a/old/src/ImageProcessor.Web/Processors/Brightness.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the brightness component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to change the brightness component of the image. - /// - public class Brightness : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"brightness=(-)?\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Brightness() - { - this.Processor = new ImageProcessor.Processors.Brightness(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int percentage = QueryParamParser.Instance.ParseValue(queryCollection["brightness"]); - percentage = ImageMaths.Clamp(percentage, -100, 100); - this.Processor.DynamicParameter = percentage; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Contrast.cs b/old/src/ImageProcessor.Web/Processors/Contrast.cs deleted file mode 100644 index ee25c48ba..000000000 --- a/old/src/ImageProcessor.Web/Processors/Contrast.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the contrast component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to change the contrast component of the image. - /// - public class Contrast : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"contrast=(-)?\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Contrast() - { - this.Processor = new ImageProcessor.Processors.Contrast(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int percentage = QueryParamParser.Instance.ParseValue(queryCollection["contrast"]); - percentage = ImageMaths.Clamp(percentage, -100, 100); - this.Processor.DynamicParameter = percentage; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Crop.cs b/old/src/ImageProcessor.Web/Processors/Crop.cs deleted file mode 100644 index b1eda64aa..000000000 --- a/old/src/ImageProcessor.Web/Processors/Crop.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Crops an image to the given directions. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Crops an image to the given directions. - /// - public class Crop : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"\b(?!entropy)crop\b[=]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Crop() - { - this.Processor = new ImageProcessor.Processors.Crop(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - float[] coordinates = QueryParamParser.Instance.ParseValue(queryCollection["crop"]); - - // Default CropMode.Pixels will be returned. - CropMode cropMode = QueryParamParser.Instance.ParseValue(queryCollection["cropmode"]); - CropLayer cropLayer = new CropLayer(coordinates[0], coordinates[1], coordinates[2], coordinates[3], cropMode); - this.Processor.DynamicParameter = cropLayer; - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/DetectEdges.cs b/old/src/ImageProcessor.Web/Processors/DetectEdges.cs deleted file mode 100644 index 986a7d253..000000000 --- a/old/src/ImageProcessor.Web/Processors/DetectEdges.cs +++ /dev/null @@ -1,129 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Produces an image with the detected edges highlighted. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Generic; - using System.Collections.Specialized; - using System.Linq; - using System.Reflection; - using System.Text; - using System.Text.RegularExpressions; - using System.Web; - using System.Web.Compilation; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging.Filters.EdgeDetection; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Produces an image with the detected edges highlighted. - /// - public class DetectEdges : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = BuildRegex(); - - /// - /// The edge detectors. - /// - private static Dictionary detectors; - - /// - /// Initializes a new instance of the class. - /// - public DetectEdges() - { - this.Processor = new ImageProcessor.Processors.DetectEdges(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the processor. - /// - /// - /// The processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - IEdgeFilter filter = (IEdgeFilter)detectors[QueryParamParser.Instance.ParseValue(queryCollection["detectedges"])]; - bool greyscale = QueryParamParser.Instance.ParseValue(queryCollection["greyscale"]); - this.Processor.DynamicParameter = new Tuple(filter, greyscale); - } - - return this.SortOrder; - } - - /// - /// Builds a regular expression from the type, this allows extensibility. - /// - /// - /// The to match matrix filters. - /// - private static Regex BuildRegex() - { - StringBuilder stringBuilder = new StringBuilder(); - - stringBuilder.Append("detectedges=("); - - Type type = typeof(IEdgeFilter); - - // Build a list of native IEdgeFilter instances. - detectors = BuildManager.GetReferencedAssemblies() - .Cast() - .SelectMany(s => s.GetLoadableTypes()) - .Where(t => type.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract) - .ToDictionary(t => t.Name.ToLowerInvariant().Replace("edgefilter", string.Empty), Activator.CreateInstance); - - stringBuilder.Append(string.Join("|", detectors.Keys.ToList())); - - stringBuilder.Append(")"); - - return new Regex(stringBuilder.ToString(), RegexOptions.IgnoreCase); - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/EntropyCrop.cs b/old/src/ImageProcessor.Web/Processors/EntropyCrop.cs deleted file mode 100644 index 41c5f177d..000000000 --- a/old/src/ImageProcessor.Web/Processors/EntropyCrop.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Performs a crop on an image to the area of greatest entropy. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Performs a crop on an image to the area of greatest entropy. - /// - public class EntropyCrop : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"entropycrop(=)?[^&]*", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public EntropyCrop() - { - this.Processor = new ImageProcessor.Processors.EntropyCrop(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - // Set the sort order to max to allow filtering. - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - byte threshold = QueryParamParser.Instance.ParseValue(queryCollection["entropycrop"]); - - // Fallback to the default if 0. - this.Processor.DynamicParameter = threshold > 0 ? threshold : (byte)128; - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Filter.cs b/old/src/ImageProcessor.Web/Processors/Filter.cs deleted file mode 100644 index 89e7899c2..000000000 --- a/old/src/ImageProcessor.Web/Processors/Filter.cs +++ /dev/null @@ -1,157 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add filters to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Reflection; - using System.Text; - using System.Text.RegularExpressions; - using ImageProcessor.Imaging.Filters.Photo; - using ImageProcessor.Processors; - - /// - /// Encapsulates methods with which to add filters to an image. - /// - public class Filter : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = BuildRegex(); - - /// - /// The filter cache. - /// - private static readonly ConcurrentDictionary FilterCache - = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - - /// - /// Initializes a new instance of the class. - /// - public Filter() - { - this.Processor = new ImageProcessor.Processors.Filter(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the processor. - /// - /// - /// The processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - this.Processor.DynamicParameter = this.ParseFilter(match.Value.Split('=')[1]); - } - - return this.SortOrder; - } - - /// - /// Builds a regular expression from the type, this allows extensibility. - /// - /// - /// The to match matrix filters. - /// - private static Regex BuildRegex() - { - const BindingFlags Flags = BindingFlags.Public | BindingFlags.Static; - Type type = typeof(MatrixFilters); - IEnumerable filters = type.GetProperties(Flags) - .Where(p => p.PropertyType.IsAssignableFrom(typeof(IMatrixFilter))) - .ToList(); - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append("filter=("); - int counter = 0; - - foreach (PropertyInfo filter in filters) - { - if (counter == 0) - { - stringBuilder.Append(filter.Name.ToLowerInvariant()); - } - else - { - stringBuilder.AppendFormat("|{0}", filter.Name.ToLowerInvariant()); - } - - counter++; - } - - stringBuilder.Append(")"); - - return new Regex(stringBuilder.ToString(), RegexOptions.IgnoreCase); - } - - /// - /// Parses the input string to return the correct . - /// - /// - /// The identifier. - /// - /// - /// The . - /// - private IMatrixFilter ParseFilter(string identifier) - { - const BindingFlags Flags = BindingFlags.Public | BindingFlags.Static; - return FilterCache.GetOrAdd( - identifier, - f => - { - Type type = typeof(MatrixFilters); - PropertyInfo filter = - type.GetProperties(Flags) - .Where(p => p.PropertyType.IsAssignableFrom(typeof(IMatrixFilter))) - .First(p => p.Name.Equals(identifier, StringComparison.InvariantCultureIgnoreCase)); - - return filter.GetValue(null, null) as IMatrixFilter; - }); - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Flip.cs b/old/src/ImageProcessor.Web/Processors/Flip.cs deleted file mode 100644 index 0e51ba4ca..000000000 --- a/old/src/ImageProcessor.Web/Processors/Flip.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Flips an image horizontally or vertically. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Drawing; - using System.Text.RegularExpressions; - using ImageProcessor.Processors; - - /// - /// Flips an image horizontally or vertically. - /// - public class Flip : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"flip=(horizontal|vertical|both)", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Flip() - { - this.Processor = new ImageProcessor.Processors.Flip(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - - // We do not use the full enum so use switch. - string direction = match.Value.Split('=')[1]; - - switch (direction) - { - case "horizontal": - this.Processor.DynamicParameter = RotateFlipType.RotateNoneFlipX; - break; - case "vertical": - this.Processor.DynamicParameter = RotateFlipType.RotateNoneFlipY; - break; - default: - this.Processor.DynamicParameter = RotateFlipType.RotateNoneFlipXY; - break; - } - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Format.cs b/old/src/ImageProcessor.Web/Processors/Format.cs deleted file mode 100644 index 35cf89906..000000000 --- a/old/src/ImageProcessor.Web/Processors/Format.cs +++ /dev/null @@ -1,154 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Sets the output of the image to a specific format. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Text.RegularExpressions; - - using ImageProcessor.Configuration; - using ImageProcessor.Imaging.Formats; - using ImageProcessor.Processors; - - /// - /// Sets the output of the image to a specific format. - /// - public class Format : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = BuildRegex(); - - /// - /// Initializes a new instance of the class. - /// - public Format() - { - this.Processor = new ImageProcessor.Processors.Format(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - ISupportedImageFormat format = this.ParseFormat(match.Value.Split('=')[1]); - if (format != null) - { - this.SortOrder = match.Index; - this.Processor.DynamicParameter = format; - } - } - - return this.SortOrder; - } - - /// - /// Builds a regular expression from the type, this allows extensibility. - /// - /// - /// The to match matrix filters. - /// - private static Regex BuildRegex() - { - StringBuilder stringBuilder = new StringBuilder(); - - // png8 is a special case for determining indexed png's. - stringBuilder.Append("format=(png8"); - foreach (ISupportedImageFormat imageFormat in ImageProcessorBootstrapper.Instance.SupportedImageFormats) - { - foreach (string fileExtension in imageFormat.FileExtensions) - { - stringBuilder.AppendFormat("|{0}", fileExtension.ToLowerInvariant()); - } - } - - stringBuilder.Append(")"); - - return new Regex(stringBuilder.ToString(), RegexOptions.IgnoreCase); - } - - /// - /// Parses the input string to return the correct . - /// - /// - /// The identifier. - /// - /// - /// The . - /// - private ISupportedImageFormat ParseFormat(string identifier) - { - identifier = identifier.ToLowerInvariant(); - string finalIdentifier = identifier.Equals("png8") ? "png" : identifier; - ISupportedImageFormat newFormat = null; - List formats = ImageProcessorBootstrapper.Instance.SupportedImageFormats.ToList(); - ISupportedImageFormat format = formats.FirstOrDefault(f => f.FileExtensions.Any(e => e.Equals(finalIdentifier, StringComparison.InvariantCultureIgnoreCase))); - - if (format != null) - { - // Return a new instance as we want to use instance properties. - newFormat = Activator.CreateInstance(format.GetType()) as ISupportedImageFormat; - - if (newFormat != null) - { - // I wish this wasn't hard-coded but there's no way I can - // find to preserve the palette. - if (identifier.Equals("png8")) - { - newFormat.IsIndexed = true; - } - else if (identifier.Equals("png")) - { - newFormat.IsIndexed = false; - } - } - } - - return newFormat; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/GaussianBlur.cs b/old/src/ImageProcessor.Web/Processors/GaussianBlur.cs deleted file mode 100644 index cf06185c6..000000000 --- a/old/src/ImageProcessor.Web/Processors/GaussianBlur.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Applies a Gaussian blur to the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Globalization; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Applies a Gaussian blur to the image. - /// - public class GaussianBlur : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"blur=[^&]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public GaussianBlur() - { - this.Processor = new ImageProcessor.Processors.GaussianBlur(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - if (match.Success) - { - this.SortOrder = match.Index; - - int maxSize; - double maxSigma; - int maxThreshold; - - int.TryParse(this.Processor.Settings["MaxSize"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxSize); - double.TryParse(this.Processor.Settings["MaxSigma"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxSigma); - int.TryParse(this.Processor.Settings["MaxThreshold"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxThreshold); - - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int size = QueryParamParser.Instance.ParseValue(queryCollection["blur"]); - - // Fall back to default sigma. - double sigma = queryCollection["sigma"] != null ? QueryParamParser.Instance.ParseValue(queryCollection["sigma"]) : 1.4d; - int threshold = QueryParamParser.Instance.ParseValue(queryCollection["threshold"]); - - // Normalize and set the variables. - size = ImageMaths.Clamp(size, 0, maxSize); - sigma = ImageMaths.Clamp(sigma, 0, maxSigma); - threshold = ImageMaths.Clamp(threshold, 0, maxThreshold); - - this.Processor.DynamicParameter = new GaussianLayer(size, sigma, threshold); - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/GaussianSharpen.cs b/old/src/ImageProcessor.Web/Processors/GaussianSharpen.cs deleted file mode 100644 index a23d915ec..000000000 --- a/old/src/ImageProcessor.Web/Processors/GaussianSharpen.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Applies a Gaussian sharpen to the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Globalization; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Applies a Gaussian sharpen to the image. - /// - public class GaussianSharpen : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"sharpen=[^&]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public GaussianSharpen() - { - this.Processor = new ImageProcessor.Processors.GaussianSharpen(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - if (match.Success) - { - this.SortOrder = match.Index; - - int maxSize; - double maxSigma; - int maxThreshold; - - int.TryParse(this.Processor.Settings["MaxSize"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxSize); - double.TryParse(this.Processor.Settings["MaxSigma"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxSigma); - int.TryParse(this.Processor.Settings["MaxThreshold"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxThreshold); - - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int size = QueryParamParser.Instance.ParseValue(queryCollection["sharpen"]); - - // Fall back to default sigma. - double sigma = queryCollection["sigma"] != null ? QueryParamParser.Instance.ParseValue(queryCollection["sigma"]) : 1.4d; - int threshold = QueryParamParser.Instance.ParseValue(queryCollection["threshold"]); - - // Normalize and set the variables. - size = ImageMaths.Clamp(size, 0, maxSize); - sigma = ImageMaths.Clamp(sigma, 0, maxSigma); - threshold = ImageMaths.Clamp(threshold, 0, maxThreshold); - - this.Processor.DynamicParameter = new GaussianLayer(size, sigma, threshold); - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Halftone.cs b/old/src/ImageProcessor.Web/Processors/Halftone.cs deleted file mode 100644 index 11276d60a..000000000 --- a/old/src/ImageProcessor.Web/Processors/Halftone.cs +++ /dev/null @@ -1,78 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The halftone processor applies a classical CMYK halftone to the given image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Text.RegularExpressions; - - using ImageProcessor.Processors; - - /// - /// The halftone processor applies a classical CMYK halftone to the given image. - /// - public class Halftone : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"halftone(=comic)?", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Halftone() - { - this.Processor = new ImageProcessor.Processors.Halftone(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - bool comicMode = match.Value.Contains("comic"); - this.Processor.DynamicParameter = comicMode; - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Hue.cs b/old/src/ImageProcessor.Web/Processors/Hue.cs deleted file mode 100644 index d944bc828..000000000 --- a/old/src/ImageProcessor.Web/Processors/Hue.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to adjust the hue component of an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Specialized; - using System.Globalization; - using System.Text; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to adjust the hue component of an image. - /// - public class Hue : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"hue=\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Hue() - { - this.Processor = new ImageProcessor.Processors.Hue(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - - int degrees = QueryParamParser.Instance.ParseValue(queryCollection["hue"]); - bool rotate = QueryParamParser.Instance.ParseValue(queryCollection["hue.rotate"]); - degrees = ImageMaths.Clamp(degrees, 0, 360); - - this.Processor.DynamicParameter = new Tuple(degrees, rotate); - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/IWebGraphicsProcessor.cs b/old/src/ImageProcessor.Web/Processors/IWebGraphicsProcessor.cs deleted file mode 100644 index b15d86d30..000000000 --- a/old/src/ImageProcessor.Web/Processors/IWebGraphicsProcessor.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Defines properties and methods for ImageProcessor.Web Plugins. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Text.RegularExpressions; - using ImageProcessor.Processors; - - /// - /// Defines properties and methods for ImageProcessor.Web Plugins. - /// - public interface IWebGraphicsProcessor - { - #region Properties - /// - /// Gets the regular expression to search strings for. - /// - Regex RegexPattern { get; } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - int SortOrder { get; } - - /// - /// Gets the associated graphics processor. - /// - IGraphicsProcessor Processor { get; } - #endregion - - #region Methods - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - int MatchRegexIndex(string queryString); - #endregion - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Mask.cs b/old/src/ImageProcessor.Web/Processors/Mask.cs deleted file mode 100644 index a3641206a..000000000 --- a/old/src/ImageProcessor.Web/Processors/Mask.cs +++ /dev/null @@ -1,126 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Applies a mask to the given image. If the mask is not the same size as the image -// it will be centered against the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Specialized; - using System.Drawing; - using System.IO; - using System.Text.RegularExpressions; - using System.Web; - using System.Web.Hosting; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Applies a mask to the given image. If the mask is not the same size as the image - /// it will be centered against the image. - /// - public class Mask : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"mask=[\w+-]+." + ImageHelpers.ExtensionRegexPattern); - - /// - /// Initializes a new instance of the class. - /// - public Mask() - { - this.Processor = new ImageProcessor.Processors.Mask(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - Image image = this.ParseImage(queryCollection["mask"]); - Point? position = queryCollection["mask.position"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["mask.position"]) - : (Point?)null; - - this.Processor.DynamicParameter = new Tuple(image, position); - } - - return this.SortOrder; - } - - /// - /// Returns an image from the given input path. - /// - /// - /// The input containing the value to parse. - /// - /// - /// The representing the given image path. - /// - public Image ParseImage(string input) - { - Image image = null; - - // Correctly parse the path. - string path; - this.Processor.Settings.TryGetValue("VirtualPath", out path); - - if (!string.IsNullOrWhiteSpace(path) && path.StartsWith("~/")) - { - string imagePath = HostingEnvironment.MapPath(path); - if (imagePath != null) - { - imagePath = Path.Combine(imagePath, input); - using (ImageFactory factory = new ImageFactory()) - { - factory.Load(imagePath); - image = new Bitmap(factory.Image); - } - } - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Meta.cs b/old/src/ImageProcessor.Web/Processors/Meta.cs deleted file mode 100644 index b6ea4bd79..000000000 --- a/old/src/ImageProcessor.Web/Processors/Meta.cs +++ /dev/null @@ -1,78 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to control preservation of meta information. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Text.RegularExpressions; - using ImageProcessor.Processors; - - /// - /// Encapsulates methods to control preservation of meta information. - /// - public class Meta : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"meta=(true|false)", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Meta() - { - this.Processor = new ImageProcessor.Processors.Meta(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - if (match.Success) - { - this.SortOrder = match.Index; - bool preserve = bool.Parse(match.Value.Split('=')[1]); - this.Processor.DynamicParameter = preserve; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Overlay.cs b/old/src/ImageProcessor.Web/Processors/Overlay.cs deleted file mode 100644 index f1e782eb8..000000000 --- a/old/src/ImageProcessor.Web/Processors/Overlay.cs +++ /dev/null @@ -1,138 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Adds an image overlay to the current image. -// If the overlay is larger than the image it will be scaled to match the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Drawing; - using System.IO; - using System.Text.RegularExpressions; - using System.Web; - using System.Web.Hosting; - - using ImageProcessor.Imaging; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Adds an image overlay to the current image. - /// If the overlay is larger than the image it will be scaled to match the image. - /// - public class Overlay : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"overlay=[\w+-]+." + ImageHelpers.ExtensionRegexPattern); - - /// - /// Initializes a new instance of the class. - /// - public Overlay() - { - this.Processor = new ImageProcessor.Processors.Overlay(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - Image image = this.ParseImage(queryCollection["overlay"]); - - Point? position = queryCollection["overlay.position"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["overlay.position"]) - : (Point?)null; - - int opacity = queryCollection["overlay.opacity"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["overlay.opacity"]) - : 100; - Size size = QueryParamParser.Instance.ParseValue(queryCollection["overlay.size"]); - - this.Processor.DynamicParameter = new ImageLayer - { - Image = image, - Position = position, - Opacity = opacity, - Size = size - }; - } - - return this.SortOrder; - } - - /// - /// Returns an image from the given input path. - /// - /// - /// The input containing the value to parse. - /// - /// - /// The representing the given image path. - /// - public Image ParseImage(string input) - { - Image image = null; - - // Correctly parse the path. - string path; - this.Processor.Settings.TryGetValue("VirtualPath", out path); - - if (!string.IsNullOrWhiteSpace(path) && path.StartsWith("~/")) - { - string imagePath = HostingEnvironment.MapPath(path); - if (imagePath != null) - { - imagePath = Path.Combine(imagePath, input); - using (ImageFactory factory = new ImageFactory()) - { - factory.Load(imagePath); - image = new Bitmap(factory.Image); - } - } - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Pixelate.cs b/old/src/ImageProcessor.Web/Processors/Pixelate.cs deleted file mode 100644 index dae731292..000000000 --- a/old/src/ImageProcessor.Web/Processors/Pixelate.cs +++ /dev/null @@ -1,149 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to pixelate an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Specialized; - using System.Drawing; - using System.Globalization; - using System.Text; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Extensions; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to pixelate an image. - /// - public class Pixelate : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"pixelate=[^&]", RegexOptions.Compiled); - - /// - /// The pixel regex. - /// - private static readonly Regex PixelRegex = new Regex(@"pixelate=\d+", RegexOptions.Compiled); - - /// - /// The rectangle regex. - /// - private static readonly Regex RectangleRegex = new Regex(@"pixelrect=\d+,\d+,\d+,\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Pixelate() - { - this.Processor = new ImageProcessor.Processors.Pixelate(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int size = QueryParamParser.Instance.ParseValue(queryCollection["pixelate"]); - - Rectangle? rectangle = queryCollection["pixelrect"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["pixelrect"]) - : (Rectangle?)null; - - this.Processor.DynamicParameter = new Tuple(size, rectangle); - } - - return this.SortOrder; - } - - /// - /// Returns the correct size of pixels. - /// - /// - /// The input containing the value to parse. - /// - /// - /// The representing the pixel size. - /// - public int ParseSize(string input) - { - int size = 0; - - foreach (Match match in PixelRegex.Matches(input)) - { - size = int.Parse(match.Value.Split('=')[1], CultureInfo.InvariantCulture); - } - - return size; - } - - /// - /// Returns the correct for the given string. - /// - /// - /// The input string containing the value to parse. - /// - /// - /// The correct - /// - private Rectangle? ParseRectangle(string input) - { - int[] dimensions = { }; - - foreach (Match match in RectangleRegex.Matches(input)) - { - dimensions = match.Value.ToPositiveIntegerArray(); - } - - if (dimensions.Length == 4) - { - return new Rectangle(dimensions[0], dimensions[1], dimensions[2], dimensions[3]); - } - - return null; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Quality.cs b/old/src/ImageProcessor.Web/Processors/Quality.cs deleted file mode 100644 index 0a898aa52..000000000 --- a/old/src/ImageProcessor.Web/Processors/Quality.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the quality component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to change the quality component of the image. - /// - public class Quality : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"quality=\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Quality() - { - this.Processor = new ImageProcessor.Processors.Quality(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - - Match match = this.RegexPattern.Match(queryString); - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int percentage = QueryParamParser.Instance.ParseValue(queryCollection["quality"]); - percentage = ImageMaths.Clamp(percentage, 0, 100); - this.Processor.DynamicParameter = percentage; - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/ReplaceColor.cs b/old/src/ImageProcessor.Web/Processors/ReplaceColor.cs deleted file mode 100644 index 254f985a4..000000000 --- a/old/src/ImageProcessor.Web/Processors/ReplaceColor.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods allowing the replacement of a color within an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Specialized; - using System.Drawing; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods allowing the replacement of a color within an image. - /// - public class ReplaceColor : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"replace=[^&]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public ReplaceColor() - { - this.Processor = new ImageProcessor.Processors.ReplaceColor(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - Color[] colors = QueryParamParser.Instance.ParseValue(queryCollection["replace"]); - int fuzziness = QueryParamParser.Instance.ParseValue(queryCollection["fuzziness"]); - - fuzziness = ImageMaths.Clamp(fuzziness, 0, 128); - this.Processor.DynamicParameter = new Tuple(colors[0], colors[1], fuzziness); - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Resize.cs b/old/src/ImageProcessor.Web/Processors/Resize.cs deleted file mode 100644 index 65ac74cb8..000000000 --- a/old/src/ImageProcessor.Web/Processors/Resize.cs +++ /dev/null @@ -1,190 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Resizes an image to the given dimensions. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Generic; - using System.Collections.Specialized; - using System.Drawing; - using System.Linq; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Resizes an image to the given dimensions. - /// - public class Resize : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"(width|height)=((.)?\d+|\d+(.\d+)?)+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Resize() - { - this.Processor = new ImageProcessor.Processors.Resize(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - Size size = this.ParseSize(queryCollection); - ResizeMode mode = QueryParamParser.Instance.ParseValue(queryCollection["mode"]); - AnchorPosition position = QueryParamParser.Instance.ParseValue(queryCollection["anchor"]); - bool upscale = queryCollection["upscale"] == null || QueryParamParser.Instance.ParseValue(queryCollection["upscale"]); - float[] center = queryCollection["center"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["center"]) : - new float[] { }; - - ResizeLayer resizeLayer = new ResizeLayer(size) - { - ResizeMode = mode, - AnchorPosition = position, - Upscale = upscale, - CenterCoordinates = center - }; - - this.Processor.DynamicParameter = resizeLayer; - - // Correctly parse any restrictions. - string restrictions; - this.Processor.Settings.TryGetValue("RestrictTo", out restrictions); - ((ImageProcessor.Processors.Resize)this.Processor).RestrictedSizes = this.ParseRestrictions( - restrictions); - } - - return this.SortOrder; - } - - /// - /// Returns the correct for the given query collection. - /// - /// - /// The containing the query parameters to parse. - /// - /// - /// The . - /// - private Size ParseSize(NameValueCollection queryCollection) - { - string width = queryCollection["width"]; - string height = queryCollection["height"]; - string widthRatio = queryCollection["widthratio"]; - string heightRatio = queryCollection["heightratio"]; - Size size = new Size(); - - // Umbraco calls the API incorrectly so we have to deal with floats. - // We round up so that single pixel lines are not produced. - const MidpointRounding Rounding = MidpointRounding.AwayFromZero; - - // First cater for single dimensions. - if (width != null && height == null) - { - size = new Size((int)Math.Round(QueryParamParser.Instance.ParseValue(width), Rounding), 0); - } - - if (width == null && height != null) - { - size = new Size(0, (int)Math.Round(QueryParamParser.Instance.ParseValue(height), Rounding)); - } - - // Both supplied - if (width != null && height != null) - { - size = new Size( - (int)Math.Round(QueryParamParser.Instance.ParseValue(width), Rounding), - (int)Math.Round(QueryParamParser.Instance.ParseValue(height), Rounding)); - } - - // Calculate any ratio driven sizes. - if (size.Width == 0 || size.Height == 0) - { - // Replace 0 width - if (size.Width == 0 && size.Height > 0 && widthRatio != null && heightRatio == null) - { - size.Width = (int)Math.Round(QueryParamParser.Instance.ParseValue(widthRatio) * size.Height, Rounding); - } - - // Replace 0 height - if (size.Width > 0 && size.Height == 0 && widthRatio == null && heightRatio != null) - { - size.Height = (int)Math.Round(QueryParamParser.Instance.ParseValue(heightRatio) * size.Width, Rounding); - } - } - - return size; - } - - /// - /// Returns a of sizes to restrict resizing to. - /// - /// - /// The input. - /// - /// - /// The to restrict resizing to. - /// - private List ParseRestrictions(string input) - { - List sizes = new List(); - - if (!string.IsNullOrWhiteSpace(input)) - { - sizes.AddRange(input.Split(',').Select(q => this.ParseSize(HttpUtility.ParseQueryString(q)))); - } - - return sizes; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Rotate.cs b/old/src/ImageProcessor.Web/Processors/Rotate.cs deleted file mode 100644 index 2ff29b867..000000000 --- a/old/src/ImageProcessor.Web/Processors/Rotate.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to rotate an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to rotate an image. - /// - public class Rotate : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"rotate=[^&]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Rotate() - { - this.Processor = new ImageProcessor.Processors.Rotate(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder - { - get; - private set; - } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - this.Processor.DynamicParameter = QueryParamParser.Instance.ParseValue(queryCollection["rotate"]); - } - - return this.SortOrder; - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/RotateBounded.cs b/old/src/ImageProcessor.Web/Processors/RotateBounded.cs deleted file mode 100644 index aa847a7a5..000000000 --- a/old/src/ImageProcessor.Web/Processors/RotateBounded.cs +++ /dev/null @@ -1,98 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to rotate an image without expanding the canvas. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System; - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to rotate an image without expanding the canvas. - /// - public class RotateBounded : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"rotatebounded=[^&]", RegexOptions.Compiled); - - /// - /// The regular expression to search for. - /// - private static readonly Regex BoundRegex = new Regex(@"rotatebounded.keepsize=true", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public RotateBounded() - { - this.Processor = new ImageProcessor.Processors.RotateBounded(); - } - - #region IGraphicsProcessor Members - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder - { - get; - private set; - } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - float angle = QueryParamParser.Instance.ParseValue(queryCollection["rotatebounded"]); - bool keepSize = BoundRegex.Match(queryString).Success; - - this.Processor.DynamicParameter = new Tuple(angle, keepSize); - } - - return this.SortOrder; - } - #endregion - } -} diff --git a/old/src/ImageProcessor.Web/Processors/RoundedCorners.cs b/old/src/ImageProcessor.Web/Processors/RoundedCorners.cs deleted file mode 100644 index 1ba8cdff9..000000000 --- a/old/src/ImageProcessor.Web/Processors/RoundedCorners.cs +++ /dev/null @@ -1,107 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to add rounded corners to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to add rounded corners to an image. - /// - public class RoundedCorners : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"roundedcorners=\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public RoundedCorners() - { - this.Processor = new ImageProcessor.Processors.RoundedCorners(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - - RoundedCornerLayer roundedCornerLayer = new RoundedCornerLayer( - QueryParamParser.Instance.ParseValue(queryCollection["roundedcorners"]), - this.ParseCorner(queryCollection, "tl"), - this.ParseCorner(queryCollection, "tr"), - this.ParseCorner(queryCollection, "bl"), - this.ParseCorner(queryCollection, "br")); - - this.Processor.DynamicParameter = roundedCornerLayer; - } - - return this.SortOrder; - } - - /// - /// Returns a value indicating whether to round the given corner. - /// - /// - /// The collection of query parameters. - /// - /// - /// The parameter key. - /// - /// - /// The correct true or false. - /// - private bool ParseCorner(NameValueCollection queryCollection, string key) - { - return queryCollection[key] == null || QueryParamParser.Instance.ParseValue(queryCollection[key]); - } - } -} diff --git a/old/src/ImageProcessor.Web/Processors/Saturation.cs b/old/src/ImageProcessor.Web/Processors/Saturation.cs deleted file mode 100644 index 5ed751fd3..000000000 --- a/old/src/ImageProcessor.Web/Processors/Saturation.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the saturation component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to change the saturation component of the image. - /// - public class Saturation : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"saturation=(-)?\d+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Saturation() - { - this.Processor = new ImageProcessor.Processors.Saturation(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - int percentage = QueryParamParser.Instance.ParseValue(queryCollection["saturation"]); - percentage = ImageMaths.Clamp(percentage, -100, 100); - this.Processor.DynamicParameter = percentage; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Tint.cs b/old/src/ImageProcessor.Web/Processors/Tint.cs deleted file mode 100644 index 3cd592878..000000000 --- a/old/src/ImageProcessor.Web/Processors/Tint.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Tints an image with the given color. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Drawing; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Tints an image with the given color. - /// - public class Tint : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"tint=[^&]", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Tint() - { - this.Processor = new ImageProcessor.Processors.Tint(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get { return QueryRegex; } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// The query string to search. - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - this.Processor.DynamicParameter = QueryParamParser.Instance.ParseValue(queryCollection["tint"]); - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Vignette.cs b/old/src/ImageProcessor.Web/Processors/Vignette.cs deleted file mode 100644 index 5f025ae32..000000000 --- a/old/src/ImageProcessor.Web/Processors/Vignette.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a vignette image effect to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Drawing; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods with which to add a vignette image effect to an image. - /// - public class Vignette : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"vignette(=true)?[^&]+", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Vignette() - { - this.Processor = new ImageProcessor.Processors.Vignette(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - string vignette = queryCollection["vignette"]; - bool doVignette = QueryParamParser.Instance.ParseValue(vignette); - Color color = doVignette - ? Color.Black - : QueryParamParser.Instance.ParseValue(vignette); - - this.Processor.DynamicParameter = color; - } - - return this.SortOrder; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor.Web/Processors/Watermark.cs b/old/src/ImageProcessor.Web/Processors/Watermark.cs deleted file mode 100644 index e58955073..000000000 --- a/old/src/ImageProcessor.Web/Processors/Watermark.cs +++ /dev/null @@ -1,263 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to add a watermark text overlay to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Processors -{ - using System.Collections.Specialized; - using System.Drawing; - using System.Drawing.Text; - using System.Text.RegularExpressions; - using System.Web; - - using ImageProcessor.Imaging; - using ImageProcessor.Processors; - using ImageProcessor.Web.Helpers; - - /// - /// Encapsulates methods to add a watermark text overlay to an image. - /// - public class Watermark : IWebGraphicsProcessor - { - /// - /// The regular expression to search strings for. - /// - private static readonly Regex QueryRegex = new Regex(@"watermark=", RegexOptions.Compiled); - - /// - /// Initializes a new instance of the class. - /// - public Watermark() - { - this.Processor = new ImageProcessor.Processors.Watermark(); - } - - /// - /// Gets the regular expression to search strings for. - /// - public Regex RegexPattern - { - get - { - return QueryRegex; - } - } - - /// - /// Gets the order in which this processor is to be used in a chain. - /// - public int SortOrder { get; private set; } - - /// - /// Gets the associated graphics processor. - /// - public IGraphicsProcessor Processor { get; private set; } - - /// - /// The position in the original string where the first character of the captured substring was found. - /// - /// - /// The query string to search. - /// - /// - /// The zero-based starting position in the original string where the captured substring was found. - /// - public int MatchRegexIndex(string queryString) - { - this.SortOrder = int.MaxValue; - Match match = this.RegexPattern.Match(queryString); - - if (match.Success) - { - this.SortOrder = match.Index; - NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); - TextLayer textLayer = new TextLayer - { - Text = this.ParseText(queryCollection), - Position = this.ParsePosition(queryCollection), - FontColor = this.ParseColor(queryCollection), - FontSize = this.ParseFontSize(queryCollection), - FontFamily = this.ParseFontFamily(queryCollection), - Style = this.ParseFontStyle(queryCollection), - DropShadow = this.ParseDropShadow(queryCollection), - Vertical = this.ParseVertical(queryCollection), - RightToLeft = this.ParseRightToLeft(queryCollection) - }; - - textLayer.Opacity = this.ParseOpacity(queryCollection, textLayer.FontColor); - - this.Processor.DynamicParameter = textLayer; - } - - return this.SortOrder; - } - - #region Private Methods - /// - /// Returns the correct for the given parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The correct . - /// - private string ParseText(NameValueCollection queryCollection) - { - return QueryParamParser.Instance.ParseValue(queryCollection["watermark"]); - } - - /// - /// Returns the correct for the given parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The correct - /// - private Point? ParsePosition(NameValueCollection queryCollection) - { - return queryCollection["textposition"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["textposition"]) - : (Point?)null; - } - - /// - /// Returns the correct for the given parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The correct - /// - private Color ParseColor(NameValueCollection queryCollection) - { - return queryCollection["color"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["color"]) - : Color.Black; - } - - /// - /// Returns the correct for the given parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The correct - /// - private int ParseFontSize(NameValueCollection queryCollection) - { - return queryCollection["fontsize"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["fontsize"]) - : 48; - } - - /// - /// Returns the correct for the given parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The correct - /// - private FontStyle ParseFontStyle(NameValueCollection queryCollection) - { - return queryCollection["fontstyle"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["fontstyle"]) - : FontStyle.Bold; - } - - /// - /// Returns the correct for the given parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The correct . - /// - private FontFamily ParseFontFamily(NameValueCollection queryCollection) - { - return queryCollection["fontfamily"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["fontfamily"]) - : new FontFamily(GenericFontFamilies.SansSerif); - } - - /// - /// Returns a value indicating whether the watermark is to have a shadow. - /// - /// - /// The of query parameters. - /// - /// - /// True if the watermark is to have a shadow; otherwise false. - /// - private bool ParseDropShadow(NameValueCollection queryCollection) - { - return QueryParamParser.Instance.ParseValue(queryCollection["dropshadow"]); - } - - /// - /// Returns the correct containing the opacity for the parameter collection. - /// - /// - /// The of query parameters. - /// - /// - /// The of the current . - /// - /// - /// The correct . - /// - private int ParseOpacity(NameValueCollection queryCollection, Color color) - { - if (color.A < 255) - { - return (color.A / 255) * 100; - } - - return queryCollection["fontopacity"] != null - ? QueryParamParser.Instance.ParseValue(queryCollection["fontopacity"]) - : 100; - } - - /// - /// Returns a value indicating whether the watermark is to be written right to left. - /// - /// - /// The of query parameters. - /// - /// - /// True if the watermark is to be written right to left; otherwise false. - /// - private bool ParseRightToLeft(NameValueCollection queryCollection) - { - return QueryParamParser.Instance.ParseValue(queryCollection["rtl"]); - } - - /// - /// Returns a value indicating whether the watermark is to be written vertically. - /// - /// - /// The of query parameters. - /// - /// - /// True if the watermark is to be written vertically; otherwise false. - /// - private bool ParseVertical(NameValueCollection queryCollection) - { - return QueryParamParser.Instance.ParseValue(queryCollection["vertical"]); - } - #endregion - } -} diff --git a/old/src/ImageProcessor.Web/Properties/AssemblyInfo.cs b/old/src/ImageProcessor.Web/Properties/AssemblyInfo.cs deleted file mode 100644 index cf002a487..000000000 --- a/old/src/ImageProcessor.Web/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// AssemblyInfo.cs -// -// -------------------------------------------------------------------------------------------------------------------- - -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.Web")] -[assembly: AssemblyDescription("A library for on-the-fly processing of image files with ASP.NET written in C#")] -[assembly: AssemblyConfiguration("James South")] -[assembly: AssemblyCompany("James South")] -[assembly: AssemblyProduct("ImageProcessor.Web")] -[assembly: AssemblyCopyright("Copyright © James South")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("cef6713b-4088-488a-ad2c-6f94aff082d5")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("4.3.0.0")] -[assembly: AssemblyFileVersion("4.3.0.0")] diff --git a/old/src/ImageProcessor.Web/Services/IImageService.cs b/old/src/ImageProcessor.Web/Services/IImageService.cs deleted file mode 100644 index c6c39f80f..000000000 --- a/old/src/ImageProcessor.Web/Services/IImageService.cs +++ /dev/null @@ -1,68 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Defines properties and methods for allowing retrieval of images from different sources. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Services -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - - /// - /// Defines properties and methods for allowing retrieval of images from different sources. - /// - public interface IImageService - { - /// - /// Gets or sets the prefix for the given implementation. - /// - /// This value is used as a prefix for any image requests that should use this service. - /// - /// - string Prefix { get; set; } - - /// - /// Gets a value indicating whether the image service requests files from - /// the locally based file system. - /// - bool IsFileLocalService { get; } - - /// - /// Gets or sets any additional settings required by the service. - /// - Dictionary Settings { get; set; } - - /// - /// Gets or sets the white list of . - /// - Uri[] WhiteList { get; set; } - - /// - /// Gets a value indicating whether the current request passes sanitizing rules. - /// - /// - /// The image path. - /// - /// - /// True if the request is valid; otherwise, False. - /// - bool IsValidRequest(string path); - - /// - /// Gets the image using the given identifier. - /// - /// - /// The value identifying the image to fetch. - /// - /// - /// The array containing the image data. - /// - Task GetImage(object id); - } -} diff --git a/old/src/ImageProcessor.Web/Services/LocalFileImageService.cs b/old/src/ImageProcessor.Web/Services/LocalFileImageService.cs deleted file mode 100644 index 499753753..000000000 --- a/old/src/ImageProcessor.Web/Services/LocalFileImageService.cs +++ /dev/null @@ -1,118 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The local file image service for retrieving images from the file system. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Services -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading.Tasks; - using System.Web; - - using ImageProcessor.Web.Helpers; - - /// - /// The local file image service for retrieving images from the file system. - /// - public class LocalFileImageService : IImageService - { - /// - /// The prefix for the given implementation. - /// - private string prefix = string.Empty; - - /// - /// Gets or sets the prefix for the given implementation. - /// - /// This value is used as a prefix for any image requests that should use this service. - /// - /// - public string Prefix - { - get - { - return this.prefix; - } - - set - { - this.prefix = value; - } - } - - /// - /// Gets a value indicating whether the image service requests files from - /// the locally based file system. - /// - public bool IsFileLocalService - { - get - { - return true; - } - } - - /// - /// Gets or sets any additional settings required by the service. - /// - public Dictionary Settings { get; set; } - - /// - /// Gets or sets the white list of . - /// - public Uri[] WhiteList { get; set; } - - /// - /// Gets a value indicating whether the current request passes sanitizing rules. - /// - /// - /// The image path. - /// - /// - /// True if the request is valid; otherwise, False. - /// - public bool IsValidRequest(string path) - { - return ImageHelpers.IsValidImageExtension(path); - } - - /// - /// Gets the image using the given identifier. - /// - /// - /// The value identifying the image to fetch. - /// - /// - /// The array containing the image data. - /// - public async Task GetImage(object id) - { - string path = id.ToString(); - byte[] buffer; - - // Check to see if the file exists. - // ReSharper disable once AssignNullToNotNullAttribute - FileInfo fileInfo = new FileInfo(path); - - if (!fileInfo.Exists) - { - throw new HttpException(404, "No image exists at " + path); - } - - using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - { - buffer = new byte[file.Length]; - await file.ReadAsync(buffer, 0, (int)file.Length); - } - - return buffer; - } - } -} diff --git a/old/src/ImageProcessor.Web/Services/RemoteImageService.cs b/old/src/ImageProcessor.Web/Services/RemoteImageService.cs deleted file mode 100644 index 36888a6f0..000000000 --- a/old/src/ImageProcessor.Web/Services/RemoteImageService.cs +++ /dev/null @@ -1,175 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The remote image service. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Services -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Threading.Tasks; - using System.Web; - - using ImageProcessor.Web.Helpers; - - /// - /// The remote image service. - /// - public class RemoteImageService : IImageService - { - /// - /// The prefix for the given implementation. - /// - private string prefix = "remote.axd"; - - /// - /// Initializes a new instance of the class. - /// - public RemoteImageService() - { - this.Settings = new Dictionary - { - { "MaxBytes", "4194304" }, - { "Timeout", "30000" }, - { "Protocol", "http" } - }; - - this.WhiteList = new Uri[] { }; - } - - /// - /// Gets or sets the prefix for the given implementation. - /// - /// This value is used as a prefix for any image requests that should use this service. - /// - /// - public string Prefix - { - get - { - return this.prefix; - } - - set - { - this.prefix = value; - } - } - - /// - /// Gets a value indicating whether the image service requests files from - /// the locally based file system. - /// - public bool IsFileLocalService - { - get - { - return false; - } - } - - /// - /// Gets or sets any additional settings required by the service. - /// - public Dictionary Settings { get; set; } - - /// - /// Gets or sets the white list of . - /// - public Uri[] WhiteList { get; set; } - - /// - /// Gets a value indicating whether the current request passes sanitizing rules. - /// - /// - /// The image path. - /// - /// - /// True if the request is valid; otherwise, False. - /// - public bool IsValidRequest(string path) - { - // Check the url is from a whitelisted location. - Uri url = new Uri(path); - string upper = url.Host.ToUpperInvariant(); - - // Check for root or sub domain. - bool validUrl = false; - foreach (Uri uri in this.WhiteList) - { - if (!uri.IsAbsoluteUri) - { - Uri rebaseUri = new Uri("http://" + uri.ToString().TrimStart('.', '/')); - validUrl = upper.StartsWith(rebaseUri.Host.ToUpperInvariant()) || upper.EndsWith(rebaseUri.Host.ToUpperInvariant()); - } - else - { - validUrl = upper.StartsWith(uri.Host.ToUpperInvariant()) || upper.EndsWith(uri.Host.ToUpperInvariant()); - } - - if (validUrl) - { - break; - } - } - - return validUrl; - } - - /// - /// Gets the image using the given identifier. - /// - /// - /// The value identifying the image to fetch. - /// - /// - /// The array containing the image data. - /// - public async Task GetImage(object id) - { - Uri uri = new Uri(id.ToString()); - RemoteFile remoteFile = new RemoteFile(uri) - { - MaxDownloadSize = int.Parse(this.Settings["MaxBytes"]), - TimeoutLength = int.Parse(this.Settings["Timeout"]) - }; - - byte[] buffer; - - // Prevent response blocking. - WebResponse webResponse = await remoteFile.GetWebResponseAsync().ConfigureAwait(false); - - using (MemoryStream memoryStream = new MemoryStream()) - { - using (WebResponse response = webResponse) - { - using (Stream responseStream = response.GetResponseStream()) - { - if (responseStream != null) - { - responseStream.CopyTo(memoryStream); - - // Reset the position of the stream to ensure we're reading the correct part. - memoryStream.Position = 0; - - buffer = memoryStream.ToArray(); - } - else - { - throw new HttpException(404, "No image exists at " + uri); - } - } - } - } - - return buffer; - } - } -} diff --git a/old/src/ImageProcessor.Web/Settings.StyleCop b/old/src/ImageProcessor.Web/Settings.StyleCop deleted file mode 100644 index 311872ed4..000000000 --- a/old/src/ImageProcessor.Web/Settings.StyleCop +++ /dev/null @@ -1,8 +0,0 @@ - - - - cdn - dllimport - - - \ No newline at end of file diff --git a/old/src/ImageProcessor.sln b/old/src/ImageProcessor.sln deleted file mode 100644 index 34abdf893..000000000 --- a/old/src/ImageProcessor.sln +++ /dev/null @@ -1,219 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{1E656CDE-124D-4FAF-837C-0EF1E192D418}" - ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config - .nuget\NuGet.exe = .nuget\NuGet.exe - .nuget\NuGet.targets = .nuget\NuGet.targets - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor", "ImageProcessor\ImageProcessor.csproj", "{3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Web", "ImageProcessor.Web\ImageProcessor.Web.csproj", "{D011A778-59C8-4BFA-A770-C350216BF161}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Plugins.WebP", "Plugins\ImageProcessor\ImageProcessor.Plugins.WebP\ImageProcessor.Plugins.WebP.csproj", "{2CF69699-959A-44DC-A281-4E2596C25043}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Web.UnitTests", "ImageProcessor.Web.UnitTests\ImageProcessor.Web.UnitTests.csproj", "{961340C8-8C93-401D-A0A2-FF9EC61E5260}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.UnitTests", "ImageProcessor.UnitTests\ImageProcessor.UnitTests.csproj", "{633B1C4C-4823-47BE-9A01-A665F3118C8C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test_Website_MVC", "TestWebsites\MVC\Test_Website_MVC.csproj", "{F6A208E9-C18F-43E9-B051-3C6EED30FDAF}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Plugins.Cair", "Plugins\ImageProcessor\ImageProcessor.Plugins.Cair\ImageProcessor.Plugins.Cair.csproj", "{C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Playground", "ImageProcessor.Playground\ImageProcessor.Playground.csproj", "{7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Web.PostProcessor", "ImageProcessor.Web.PostProcessor\ImageProcessor.Web.PostProcessor.csproj", "{55D08737-7D7E-4995-8892-BD9F944329E6}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Web.Plugins.AzureBlobCache", "Plugins\ImageProcessor.Web\ImageProcessor.Web.Plugins.AzureBlobCache\ImageProcessor.Web.Plugins.AzureBlobCache.csproj", "{3C805E4C-D679-43F8-8C43-8909CDB4D4D7}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{B5217BED-B0B7-408E-81B7-877DE2BF9036}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Plugins", "Plugins", "{5D12E196-FB7A-4D97-B156-56901EF8084D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - All|Any CPU = All|Any CPU - All|Mixed Platforms = All|Mixed Platforms - All|x86 = All|x86 - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Any CPU.ActiveCfg = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Any CPU.Build.0 = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Mixed Platforms.ActiveCfg = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Mixed Platforms.Build.0 = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|x86.ActiveCfg = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|x86.ActiveCfg = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Any CPU.Build.0 = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|x86.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Any CPU.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Any CPU.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Mixed Platforms.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|x86.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|x86.ActiveCfg = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Any CPU.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|x86.ActiveCfg = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.All|Any CPU.ActiveCfg = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.All|Any CPU.Build.0 = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.All|Mixed Platforms.Build.0 = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.All|x86.ActiveCfg = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Debug|x86.ActiveCfg = Debug|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Release|Any CPU.Build.0 = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {2CF69699-959A-44DC-A281-4E2596C25043}.Release|x86.ActiveCfg = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.All|Any CPU.ActiveCfg = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.All|Any CPU.Build.0 = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.All|Mixed Platforms.Build.0 = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.All|x86.ActiveCfg = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Debug|Any CPU.Build.0 = Debug|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Debug|x86.ActiveCfg = Debug|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Release|Any CPU.ActiveCfg = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Release|Any CPU.Build.0 = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {961340C8-8C93-401D-A0A2-FF9EC61E5260}.Release|x86.ActiveCfg = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.All|Any CPU.ActiveCfg = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.All|Any CPU.Build.0 = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.All|Mixed Platforms.Build.0 = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.All|x86.ActiveCfg = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Debug|x86.ActiveCfg = Debug|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Release|Any CPU.Build.0 = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {633B1C4C-4823-47BE-9A01-A665F3118C8C}.Release|x86.ActiveCfg = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.All|Any CPU.ActiveCfg = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.All|Any CPU.Build.0 = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.All|Mixed Platforms.Build.0 = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.All|x86.ActiveCfg = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Debug|x86.ActiveCfg = Debug|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Release|Any CPU.Build.0 = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF}.Release|x86.ActiveCfg = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.All|Any CPU.ActiveCfg = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.All|Any CPU.Build.0 = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.All|Mixed Platforms.Build.0 = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.All|x86.ActiveCfg = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Debug|x86.ActiveCfg = Debug|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Release|Any CPU.Build.0 = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5}.Release|x86.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Any CPU.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Any CPU.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Mixed Platforms.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|x86.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|x86.ActiveCfg = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Any CPU.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|x86.ActiveCfg = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.All|Any CPU.ActiveCfg = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.All|Any CPU.Build.0 = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.All|Mixed Platforms.Build.0 = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.All|x86.ActiveCfg = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Debug|x86.ActiveCfg = Debug|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Release|Any CPU.Build.0 = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {55D08737-7D7E-4995-8892-BD9F944329E6}.Release|x86.ActiveCfg = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.All|Any CPU.ActiveCfg = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.All|Any CPU.Build.0 = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.All|Mixed Platforms.Build.0 = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.All|x86.ActiveCfg = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Debug|x86.ActiveCfg = Debug|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Release|Any CPU.Build.0 = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7}.Release|x86.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {2CF69699-959A-44DC-A281-4E2596C25043} = {5D12E196-FB7A-4D97-B156-56901EF8084D} - {961340C8-8C93-401D-A0A2-FF9EC61E5260} = {B5217BED-B0B7-408E-81B7-877DE2BF9036} - {633B1C4C-4823-47BE-9A01-A665F3118C8C} = {B5217BED-B0B7-408E-81B7-877DE2BF9036} - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF} = {B5217BED-B0B7-408E-81B7-877DE2BF9036} - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5} = {5D12E196-FB7A-4D97-B156-56901EF8084D} - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7} = {B5217BED-B0B7-408E-81B7-877DE2BF9036} - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7} = {5D12E196-FB7A-4D97-B156-56901EF8084D} - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = ImageProcessorConsole\ImageProcessorConsole.csproj - EndGlobalSection - GlobalSection(TestCaseManagementSettings) = postSolution - CategoryFile = ImageProcessor.vsmdi - EndGlobalSection -EndGlobal diff --git a/old/src/ImageProcessor.sln.DotSettings b/old/src/ImageProcessor.sln.DotSettings deleted file mode 100644 index 6ab368df9..000000000 --- a/old/src/ImageProcessor.sln.DotSettings +++ /dev/null @@ -1,24 +0,0 @@ - - BGRA - BPP - CORS - DT - FPX - FR - HSL - HSLA - ICC - ISO - JPEG - JPEGAC - JPEGDC - JPEGQ - LPI - MD - OECF - REF - RGB - RGBA - SHA - SRGB - SS \ No newline at end of file diff --git a/old/src/ImageProcessor/Common/Exceptions/ImageFormatException.cs b/old/src/ImageProcessor/Common/Exceptions/ImageFormatException.cs deleted file mode 100644 index 1d4169a88..000000000 --- a/old/src/ImageProcessor/Common/Exceptions/ImageFormatException.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The exception that is thrown when loading the supported image format types has failed. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Exceptions -{ - using System; - - /// - /// The exception that is thrown when loading the supported image format types has failed. - /// - [Serializable] - public sealed class ImageFormatException : Exception - { - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - public ImageFormatException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The error message that explains the reason for the exception. - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. - public ImageFormatException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} diff --git a/old/src/ImageProcessor/Common/Exceptions/ImageProcessingException.cs b/old/src/ImageProcessor/Common/Exceptions/ImageProcessingException.cs deleted file mode 100644 index 02b6be4f2..000000000 --- a/old/src/ImageProcessor/Common/Exceptions/ImageProcessingException.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The exception that is thrown when processing an image has failed. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Exceptions -{ - using System; - - /// - /// The exception that is thrown when processing an image has failed. - /// - [Serializable] - public sealed class ImageProcessingException : Exception - { - /// - /// Initializes a new instance of the class. - /// - /// The message that describes the error. - public ImageProcessingException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The error message that explains the reason for the exception. - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. - public ImageProcessingException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} diff --git a/old/src/ImageProcessor/Common/Exceptions/QuantizationException.cs b/old/src/ImageProcessor/Common/Exceptions/QuantizationException.cs deleted file mode 100644 index 7c2e17946..000000000 --- a/old/src/ImageProcessor/Common/Exceptions/QuantizationException.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The exception that is thrown when quantizing an image has failed. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Exceptions -{ - using System; - - /// - /// The exception that is thrown when quantizing an image has failed. - /// - [Serializable] - public class QuantizationException : Exception - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The message. - /// - public QuantizationException(string message) - : base(message) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The error message that explains the reason for the exception. - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. - public QuantizationException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} diff --git a/old/src/ImageProcessor/Common/Extensions/AssemblyExtensions.cs b/old/src/ImageProcessor/Common/Extensions/AssemblyExtensions.cs deleted file mode 100644 index 1f94afc53..000000000 --- a/old/src/ImageProcessor/Common/Extensions/AssemblyExtensions.cs +++ /dev/null @@ -1,115 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates a series of time saving extension methods to the class. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Extensions -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Text; - - /// - /// Encapsulates a series of time saving extension methods to the class. - /// - public static class AssemblyExtensions - { - /// - /// Gets a collection of loadable types from the given assembly. - /// Adapted from - /// - /// - /// The to load the types from. - /// - /// - /// The loadable . - /// - public static IEnumerable GetLoadableTypes(this Assembly assembly) - { - if (assembly == null) - { - throw new ArgumentNullException("assembly"); - } - - try - { - return assembly.GetTypes(); - } - catch (ReflectionTypeLoadException ex) - { - return ex.Types.Where(t => t != null); - } - } - - /// - /// Converts an assembly resource into a string. - /// - /// - /// The to load the strings from. - /// - /// - /// The resource. - /// - /// - /// The character encoding to return the resource in. - /// - /// - /// The . - /// - public static string GetResourceAsString(this Assembly assembly, string resource, Encoding encoding = null) - { - encoding = encoding ?? Encoding.UTF8; - - using (MemoryStream ms = new MemoryStream()) - { - using (Stream manifestResourceStream = assembly.GetManifestResourceStream(resource)) - { - if (manifestResourceStream != null) - { - manifestResourceStream.CopyTo(ms); - } - } - - return encoding.GetString(ms.GetBuffer()).Replace('\0', ' ').Trim(); - } - } - - /// - /// Returns the identifying the file used to load the assembly - /// - /// - /// The to get the name from. - /// - /// The - public static FileInfo GetAssemblyFile(this Assembly assembly) - { - string codeBase = assembly.CodeBase; - Uri uri = new Uri(codeBase); - string path = uri.LocalPath; - return new FileInfo(path); - } - - /// - /// Returns the identifying the file used to load the assembly - /// - /// - /// The to get the name from. - /// - /// The - public static FileInfo GetAssemblyFile(this AssemblyName assemblyName) - { - var codeBase = assemblyName.CodeBase; - var uri = new Uri(codeBase); - var path = uri.LocalPath; - return new FileInfo(path); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Common/Extensions/DoubleExtensions.cs b/old/src/ImageProcessor/Common/Extensions/DoubleExtensions.cs deleted file mode 100644 index 28fbeb217..000000000 --- a/old/src/ImageProcessor/Common/Extensions/DoubleExtensions.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates a series of time saving extension methods to the class. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Extensions -{ - using System; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates a series of time saving extension methods to the class. - /// - public static class DoubleExtensions - { - /// - /// Converts an value into a valid . - /// - /// If the value given is less than 0 or greater than 255, the value will be constrained into - /// those restricted ranges. - /// - /// - /// - /// The to convert. - /// - /// - /// The . - /// - public static byte ToByte(this double value) - { - return Convert.ToByte(ImageMaths.Clamp(value, 0, 255)); - } - } -} diff --git a/old/src/ImageProcessor/Common/Extensions/EnumerableExtensions.cs b/old/src/ImageProcessor/Common/Extensions/EnumerableExtensions.cs deleted file mode 100644 index 302ceaf78..000000000 --- a/old/src/ImageProcessor/Common/Extensions/EnumerableExtensions.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates a series of time saving extension methods to the interface. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Extensions -{ - using System; - using System.Collections.Generic; - - /// - /// Encapsulates a series of time saving extension methods to the interface. - /// - public static class EnumerableExtensions - { - /// - /// Generates a sequence of integral numbers within a specified range. - /// - /// - /// The start index, inclusive. - /// - /// - /// The end index, exclusive. - /// - /// - /// The incremental step. - /// - /// - /// The that contains a range of sequential integral numbers. - /// - public static IEnumerable SteppedRange(int fromInclusive, int toExclusive, int step) - { - // Borrowed from Enumerable.Range - long num = (fromInclusive + toExclusive) - 1L; - if ((toExclusive < 0) || (num > 0x7fffffffL)) - { - throw new ArgumentOutOfRangeException("toExclusive"); - } - - return RangeIterator(fromInclusive, i => i < toExclusive, step); - } - - /// - /// Generates a sequence of integral numbers within a specified range. - /// - /// - /// The start index, inclusive. - /// - /// - /// A method that has one parameter and returns a calculating the end index - /// - /// - /// The incremental step. - /// - /// - /// The that contains a range of sequential integral numbers. - /// - public static IEnumerable SteppedRange(int fromInclusive, Func toDelegate, int step) - { - return RangeIterator(fromInclusive, toDelegate, step); - } - - /// - /// Generates a sequence of integral numbers within a specified range. - /// - /// - /// The start index, inclusive. - /// - /// - /// A method that has one parameter and returns a calculating the end index - /// - /// - /// The incremental step. - /// - /// - /// The that contains a range of sequential integral numbers. - /// - private static IEnumerable RangeIterator(int fromInclusive, Func toDelegate, int step) - { - int i = fromInclusive; - while (toDelegate(i)) - { - yield return i; - i += step; - } - } - } -} diff --git a/old/src/ImageProcessor/Common/Extensions/IntegerExtensions.cs b/old/src/ImageProcessor/Common/Extensions/IntegerExtensions.cs deleted file mode 100644 index 467c46dcf..000000000 --- a/old/src/ImageProcessor/Common/Extensions/IntegerExtensions.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates a series of time saving extension methods to the class. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Extensions -{ - using System; - using System.Globalization; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates a series of time saving extension methods to the class. - /// - public static class IntegerExtensions - { - /// - /// Converts an value into a valid . - /// - /// If the value given is less than 0 or greater than 255, the value will be constrained into - /// those restricted ranges. - /// - /// - /// - /// The to convert. - /// - /// - /// The . - /// - public static byte ToByte(this int value) - { - return Convert.ToByte(ImageMaths.Clamp(value, 0, 255)); - } - - /// - /// Converts the string representation of a number in a specified culture-specific format to its - /// 32-bit signed integer equivalent using invariant culture. - /// - /// The integer. - /// A string containing a number to convert. - /// A 32-bit signed integer equivalent to the number specified in toParse. - public static int ParseInvariant(this int value, string toParse) - { - return int.Parse(toParse, CultureInfo.InvariantCulture); - } - } -} diff --git a/old/src/ImageProcessor/Common/Extensions/RectangleExtensions.cs b/old/src/ImageProcessor/Common/Extensions/RectangleExtensions.cs deleted file mode 100644 index a2e831026..000000000 --- a/old/src/ImageProcessor/Common/Extensions/RectangleExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace ImageProcessor.Common.Extensions -{ - using System; - using System.Drawing; - - internal static class RectangleExtensions - { - /// - /// Compares two rectangles for equality, considering an acceptance threshold. - /// - public static bool IsEqual(this Rectangle objA, Rectangle objB, int threshold) - { - return (Math.Abs(objA.X - objB.X) < threshold) && - (Math.Abs(objA.Y - objB.Y) < threshold) && - (Math.Abs(objA.Width - objB.Width) < threshold) && - (Math.Abs(objA.Height - objB.Height) < threshold); - } - } -} diff --git a/old/src/ImageProcessor/Common/Helpers/IOHelper.cs b/old/src/ImageProcessor/Common/Helpers/IOHelper.cs deleted file mode 100644 index 8e31874e0..000000000 --- a/old/src/ImageProcessor/Common/Helpers/IOHelper.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides helper method for traversing the file system. -// -// Adapted from identically named class within -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Helpers -{ - using System; - using System.Globalization; - using System.IO; - using System.Reflection; - - using ImageProcessor.Common.Extensions; - - /// - /// Provides helper method for traversing the file system. - /// - /// Adapted from identically named class within - /// - /// - internal class IOHelper - { - /// - /// The root directory. - /// - private static string rootDirectory; - - /// - /// Maps a virtual path to a physical path. - /// - /// - /// The virtual path to map. - /// - /// - /// The representing the physical path. - /// - public static string MapPath(string virtualPath) - { - // Check if the path is already mapped - // UNC Paths start with "\\". If the site is running off a network drive mapped paths - // will look like "\\Whatever\Boo\Bar" - if ((virtualPath.Length >= 2 && virtualPath[1] == Path.VolumeSeparatorChar) - || virtualPath.StartsWith(@"\\")) - { - return virtualPath; - } - - char separator = Path.DirectorySeparatorChar; - string root = GetRootDirectorySafe(); - string newPath = virtualPath.TrimStart('~', '/').Replace('/', separator); - return root + separator.ToString(CultureInfo.InvariantCulture) + newPath; - } - - /// - /// Gets the root directory bin folder for the currently running application. - /// - /// - /// The representing the root directory bin folder. - /// - public static string GetRootDirectoryBinFolder() - { - string binFolder = string.Empty; - if (string.IsNullOrEmpty(rootDirectory)) - { - DirectoryInfo directoryInfo = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory; - if (directoryInfo != null) - { - binFolder = directoryInfo.FullName; - } - - return binFolder; - } - - binFolder = Path.Combine(GetRootDirectorySafe(), "bin"); - -#if DEBUG - string debugFolder = Path.Combine(binFolder, "debug"); - if (Directory.Exists(debugFolder)) - { - return debugFolder; - } -#endif - string releaseFolder = Path.Combine(binFolder, "release"); - if (Directory.Exists(releaseFolder)) - { - return releaseFolder; - } - - if (Directory.Exists(binFolder)) - { - return binFolder; - } - - return rootDirectory; - } - - /// - /// Returns the path to the root of the application, by getting the path to where the assembly where this - /// method is included is present, then traversing until it's past the /bin directory. I.e. this makes it work - /// even if the assembly is in a /bin/debug or /bin/release folder - /// - /// - /// The representing the root path of the currently running application. - internal static string GetRootDirectorySafe() - { - if (string.IsNullOrEmpty(rootDirectory) == false) - { - return rootDirectory; - } - - string codeBase = Assembly.GetExecutingAssembly().CodeBase; - Uri uri = new Uri(codeBase); - string path = uri.LocalPath; - string baseDirectory = Path.GetDirectoryName(path); - if (string.IsNullOrEmpty(baseDirectory)) - { - throw new Exception( - "No root directory could be resolved. Please ensure that your solution is correctly configured."); - } - - rootDirectory = baseDirectory.Contains("bin") - ? baseDirectory.Substring(0, baseDirectory.LastIndexOf("bin", StringComparison.OrdinalIgnoreCase) - 1) - : baseDirectory; - - return rootDirectory; - } - } -} diff --git a/old/src/ImageProcessor/Common/Helpers/TypeFinder.cs b/old/src/ImageProcessor/Common/Helpers/TypeFinder.cs deleted file mode 100644 index 70257b5f0..000000000 --- a/old/src/ImageProcessor/Common/Helpers/TypeFinder.cs +++ /dev/null @@ -1,285 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// A utility class to find all classes of a certain type by reflection in the current bin folder -// of the web application. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Helpers -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Security; - using System.Threading; - - using ImageProcessor.Common.Extensions; - - /// - /// A utility class to find all classes of a certain type by reflection in the current bin folder - /// of the web application. - /// - /// - /// Adapted from identically named class within - /// - internal static class TypeFinder - { - /// - /// The local filtered assembly cache. - /// - private static readonly HashSet LocalFilteredAssemblyCache = new HashSet(); - - /// - /// The local filtered assembly cache locker. - /// - private static readonly ReaderWriterLockSlim LocalFilteredAssemblyCacheLocker = new ReaderWriterLockSlim(); - - /// - /// The reader-writer lock implementation. - /// - private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); - - /// - /// An assembly filter collection to filter out known types that definitely don't contain types - /// we'd like to find or plugins. - /// Umbraco uses ImageProcessor in it's core so add common exclusion files from that. - /// - /// - /// NOTE the comma versus period... comma delimits the name in an Assembly FullName property so - /// if it ends with comma then its an exact name match. - /// - private static readonly string[] KnownAssemblyExclusionFilter = - { - "mscorlib,", "System.", "Antlr3.", "Autofac.", - "Autofac,", "Castle.", "ClientDependency.", - "DataAnnotationsExtensions.", "Dynamic,", - "HtmlDiff,", "Iesi.Collections,", "log4net,", - "Microsoft.", "Newtonsoft.", "NHibernate.", - "NHibernate,", "NuGet.", "RouteDebugger,", - "SqlCE4Umbraco,", "umbraco.", - "Lucene.", "Examine,", "AutoMapper.", - "Examine.", "ServiceStack.", "MySql.", - "HtmlAgilityPack.", "TidyNet.", - "ICSharpCode.", "CookComputing.", - "AzureDirectory,", "itextsharp,", - "UrlRewritingNet.", "HtmlAgilityPack,", - "MiniProfiler,", "Moq,", "nunit.", - "TidyNet,", "WebDriver," - }; - - /// - /// A collection of all assemblies. - /// - private static HashSet allAssemblies; - - /// - /// The bin folder assemblies. - /// - private static HashSet binFolderAssemblies; - - /// - /// Lazily loads a reference to all assemblies and only local assemblies. - /// This is a modified version of: - /// - /// - /// - /// We do this because we cannot use AppDomain.Current.GetAssemblies() as this will return only assemblies that have been - /// loaded in the CLR, not all assemblies. - /// See these threads: - /// - /// - /// - /// - /// - /// The . - /// - internal static HashSet GetAllAssemblies() - { - using (UpgradeableReadLock locker = new UpgradeableReadLock(Locker)) - { - if (allAssemblies == null) - { - locker.UpgradeToWriteLock(); - - try - { - // NOTE: we cannot use AppDomain.CurrentDomain.GetAssemblies() because this only returns assemblies that have - // already been loaded in to the app domain, instead we will look directly into the bin folder and load each one. - string binFolder = IOHelper.GetRootDirectoryBinFolder(); - List binAssemblyFiles = Directory.GetFiles(binFolder, "*.dll", SearchOption.TopDirectoryOnly).ToList(); - HashSet assemblies = new HashSet(); - - foreach (string file in binAssemblyFiles) - { - try - { - AssemblyName assemblyName = AssemblyName.GetAssemblyName(file); - assemblies.Add(Assembly.Load(assemblyName)); - } - catch (Exception ex) - { - if (ex is SecurityException || ex is BadImageFormatException) - { - // Swallow exception but allow debugging. - Debug.WriteLine(ex.Message); - } - else - { - throw; - } - } - } - - // If for some reason they are still no assemblies, then use the AppDomain to load in already loaded assemblies. - if (!assemblies.Any()) - { - foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) - { - assemblies.Add(assembly); - } - } - - // Here we are trying to get the App_Code assembly - string[] fileExtensions = { ".cs", ".vb" }; - DirectoryInfo appCodeFolder = new DirectoryInfo(IOHelper.MapPath("~/App_code")); - - // Check if the folder exists and if there are any files in it with the supported file extensions - if (appCodeFolder.Exists && fileExtensions.Any(x => appCodeFolder.GetFiles("*" + x).Any())) - { - Assembly appCodeAssembly = Assembly.Load("App_Code"); - if (!assemblies.Contains(appCodeAssembly)) - { - assemblies.Add(appCodeAssembly); - } - } - - // Now set the allAssemblies - allAssemblies = new HashSet(assemblies); - } - catch (InvalidOperationException e) - { - if (!(e.InnerException is SecurityException)) - { - throw; - } - - binFolderAssemblies = allAssemblies; - } - } - - return allAssemblies; - } - } - - /// - /// Returns only assemblies found in the bin folder that have been loaded into the app domain. - /// - /// - /// The collection of assemblies. - /// - internal static HashSet GetBinAssemblies() - { - if (binFolderAssemblies == null) - { - using (new WriteLock(Locker)) - { - Assembly[] assemblies = GetAssembliesWithKnownExclusions().ToArray(); - DirectoryInfo binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory; - // ReSharper disable once PossibleNullReferenceException - List binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList(); - IEnumerable domainAssemblyNames = binAssemblyFiles.Select(AssemblyName.GetAssemblyName); - HashSet safeDomainAssemblies = new HashSet(); - HashSet binFolderAssemblyList = new HashSet(); - - foreach (Assembly assembly in assemblies) - { - safeDomainAssemblies.Add(assembly); - } - - foreach (AssemblyName assemblyName in domainAssemblyNames) - { - Assembly foundAssembly = safeDomainAssemblies - .FirstOrDefault(a => a.GetAssemblyFile() == assemblyName.GetAssemblyFile()); - - if (foundAssembly != null) - { - binFolderAssemblyList.Add(foundAssembly); - } - } - - binFolderAssemblies = new HashSet(binFolderAssemblyList); - } - } - - return binFolderAssemblies; - } - - /// - /// Return a list of found local Assemblies excluding the known assemblies we don't want to scan - /// and excluding the ones passed in and excluding the exclusion list filter, the results of this are - /// cached for performance reasons. - /// - /// - /// An to exclude. - /// - /// The collection of local assemblies. - internal static HashSet GetAssembliesWithKnownExclusions( - IEnumerable excludeFromResults = null) - { - using (UpgradeableReadLock locker = new UpgradeableReadLock(LocalFilteredAssemblyCacheLocker)) - { - if (LocalFilteredAssemblyCache.Any()) - { - return LocalFilteredAssemblyCache; - } - - locker.UpgradeToWriteLock(); - - IEnumerable assemblies = GetFilteredAssemblies(excludeFromResults, KnownAssemblyExclusionFilter); - foreach (Assembly assembly in assemblies) - { - LocalFilteredAssemblyCache.Add(assembly); - } - - return LocalFilteredAssemblyCache; - } - } - - /// - /// Return a distinct list of found local Assemblies and excluding the ones passed in and excluding the exclusion list filter - /// - /// - /// An to exclude. - /// - /// - /// An array containing exclusion filters. - /// - /// The collection of filtered local assemblies. - private static IEnumerable GetFilteredAssemblies( - IEnumerable excludeFromResults = null, - string[] exclusionFilter = null) - { - if (excludeFromResults == null) - { - excludeFromResults = new HashSet(); - } - - if (exclusionFilter == null) - { - exclusionFilter = new string[] { }; - } - - return GetAllAssemblies() - .Where(x => !excludeFromResults.Contains(x) - && !x.GlobalAssemblyCache - && !exclusionFilter.Any(f => x.FullName.StartsWith(f, StringComparison.OrdinalIgnoreCase))); - } - } -} diff --git a/old/src/ImageProcessor/Common/Helpers/UpgradeableReadLock.cs b/old/src/ImageProcessor/Common/Helpers/UpgradeableReadLock.cs deleted file mode 100644 index fca1fb407..000000000 --- a/old/src/ImageProcessor/Common/Helpers/UpgradeableReadLock.cs +++ /dev/null @@ -1,126 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides a convenience methodology for implementing upgradeable locked access to resources. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Helpers -{ - using System; - using System.Threading; - - /// - /// Provides a convenience methodology for implementing upgradeable locked access to resources. - /// - /// - /// Adapted from identically named class within - /// - internal sealed class UpgradeableReadLock : IDisposable - { - /// - /// The locker to lock against. - /// - private readonly ReaderWriterLockSlim locker; - - /// - /// A value indicating whether the locker has been upgraded to a writeable lock. - /// - private bool upgraded; - - /// - /// A value indicating whether this instance of the given entity has been disposed. - /// - /// if this instance has been disposed; otherwise, . - /// - /// If the entity is disposed, it must not be disposed a second - /// time. The isDisposed field is set the first time the entity - /// is disposed. If the isDisposed field is true, then the Dispose() - /// method will not dispose again. This help not to prolong the entity's - /// life in the Garbage Collector. - /// - private bool isDisposed; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The locker. - /// - public UpgradeableReadLock(ReaderWriterLockSlim locker) - { - this.locker = locker; - this.locker.EnterUpgradeableReadLock(); - } - - /// - /// Finalizes an instance of the class. - /// - /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// - ~UpgradeableReadLock() - { - // Do not re-create Dispose clean-up code here. - // Calling Dispose(false) is optimal in terms of - // readability and maintainability. - this.Dispose(false); - } - - /// - /// Tries to enter the locker in write mode. - /// - public void UpgradeToWriteLock() - { - this.locker.EnterWriteLock(); - this.upgraded = true; - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - public void Dispose() - { - this.Dispose(true); - - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - /// If true, the object gets disposed. - private void Dispose(bool disposing) - { - if (this.isDisposed) - { - return; - } - - if (disposing) - { - if (this.upgraded) - { - this.locker.ExitWriteLock(); - } - - this.locker.ExitUpgradeableReadLock(); - } - - // Note disposing is done. - this.isDisposed = true; - } - } -} diff --git a/old/src/ImageProcessor/Common/Helpers/WriteLock.cs b/old/src/ImageProcessor/Common/Helpers/WriteLock.cs deleted file mode 100644 index 7037fde9e..000000000 --- a/old/src/ImageProcessor/Common/Helpers/WriteLock.cs +++ /dev/null @@ -1,107 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides a convenience methodology for implementing writeable locked access to resources. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Common.Helpers -{ - using System; - using System.Threading; - - /// - /// Provides a convenience methodology for implementing writable locked access to resources. - /// - /// - /// Adapted from identically named class within - /// - internal sealed class WriteLock : IDisposable - { - /// - /// The locker to lock against. - /// - private readonly ReaderWriterLockSlim locker; - - /// - /// A value indicating whether this instance of the given entity has been disposed. - /// - /// if this instance has been disposed; otherwise, . - /// - /// If the entity is disposed, it must not be disposed a second - /// time. The isDisposed field is set the first time the entity - /// is disposed. If the isDisposed field is true, then the Dispose() - /// method will not dispose again. This help not to prolong the entity's - /// life in the Garbage Collector. - /// - private bool isDisposed; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The locker. - /// - public WriteLock(ReaderWriterLockSlim locker) - { - this.locker = locker; - this.locker.EnterWriteLock(); - } - - /// - /// Finalizes an instance of the class. - /// - /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// - ~WriteLock() - { - // Do not re-create Dispose clean-up code here. - // Calling Dispose(false) is optimal in terms of - // readability and maintainability. - this.Dispose(false); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - public void Dispose() - { - this.Dispose(true); - - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - /// If true, the object gets disposed. - private void Dispose(bool disposing) - { - if (this.isDisposed) - { - return; - } - - if (disposing) - { - this.locker.ExitWriteLock(); - } - - // Note disposing is done. - this.isDisposed = true; - } - } -} diff --git a/old/src/ImageProcessor/Configuration/ImageProcessorBootstrapper.cs b/old/src/ImageProcessor/Configuration/ImageProcessorBootstrapper.cs deleted file mode 100644 index 30ff475bb..000000000 --- a/old/src/ImageProcessor/Configuration/ImageProcessorBootstrapper.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The ImageProcessor bootstrapper containing initialization code for extending ImageProcessor. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Configuration -{ - using System; - using System.Collections.Generic; - using System.Linq; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Common.Helpers; - using ImageProcessor.Imaging.Formats; - - /// - /// The ImageProcessor bootstrapper containing initialization code for extending ImageProcessor. - /// - public class ImageProcessorBootstrapper - { - /// - /// A new instance Initializes a new instance of the class. - /// with lazy initialization. - /// - private static readonly Lazy Lazy = - new Lazy(() => new ImageProcessorBootstrapper()); - - /// - /// Prevents a default instance of the class from being created. - /// - private ImageProcessorBootstrapper() - { - this.NativeBinaryFactory = new NativeBinaryFactory(); - this.LoadSupportedImageFormats(); - } - - /// - /// Gets the current instance of the class. - /// - public static ImageProcessorBootstrapper Instance - { - get - { - return Lazy.Value; - } - } - - /// - /// Gets the supported image formats. - /// - public IEnumerable SupportedImageFormats { get; private set; } - - /// - /// Gets the native binary factory for registering embedded (unmanaged) binaries. - /// - public NativeBinaryFactory NativeBinaryFactory { get; private set; } - - /// - /// Creates a list, using reflection, of supported image formats that ImageProcessor can run. - /// - private void LoadSupportedImageFormats() - { - Type type = typeof(ISupportedImageFormat); - if (this.SupportedImageFormats == null) - { - List availableTypes = - TypeFinder.GetAssembliesWithKnownExclusions() - .SelectMany(a => a.GetLoadableTypes()) - .Where(t => type.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract) - .ToList(); - - this.SupportedImageFormats = - availableTypes.Select(f => (Activator.CreateInstance(f) as ISupportedImageFormat)) - .ToList(); - } - } - } -} diff --git a/old/src/ImageProcessor/Configuration/NativeBinaryFactory.cs b/old/src/ImageProcessor/Configuration/NativeBinaryFactory.cs deleted file mode 100644 index 1f939fe5d..000000000 --- a/old/src/ImageProcessor/Configuration/NativeBinaryFactory.cs +++ /dev/null @@ -1,216 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Controls the loading and unloading of any native binaries required by ImageProcessor. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Configuration -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Reflection; - - /// - /// Controls the loading and unloading of any native binaries required by ImageProcessor. - /// - public class NativeBinaryFactory : IDisposable - { - /// - /// Whether the process is running in 64bit mode. Used for calling the correct dllimport method. - /// - private static readonly bool Is64Bit = Environment.Is64BitProcess; - - /// - /// The native binaries. - /// - private static ConcurrentDictionary nativeBinaries; - - /// - /// A value indicating whether this instance of the given entity has been disposed. - /// - /// if this instance has been disposed; otherwise, . - /// - /// If the entity is disposed, it must not be disposed a second - /// time. The isDisposed field is set the first time the entity - /// is disposed. If the isDisposed field is true, then the Dispose() - /// method will not dispose again. This help not to prolong the entity's - /// life in the Garbage Collector. - /// - private bool isDisposed; - - /// - /// Initializes a new instance of the class. - /// - public NativeBinaryFactory() - { - nativeBinaries = new ConcurrentDictionary(); - } - - /// - /// Finalizes an instance of the ImageFactory class. - /// - /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// - ~NativeBinaryFactory() - { - // Do not re-create Dispose clean-up code here. - // Calling Dispose(false) is optimal in terms of - // readability and maintainability. - this.Dispose(false); - } - - /// - /// Gets a value indicating whether the operating environment is 64 bit. - /// - public bool Is64BitEnvironment - { - get - { - return Is64Bit; - } - } - - /// - /// Registers any embedded native (unmanaged) binaries required by ImageProcessor. - /// - /// - /// The name of the native binary. - /// - /// - /// The resource bytes containing the native binary. - /// - /// - /// Thrown if the binary cannot be registered. - /// - public void RegisterNativeBinary(string name, byte[] resourceBytes) - { - nativeBinaries.GetOrAdd( - name, - b => - { - IntPtr pointer; - string folder = Is64BitEnvironment ? "x64" : "x86"; - Assembly assembly = Assembly.GetExecutingAssembly(); - string targetBasePath = new Uri(assembly.Location).LocalPath; - string targetPath = Path.GetFullPath(Path.Combine(targetBasePath, "..\\" + folder + "\\" + name)); - - // Copy the file across if necessary. - FileInfo fileInfo = new FileInfo(targetPath); - bool rewrite = true; - if (fileInfo.Exists) - { - byte[] existing = File.ReadAllBytes(targetPath); - - if (resourceBytes.SequenceEqual(existing)) - { - rewrite = false; - } - } - - if (rewrite) - { - // ReSharper disable once AssignNullToNotNullAttribute - DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(targetPath)); - if (!directoryInfo.Exists) - { - directoryInfo.Create(); - } - - File.WriteAllBytes(targetPath, resourceBytes); - } - - try - { -#if !__MonoCS__ - // Load the binary into memory. - pointer = NativeMethods.LoadLibrary(targetPath); -#else - // Load the binary into memory. The second parameter forces it to load immediately. - pointer = NativeMethods.dlopen(targetPath, 2); -#endif - } - catch (Exception ex) - { - throw new ApplicationException(ex.Message); - } - - if (pointer == IntPtr.Zero) - { - throw new ApplicationException("Cannot load " + name); - } - - return pointer; - }); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - public void Dispose() - { - this.Dispose(true); - - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - /// If true, the object gets disposed. - protected virtual void Dispose(bool disposing) - { - if (this.isDisposed) - { - return; - } - - if (disposing) - { - // Dispose of any managed resources here. - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - this.FreeNativeBinaries(); - - // Note disposing is done. - this.isDisposed = true; - } - - /// - /// Frees the reference to the native binaries. - /// - private void FreeNativeBinaries() - { - foreach (KeyValuePair nativeBinary in nativeBinaries) - { - IntPtr pointer = nativeBinary.Value; - -#if !__MonoCS__ - // According to http://stackoverflow.com/a/2445558/427899 you need to call this twice. - NativeMethods.FreeLibrary(pointer); - NativeMethods.FreeLibrary(pointer); -#else - NativeMethods.dlclose(pointer); -#endif - } - } - } -} diff --git a/old/src/ImageProcessor/Configuration/NativeMethods.cs b/old/src/ImageProcessor/Configuration/NativeMethods.cs deleted file mode 100644 index 895de7fe5..000000000 --- a/old/src/ImageProcessor/Configuration/NativeMethods.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides access to unmanaged native methods. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Configuration -{ - using System; - using System.Runtime.InteropServices; - - /// - /// Provides access to unmanaged native methods. - /// - internal class NativeMethods - { - /// - /// Loads the specified module into the address space of the calling process. - /// The specified module may cause other modules to be loaded. - /// - /// - /// The name of the module. This can be either a library module or - /// an executable module. - /// - /// If the function succeeds, the return value is a handle to the module; otherwise null. - [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Auto)] - public static extern IntPtr LoadLibrary(string libname); - - /// - /// Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. - /// When the reference count reaches zero, the module is unloaded from the address space of the calling - /// process and the handle is no longer valid. - /// - /// A handle to the loaded library module. - /// The LoadLibrary, LoadLibraryEx, GetModuleHandle, or GetModuleHandleEx function returns this handle. - /// If the function succeeds, the return value is nonzero; otherwise zero. - [DllImport("kernel32", SetLastError = true)] - public static extern bool FreeLibrary(IntPtr hModule); - - /// - /// Loads the specified module into the address space of the calling process. - /// The specified module may cause other modules to be loaded. - /// - /// - /// The name of the module. This can be either a library module or - /// an executable module. - /// - /// - /// The flag indicating whether to load the library immediately or lazily. - /// - /// - /// If the function succeeds, the return value is a handle to the module; otherwise null. - /// - [System.Runtime.InteropServices.DllImport("libdl")] - public static extern IntPtr dlopen(string libname, int flags); - - /// - /// Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count. - /// When the reference count reaches zero, the module is unloaded from the address space of the calling - /// process and the handle is no longer valid. - /// - /// A handle to the loaded library module. - /// The LoadLibrary, LoadLibraryEx, GetModuleHandle, or GetModuleHandleEx function returns this handle. - /// If the function succeeds, the return value is nonzero; otherwise zero. - [System.Runtime.InteropServices.DllImport("libdl")] - public static extern int dlclose(IntPtr hModule); - } -} diff --git a/old/src/ImageProcessor/ImageFactory.cs b/old/src/ImageProcessor/ImageFactory.cs deleted file mode 100644 index 4c18e0e3d..000000000 --- a/old/src/ImageProcessor/ImageFactory.cs +++ /dev/null @@ -1,1286 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods for processing image files. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor -{ - #region Using - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Filters.EdgeDetection; - //using ImageProcessor.Imaging.Filters.ObjectDetection; - using ImageProcessor.Imaging.Filters.Photo; - using ImageProcessor.Imaging.Formats; - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Processors; - #endregion - - /// - /// Encapsulates methods for processing image files. - /// - public class ImageFactory : IDisposable - { - #region Fields - /// - /// The default quality for image files. - /// - private const int DefaultQuality = 90; - - /// - /// The backup supported image format. - /// - private ISupportedImageFormat backupFormat; - - /// - /// A value indicating whether this instance of the given entity has been disposed. - /// - /// if this instance has been disposed; otherwise, . - /// - /// If the entity is disposed, it must not be disposed a second - /// time. The isDisposed field is set the first time the entity - /// is disposed. If the isDisposed field is true, then the Dispose() - /// method will not dispose again. This help not to prolong the entity's - /// life in the Garbage Collector. - /// - private bool isDisposed; - #endregion - - #region Constructors - /// - /// Initializes a new instance of the class. - /// - /// - /// Whether to preserve exif metadata. Defaults to false. - /// - public ImageFactory(bool preserveExifData = false) - : this(preserveExifData, true) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// Whether to preserve exif metadata. Defaults to false. - /// - /// - /// Whether to fix the gamma component of the image. Defaults to true. - /// - public ImageFactory(bool preserveExifData, bool fixGamma) - { - this.PreserveExifData = preserveExifData; - this.ExifPropertyItems = new ConcurrentDictionary(); - this.FixGamma = fixGamma; - } - #endregion - - #region Destructors - /// - /// Finalizes an instance of the ImageFactory class. - /// - /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. - /// - ~ImageFactory() - { - // Do not re-create Dispose clean-up code here. - // Calling Dispose(false) is optimal in terms of - // readability and maintainability. - this.Dispose(false); - } - #endregion - - #region Properties - /// - /// Gets the path to the local image for manipulation. - /// - public string ImagePath { get; private set; } - - /// - /// Gets a value indicating whether the image factory should process the file. - /// - public bool ShouldProcess { get; private set; } - - /// - /// Gets the supported image format. - /// - public ISupportedImageFormat CurrentImageFormat { get; private set; } - - /// - /// Gets or sets a value indicating whether to preserve exif metadata. - /// - public bool PreserveExifData { get; set; } - - /// - /// Gets or sets a value indicating whether to fix the gamma component of the current image. - /// - public bool FixGamma { get; set; } - - /// - /// Gets or the current gamma value. - /// - public float CurrentGamma { get; private set; } - - /// - /// Gets or sets the exif property items. - /// - public ConcurrentDictionary ExifPropertyItems { get; set; } - - /// - /// Gets or the local image for manipulation. - /// - public Image Image { get; internal set; } - - /// - /// Gets or sets the stream for storing any input stream to prevent disposal. - /// - internal Stream InputStream { get; set; } - #endregion - - #region Methods - /// - /// Loads the image to process. Always call this method first. - /// - /// - /// The containing the image information. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Load(Stream stream) - { - // Reset the position of the stream to ensure we're reading the correct part. - stream.Position = 0; - - ISupportedImageFormat format = FormatUtilities.GetFormat(stream); - - if (format == null) - { - throw new ImageFormatException("Input stream is not a supported format."); - } - - MemoryStream memoryStream = new MemoryStream(); - - // Copy the stream. Disposal of the input stream is the responsibility - // of the user. - stream.CopyTo(memoryStream); - - // Set the position to 0 afterwards. - stream.Position = memoryStream.Position = 0; - - // Set our image as the memory stream value. - this.Image = format.Load(memoryStream); - - // Store the stream so we can dispose of it later. - this.InputStream = memoryStream; - - // Set the other properties. - format.Quality = DefaultQuality; - format.IsIndexed = FormatUtilities.IsIndexed(this.Image); - - IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat; - if (imageFormat != null) - { - imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image); - } - - this.backupFormat = format; - this.CurrentImageFormat = format; - - // Always load the data. - // TODO. Some custom data doesn't seem to get copied by default methods. - foreach (int id in this.Image.PropertyIdList) - { - this.ExifPropertyItems[id] = this.Image.GetPropertyItem(id); - } - - this.ShouldProcess = true; - - // Normalize the gamma component of the image. - if (this.FixGamma) - { - this.Gamma(2.2F); - } - - return this; - } - - /// - /// Loads the image to process. Always call this method first. - /// - /// The absolute path to the image to load. - /// - /// The current instance of the class. - /// - public ImageFactory Load(string imagePath) - { - FileInfo fileInfo = new FileInfo(imagePath); - if (fileInfo.Exists) - { - this.ImagePath = imagePath; - - // Open a file stream to prevent the need for lock. - using (FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) - { - ISupportedImageFormat format = FormatUtilities.GetFormat(fileStream); - - if (format == null) - { - throw new ImageFormatException("Input stream is not a supported format."); - } - - MemoryStream memoryStream = new MemoryStream(); - - // Copy the stream. - fileStream.CopyTo(memoryStream); - - // Set the position to 0 afterwards. - fileStream.Position = memoryStream.Position = 0; - - // Set our image as the memory stream value. - this.Image = format.Load(memoryStream); - - // Store the stream so we can dispose of it later. - this.InputStream = memoryStream; - - // Set the other properties. - format.Quality = DefaultQuality; - format.IsIndexed = FormatUtilities.IsIndexed(this.Image); - - IQuantizableImageFormat imageFormat = format as IQuantizableImageFormat; - if (imageFormat != null) - { - imageFormat.ColorCount = FormatUtilities.GetColorCount(this.Image); - } - - this.backupFormat = format; - this.CurrentImageFormat = format; - - // Always load the data. - foreach (PropertyItem propertyItem in this.Image.PropertyItems) - { - this.ExifPropertyItems[propertyItem.Id] = propertyItem; - } - - this.ShouldProcess = true; - - // Normalize the gamma component of the image. - if (this.FixGamma) - { - this.Gamma(2.2F); - } - } - } - else - { - throw new FileNotFoundException(imagePath); - } - - return this; - } - - /// - /// Resets the current image to its original loaded state. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Reset() - { - if (this.ShouldProcess) - { - // Set our new image as the memory stream value. - this.InputStream.Position = 0; - -#if !__MonoCS__ - Image newImage = Image.FromStream(this.InputStream, true); -#else - Image newImage = Image.FromStream(this.InputStream); -#endif - - // Dispose and reassign the image. - this.Image.Dispose(); - this.Image = newImage; - - // Set the other properties. - this.CurrentImageFormat = this.backupFormat; - this.CurrentImageFormat.Quality = DefaultQuality; - } - - return this; - } - - #region Manipulation - /// - /// Changes the opacity of the current image. - /// - /// - /// The percentage by which to alter the images opacity. - /// Any integer between 0 and 100. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Alpha(int percentage) - { - if (this.ShouldProcess) - { - // Sanitize the input. - percentage = ImageMaths.Clamp(percentage, 0, 100); - - Alpha alpha = new Alpha { DynamicParameter = percentage }; - this.CurrentImageFormat.ApplyProcessor(alpha.ProcessImage, this); - } - - return this; - } - - /// - /// Performs auto-rotation to ensure that EXIF defined rotation is reflected in - /// the final image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory AutoRotate() - { - if (this.ShouldProcess) - { - AutoRotate autoRotate = new AutoRotate(); - this.CurrentImageFormat.ApplyProcessor(autoRotate.ProcessImage, this); - } - - return this; - } - - /// - /// Changes the brightness of the current image. - /// - /// - /// The percentage by which to alter the images brightness. - /// Any integer between -100 and 100. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Brightness(int percentage) - { - if (this.ShouldProcess) - { - // Sanitize the input. - if (percentage > 100 || percentage < -100) - { - percentage = 0; - } - - Brightness brightness = new Brightness { DynamicParameter = percentage }; - this.CurrentImageFormat.ApplyProcessor(brightness.ProcessImage, this); - } - - return this; - } - - /// - /// Changes the background color of the current image. - /// - /// - /// The to paint the image with. - /// - /// - /// The current instance of the class. - /// - public ImageFactory BackgroundColor(Color color) - { - if (this.ShouldProcess) - { - BackgroundColor backgroundColor = new BackgroundColor { DynamicParameter = color }; - this.CurrentImageFormat.ApplyProcessor(backgroundColor.ProcessImage, this); - } - - return this; - } - - /// - /// Constrains the current image, resizing it to fit within the given dimensions whilst keeping its aspect ratio. - /// - /// - /// The containing the maximum width and height to set the image to. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Constrain(Size size) - { - if (this.ShouldProcess) - { - ResizeLayer layer = new ResizeLayer(size, ResizeMode.Max); - - return this.Resize(layer); - } - - return this; - } - - /// - /// Changes the contrast of the current image. - /// - /// - /// The percentage by which to alter the images contrast. - /// Any integer between -100 and 100. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Contrast(int percentage) - { - if (this.ShouldProcess) - { - // Sanitize the input. - if (percentage > 100 || percentage < -100) - { - percentage = 0; - } - - Contrast contrast = new Contrast { DynamicParameter = percentage }; - this.CurrentImageFormat.ApplyProcessor(contrast.ProcessImage, this); - } - - return this; - } - - /// - /// Crops the current image to the given location and size. - /// - /// - /// The containing the coordinates to crop the image to. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Crop(Rectangle rectangle) - { - if (this.ShouldProcess) - { - CropLayer cropLayer = new CropLayer(rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height, CropMode.Pixels); - return this.Crop(cropLayer); - } - - return this; - } - - /// - /// Crops the current image to the given location and size. - /// - /// - /// The containing the coordinates and mode to crop the image with. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Crop(CropLayer cropLayer) - { - if (this.ShouldProcess) - { - Crop crop = new Crop { DynamicParameter = cropLayer }; - this.CurrentImageFormat.ApplyProcessor(crop.ProcessImage, this); - } - - return this; - } - - /// - /// Detects the edges in the current image. - /// - /// - /// The to detect edges with. - /// - /// - /// Whether to convert the image to greyscale first - Defaults to true. - /// - /// - /// The current instance of the class. - /// - public ImageFactory DetectEdges(IEdgeFilter filter, bool greyscale = true) - { - if (this.ShouldProcess) - { - DetectEdges detectEdges = new DetectEdges { DynamicParameter = new Tuple(filter, greyscale) }; - this.CurrentImageFormat.ApplyProcessor(detectEdges.ProcessImage, this); - } - - return this; - } - - //public ImageFactory DetectObjects(HaarCascade cascade, bool drawRectangles = true, Color color = default(Color)) - //{ - // if (this.ShouldProcess) - // { - // DetectObjects detectObjects = new DetectObjects { DynamicParameter = cascade }; - // this.CurrentImageFormat.ApplyProcessor(detectObjects.ProcessImage, this); - // } - - // return this; - //} - - /// - /// Crops an image to the area of greatest entropy. - /// - /// - /// The threshold in bytes to control the entropy. - /// - /// - /// The current instance of the class. - /// - public ImageFactory EntropyCrop(byte threshold = 128) - { - if (this.ShouldProcess) - { - EntropyCrop autoCrop = new EntropyCrop { DynamicParameter = threshold }; - this.CurrentImageFormat.ApplyProcessor(autoCrop.ProcessImage, this); - } - - return this; - } - - /// - /// Applies a filter to the current image. Use the class to - /// assign the correct filter. - /// - /// - /// The of the filter to add to the image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Filter(IMatrixFilter matrixFilter) - { - if (this.ShouldProcess) - { - Filter filter = new Filter { DynamicParameter = matrixFilter }; - this.CurrentImageFormat.ApplyProcessor(filter.ProcessImage, this); - } - - return this; - } - - /// - /// Flips the current image either horizontally or vertically. - /// - /// - /// Whether to flip the image vertically. - /// - /// - /// Whether to flip the image both vertically and horizontally. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Flip(bool flipVertically = false, bool flipBoth = false) - { - if (this.ShouldProcess) - { - RotateFlipType rotateFlipType; - if (flipBoth) - { - rotateFlipType = RotateFlipType.RotateNoneFlipXY; - } - else - { - rotateFlipType = flipVertically - ? RotateFlipType.RotateNoneFlipY - : RotateFlipType.RotateNoneFlipX; - } - - Flip flip = new Flip { DynamicParameter = rotateFlipType }; - this.CurrentImageFormat.ApplyProcessor(flip.ProcessImage, this); - } - - return this; - } - - /// - /// Sets the output format of the current image to the matching . - /// - /// The . to set the image to. - /// - /// The current instance of the class. - /// - public ImageFactory Format(ISupportedImageFormat format) - { - if (this.ShouldProcess) - { - this.CurrentImageFormat = format; - } - - return this; - } - - /// - /// Adjust the gamma (intensity of the light) component of the given image. - /// - /// - /// The value to adjust the gamma by (typically between .2 and 5). - /// - /// - /// The current instance of the class. - /// - public ImageFactory Gamma(float value) - { - if (this.ShouldProcess) - { - // Sanitize the input. - if (value > 5 || value < .1) - { - value = 2.2F; - } - - this.CurrentGamma = value; - Gamma gamma = new Gamma { DynamicParameter = value }; - this.CurrentImageFormat.ApplyProcessor(gamma.ProcessImage, this); - } - - return this; - } - - /// - /// Uses a Gaussian kernel to blur the current image. - /// - /// - /// The sigma and threshold values applied to the kernel are - /// 1.4 and 0 respectively. - /// - /// - /// - /// - /// The size to set the Gaussian kernel to. - /// - /// - /// The current instance of the class. - /// - public ImageFactory GaussianBlur(int size) - { - if (this.ShouldProcess && size > 0) - { - GaussianLayer layer = new GaussianLayer(size); - return this.GaussianBlur(layer); - } - - return this; - } - - /// - /// Uses a Gaussian kernel to blur the current image. - /// - /// - /// The for applying sharpening and - /// blurring methods to an image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory GaussianBlur(GaussianLayer gaussianLayer) - { - if (this.ShouldProcess) - { - GaussianBlur gaussianBlur = new GaussianBlur { DynamicParameter = gaussianLayer }; - this.CurrentImageFormat.ApplyProcessor(gaussianBlur.ProcessImage, this); - } - - return this; - } - - /// - /// Uses a Gaussian kernel to sharpen the current image. - /// - /// - /// The sigma and threshold values applied to the kernel are - /// 1.4 and 0 respectively. - /// - /// - /// - /// - /// The size to set the Gaussian kernel to. - /// - /// - /// The current instance of the class. - /// - public ImageFactory GaussianSharpen(int size) - { - if (this.ShouldProcess && size > 0) - { - GaussianLayer layer = new GaussianLayer(size); - return this.GaussianSharpen(layer); - } - - return this; - } - - /// - /// Uses a Gaussian kernel to sharpen the current image. - /// - /// - /// The for applying sharpening and - /// blurring methods to an image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory GaussianSharpen(GaussianLayer gaussianLayer) - { - if (this.ShouldProcess) - { - GaussianSharpen gaussianSharpen = new GaussianSharpen { DynamicParameter = gaussianLayer }; - this.CurrentImageFormat.ApplyProcessor(gaussianSharpen.ProcessImage, this); - } - - return this; - } - - /// - /// Alters the hue of the current image changing the overall color. - /// - /// - /// The angle by which to alter the images hue. - /// Any integer between 0 and 360. - /// - /// - /// Whether to rotate the hue of the current image altering each color - /// - /// - /// The current instance of the class. - /// - public ImageFactory Hue(int degrees, bool rotate = false) - { - // Sanitize the input. - if (degrees > 360 || degrees < 0) - { - degrees = 0; - } - - if (this.ShouldProcess && degrees > 0) - { - Hue hue = new Hue { DynamicParameter = new Tuple(degrees, rotate) }; - this.CurrentImageFormat.ApplyProcessor(hue.ProcessImage, this); - } - - return this; - } - - /// - /// Converts the current image to a CMYK halftone representation of that image. - /// - /// - /// Whether to trace over the current image and add borders to add a comic book effect. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Halftone(bool comicMode = false) - { - if (this.ShouldProcess) - { - Halftone halftone = new Halftone { DynamicParameter = comicMode }; - this.CurrentImageFormat.ApplyProcessor(halftone.ProcessImage, this); - } - - return this; - } - - /// - /// Applies the given image mask to the current image. - /// - /// - /// The image containing the mask to apply. - /// - /// - /// The to place the mask if it not the same dimensions as the original image. - /// If no position is set, the mask will be centered within the image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Mask(Image imageMask, Point? point = null) - { - if (this.ShouldProcess) - { - Mask mask = new Mask { DynamicParameter = new Tuple(imageMask, point) }; - this.CurrentImageFormat.ApplyProcessor(mask.ProcessImage, this); - } - - return this; - } - - /// - /// Adds a image overlay to the current image. - /// - /// - /// The containing the properties necessary to add - /// the image overlay to the image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Overlay(ImageLayer imageLayer) - { - if (this.ShouldProcess) - { - Overlay watermark = new Overlay { DynamicParameter = imageLayer }; - this.CurrentImageFormat.ApplyProcessor(watermark.ProcessImage, this); - } - - return this; - } - - /// - /// Pixelates an image with the given size. - /// - /// - /// The size of the pixels to create. - /// - /// The area in which to pixelate the image. If not set, the whole image is pixelated. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Pixelate(int pixelSize, Rectangle? rectangle = null) - { - if (this.ShouldProcess && pixelSize > 0) - { - Pixelate pixelate = new Pixelate { DynamicParameter = new Tuple(pixelSize, rectangle) }; - this.CurrentImageFormat.ApplyProcessor(pixelate.ProcessImage, this); - } - - return this; - } - - /// - /// Alters the output quality of the current image. - /// - /// This method will only effect the output quality of jpeg images - /// - /// - /// A value between 1 and 100 to set the quality to. - /// - /// The current instance of the class. - /// - public ImageFactory Quality(int percentage) - { - if (percentage <= 100 && percentage >= 0 && this.ShouldProcess) - { - this.CurrentImageFormat.Quality = percentage; - } - - return this; - } - - /// - /// Replaces a color within the current image. - /// - /// - /// The target . - /// - /// - /// The replacement . - /// - /// - /// A value between 0 and 128 with which to alter the target detection accuracy. - /// - /// - /// The . - /// - public ImageFactory ReplaceColor(Color target, Color replacement, int fuzziness = 0) - { - // Sanitize the input. - if (fuzziness < 0 || fuzziness > 128) - { - fuzziness = 0; - } - - if (this.ShouldProcess && target != Color.Empty && replacement != Color.Empty) - { - ReplaceColor replaceColor = new ReplaceColor - { - DynamicParameter = new Tuple(target, replacement, fuzziness) - }; - this.CurrentImageFormat.ApplyProcessor(replaceColor.ProcessImage, this); - } - - return this; - } - - /// - /// Resizes the current image to the given dimensions. - /// - /// - /// The containing the width and height to set the image to. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Resize(Size size) - { - if (this.ShouldProcess) - { - int width = size.Width; - int height = size.Height; - - ResizeLayer resizeLayer = new ResizeLayer(new Size(width, height)); - return this.Resize(resizeLayer); - } - - return this; - } - - /// - /// Resizes the current image to the given dimensions. - /// - /// - /// The containing the properties required to resize the image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Resize(ResizeLayer resizeLayer) - { - if (this.ShouldProcess) - { - Dictionary resizeSettings = new Dictionary - { - { "MaxWidth", resizeLayer.Size.Width.ToString("G") }, - { "MaxHeight", resizeLayer.Size.Height.ToString("G") } - }; - - Resize resize = new Resize { DynamicParameter = resizeLayer, Settings = resizeSettings }; - this.CurrentImageFormat.ApplyProcessor(resize.ProcessImage, this); - } - - return this; - } - - /// - /// Rotates the current image by the given angle. - /// - /// - /// The angle at which to rotate the image in degrees. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Rotate(float degrees) - { - if (this.ShouldProcess) - { - Rotate rotate = new Rotate { DynamicParameter = degrees }; - this.CurrentImageFormat.ApplyProcessor(rotate.ProcessImage, this); - } - - return this; - } - - /// - /// Rotates the image without expanding the canvas to fit the image. - /// - /// - /// The angle at which to rotate the image in degrees. - /// - /// - /// Whether to keep the original image dimensions. - /// - /// If set to true, the image is zoomed to fit the bounding area. - /// - /// - /// If set to false, the area is cropped to fit the rotated image. - /// - /// - /// - /// The current instance of the class. - /// - public ImageFactory RotateBounded(float degrees, bool keepSize = false) - { - if (this.ShouldProcess) - { - RotateBounded rotate = new RotateBounded { DynamicParameter = new Tuple(degrees, keepSize) }; - this.CurrentImageFormat.ApplyProcessor(rotate.ProcessImage, this); - } - - return this; - } - - /// - /// Adds rounded corners to the current image. - /// - /// - /// The radius at which the corner will be rounded. - /// - /// - /// The current instance of the class. - /// - public ImageFactory RoundedCorners(int radius) - { - if (this.ShouldProcess) - { - if (radius < 0) - { - radius = 0; - } - - RoundedCornerLayer roundedCornerLayer = new RoundedCornerLayer(radius); - - RoundedCorners roundedCorners = new RoundedCorners { DynamicParameter = roundedCornerLayer }; - this.CurrentImageFormat.ApplyProcessor(roundedCorners.ProcessImage, this); - } - - return this; - } - - /// - /// Adds rounded corners to the current image. - /// - /// - /// The containing the properties to round corners on the image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory RoundedCorners(RoundedCornerLayer roundedCornerLayer) - { - if (this.ShouldProcess) - { - if (roundedCornerLayer.Radius < 0) - { - roundedCornerLayer.Radius = 0; - } - - RoundedCorners roundedCorners = new RoundedCorners { DynamicParameter = roundedCornerLayer }; - this.CurrentImageFormat.ApplyProcessor(roundedCorners.ProcessImage, this); - } - - return this; - } - - /// - /// Changes the saturation of the current image. - /// - /// - /// The percentage by which to alter the images saturation. - /// Any integer between -100 and 100. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Saturation(int percentage) - { - if (this.ShouldProcess) - { - // Sanitize the input. - if (percentage > 100 || percentage < -100) - { - percentage = 0; - } - - Saturation saturate = new Saturation { DynamicParameter = percentage }; - this.CurrentImageFormat.ApplyProcessor(saturate.ProcessImage, this); - } - - return this; - } - - /// - /// Tints the current image with the given color. - /// - /// - /// The to tint the image with. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Tint(Color color) - { - if (this.ShouldProcess) - { - Tint tint = new Tint { DynamicParameter = color }; - this.CurrentImageFormat.ApplyProcessor(tint.ProcessImage, this); - } - - return this; - } - - /// - /// Adds a vignette image effect to the current image. - /// - /// - /// The to tint the image with. Defaults to black. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Vignette(Color? color = null) - { - if (this.ShouldProcess) - { - Vignette vignette = new Vignette - { - DynamicParameter = color.HasValue && !color.Equals(Color.Transparent) - ? color.Value - : Color.Black - }; - - this.CurrentImageFormat.ApplyProcessor(vignette.ProcessImage, this); - } - - return this; - } - - /// - /// Adds a text based watermark to the current image. - /// - /// - /// The containing the properties necessary to add - /// the text based watermark to the image. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Watermark(TextLayer textLayer) - { - if (this.ShouldProcess) - { - Watermark watermark = new Watermark { DynamicParameter = textLayer }; - this.CurrentImageFormat.ApplyProcessor(watermark.ProcessImage, this); - } - - return this; - } - #endregion - - /// - /// Saves the current image to the specified file path. If the extension does not - /// match the correct extension for the current format it will be replaced by the - /// correct default value. - /// - /// The path to save the image to. - /// - /// The current instance of the class. - /// - public ImageFactory Save(string filePath) - { - if (this.ShouldProcess) - { - // ReSharper disable once AssignNullToNotNullAttribute - DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); - if (!directoryInfo.Exists) - { - directoryInfo.Create(); - } - - // Normalize the gamma component of the image. - if (this.FixGamma) - { - this.Gamma(1 / 2.2F); - } - - this.Image = this.CurrentImageFormat.Save(filePath, this.Image); - } - - return this; - } - - /// - /// Saves the current image to the specified output stream. - /// - /// - /// The to save the image information to. - /// - /// - /// The current instance of the class. - /// - public ImageFactory Save(Stream stream) - { - if (this.ShouldProcess) - { - // Allow the same stream to be used as for input. - stream.SetLength(0); - - // Normalize the gamma component of the image. - if (this.FixGamma) - { - this.Gamma(1 / 2.2F); - } - - this.Image = this.CurrentImageFormat.Save(stream, this.Image); - stream.Position = 0; - } - - return this; - } - - #region IDisposable Members - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - public void Dispose() - { - this.Dispose(true); - - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - /// If true, the object gets disposed. - protected virtual void Dispose(bool disposing) - { - if (this.isDisposed) - { - return; - } - - if (disposing) - { - // Dispose of any managed resources here. - if (this.Image != null) - { - // Dispose of the memory stream from Load and the image. - if (this.InputStream != null) - { - this.InputStream.Dispose(); - this.InputStream = null; - } - - this.Image.Dispose(); - this.Image = null; - } - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - // Note disposing is done. - this.isDisposed = true; - } - #endregion - #endregion - } -} diff --git a/old/src/ImageProcessor/ImageProcessor.csproj b/old/src/ImageProcessor/ImageProcessor.csproj deleted file mode 100644 index 998a82514..000000000 --- a/old/src/ImageProcessor/ImageProcessor.csproj +++ /dev/null @@ -1,264 +0,0 @@ - - - - - Debug - AnyCPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E} - Library - Properties - ImageProcessor - ImageProcessor - v4.5 - - NET45 - 512 - ..\ - true - - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE;NET45 - prompt - 4 - bin\Debug\ImageProcessor.XML - false - true - - - - - v4.0 - Client - AnyCPU - true - full - false - bin\Debug\$(Framework)\ - DEBUG;TRACE;NET40 - prompt - 4 - bin\$(Configuration)\$(Framework)\ImageProcessor.XML - false - true - - - - pdbonly - true - bin\Release\ - TRACE;NET45 - prompt - 4 - bin\Release\ImageProcessor.XML - false - true - - - - - v4.0 - Client - pdbonly - true - bin\Release\$(Framework)\ - TRACE;NET40 - prompt - 4 - bin\Release\$(Framework)\ImageProcessor.XML - false - true - - - - true - bin\All\ - DEBUG;TRACE;NET45 - bin\Debug\ImageProcessor.XML - full - AnyCPU - prompt - false - true - 4 - false - false - true - - - - - v4.0 - Client - true - bin\All\$(Framework)\ - DEBUG;TRACE;NET40 - bin\Debug\$(Framework)\ImageProcessor.XML - full - AnyCPU - prompt - false - true - 4 - false - false - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/ImageProcessor/ImageProcessor.csproj.DotSettings b/old/src/ImageProcessor/ImageProcessor.csproj.DotSettings deleted file mode 100644 index bf68fcc20..000000000 --- a/old/src/ImageProcessor/ImageProcessor.csproj.DotSettings +++ /dev/null @@ -1,2 +0,0 @@ - - True \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/AnchorPosition.cs b/old/src/ImageProcessor/Imaging/AnchorPosition.cs deleted file mode 100644 index 49362485e..000000000 --- a/old/src/ImageProcessor/Imaging/AnchorPosition.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Enumerated anchor positions to apply to resized images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - /// - /// Enumerated anchor positions to apply to resized images. - /// - public enum AnchorPosition - { - /// - /// Anchors the position of the image to the center of it's bounding container. - /// - Center, - - /// - /// Anchors the position of the image to the top of it's bounding container. - /// - Top, - - /// - /// Anchors the position of the image to the bottom of it's bounding container. - /// - Bottom, - - /// - /// Anchors the position of the image to the left of it's bounding container. - /// - Left, - - /// - /// Anchors the position of the image to the right of it's bounding container. - /// - Right - } -} diff --git a/old/src/ImageProcessor/Imaging/Colors/CmykColor.cs b/old/src/ImageProcessor/Imaging/Colors/CmykColor.cs deleted file mode 100644 index aabc468e4..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/CmykColor.cs +++ /dev/null @@ -1,375 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents an CMYK (cyan, magenta, yellow, keyline) color. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - using System; - using System.Drawing; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Represents an CMYK (cyan, magenta, yellow, keyline) color. - /// - public struct CmykColor - { - /// - /// Represents a that is null. - /// - public static readonly CmykColor Empty = new CmykColor(); - - /// - /// The cyan color component. - /// - private readonly float c; - - /// - /// The magenta color component. - /// - private readonly float m; - - /// - /// The yellow color component. - /// - private readonly float y; - - /// - /// The keyline black color component. - /// - private readonly float k; - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The cyan component. - /// - /// - /// The magenta component. - /// - /// - /// The yellow component. - /// - /// - /// The keyline black component. - /// - private CmykColor(float cyan, float magenta, float yellow, float keyline) - { - this.c = Clamp(cyan); - this.m = Clamp(magenta); - this.y = Clamp(yellow); - this.k = Clamp(keyline); - } - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The to initialize from. - /// - private CmykColor(Color color) - { - CmykColor cmykColor = color; - this.c = cmykColor.c; - this.m = cmykColor.m; - this.y = cmykColor.y; - this.k = cmykColor.k; - } - - /// - /// Gets the cyan component. - /// A value ranging between 0 and 100. - /// - public float C - { - get - { - return this.c; - } - } - - /// - /// Gets the magenta component. - /// A value ranging between 0 and 100. - /// - public float M - { - get - { - return this.m; - } - } - - /// - /// Gets the yellow component. - /// A value ranging between 0 and 100. - /// - public float Y - { - get - { - return this.y; - } - } - - /// - /// Gets the keyline black component. - /// A value ranging between 0 and 100. - /// - public float K - { - get - { - return this.k; - } - } - - /// - /// Creates a structure from the four 32-bit CMYK - /// components (cyan, magenta, yellow, and keyline) values. - /// - /// - /// The cyan component. - /// - /// - /// The magenta component. - /// - /// - /// The yellow component. - /// - /// - /// The keyline black component. - /// - /// - /// The . - /// - public static CmykColor FromCmykColor(float cyan, float magenta, float yellow, float keyline) - { - return new CmykColor(cyan, magenta, yellow, keyline); - } - - /// - /// Creates a structure from the specified structure - /// - /// - /// The from which to create the new . - /// - /// - /// The . - /// - public static CmykColor FromColor(Color color) - { - return new CmykColor(color); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator CmykColor(Color color) - { - float c = (255f - color.R) / 255; - float m = (255f - color.G) / 255; - float y = (255f - color.B) / 255; - - float k = Math.Min(c, Math.Min(m, y)); - - if (Math.Abs(k - 1.0) <= .0001f) - { - return new CmykColor(0, 0, 0, 100); - } - - c = ((c - k) / (1 - k)) * 100; - m = ((m - k) / (1 - k)) * 100; - y = ((y - k) / (1 - k)) * 100; - - return new CmykColor(c, m, y, k * 100); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator CmykColor(RgbaColor rgbaColor) - { - return FromColor(rgbaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator CmykColor(YCbCrColor ycbcrColor) - { - Color color = ycbcrColor; - return FromColor(color); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator Color(CmykColor cmykColor) - { - int red = Convert.ToInt32((1 - (cmykColor.c / 100)) * (1 - (cmykColor.k / 100)) * 255.0); - int green = Convert.ToInt32((1 - (cmykColor.m / 100)) * (1 - (cmykColor.k / 100)) * 255.0); - int blue = Convert.ToInt32((1 - (cmykColor.y / 100)) * (1 - (cmykColor.k / 100)) * 255.0); - return Color.FromArgb(red.ToByte(), green.ToByte(), blue.ToByte()); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator RgbaColor(CmykColor cmykColor) - { - int red = Convert.ToInt32((1 - (cmykColor.c / 100)) * (1 - (cmykColor.k / 100)) * 255.0); - int green = Convert.ToInt32((1 - (cmykColor.m / 100)) * (1 - (cmykColor.k / 100)) * 255.0); - int blue = Convert.ToInt32((1 - (cmykColor.y / 100)) * (1 - (cmykColor.k / 100)) * 255.0); - return RgbaColor.FromRgba(red.ToByte(), green.ToByte(), blue.ToByte()); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator YCbCrColor(CmykColor cmykColor) - { - return YCbCrColor.FromColor(cmykColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator HslaColor(CmykColor cmykColor) - { - return HslaColor.FromColor(cmykColor); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - if (this.IsEmpty()) - { - return "CmykColor [Empty]"; - } - - return string.Format("CmykColor [ C={0:#0.##}, M={1:#0.##}, Y={2:#0.##}, K={3:#0.##}]", this.C, this.M, this.Y, this.K); - } - - /// - /// Indicates whether this instance and a specified object are equal. - /// - /// - /// true if and this instance are the same type and represent the same value; otherwise, false. - /// - /// Another object to compare to. - public override bool Equals(object obj) - { - if (obj is CmykColor) - { - Color thisColor = this; - Color otherColor = (CmykColor)obj; - - return thisColor.Equals(otherColor); - } - - return false; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - Color thisColor = this; - return thisColor.GetHashCode(); - } - - /// - /// Checks the range of the given value to ensure that it remains within the acceptable boundaries. - /// - /// - /// The value to check. - /// - /// - /// The sanitized . - /// - private static float Clamp(float value) - { - return ImageMaths.Clamp(value, 0, 100); - } - - /// - /// Returns a value indicating whether the current instance is empty. - /// - /// - /// The true if this instance is empty; otherwise, false. - /// - private bool IsEmpty() - { - const float Epsilon = .0001f; - return Math.Abs(this.c - 0) <= Epsilon && Math.Abs(this.m - 0) <= Epsilon && - Math.Abs(this.y - 0) <= Epsilon && Math.Abs(this.k - 0) <= Epsilon; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Colors/Color32.cs b/old/src/ImageProcessor/Imaging/Colors/Color32.cs deleted file mode 100644 index 127fe7811..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/Color32.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Structure that defines a 32 bit color -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - using System.Drawing; - using System.Runtime.InteropServices; - - /// - /// Structure that defines a 32 bits per pixel color, used for pixel manipulation not for color conversion. - /// - /// - /// This structure is used to read data from a 32 bits per pixel image - /// in memory, and is ordered in this manner as this is the way that - /// the data is laid out in memory - /// - [StructLayout(LayoutKind.Explicit)] - public struct Color32 - { - /// - /// Holds the blue component of the colour - /// - [FieldOffset(0)] - public byte B; - - /// - /// Holds the green component of the colour - /// - [FieldOffset(1)] - public byte G; - - /// - /// Holds the red component of the colour - /// - [FieldOffset(2)] - public byte R; - - /// - /// Holds the alpha component of the colour - /// - [FieldOffset(3)] - public byte A; - - /// - /// Permits the color32 to be treated as a 32 bit integer. - /// - [FieldOffset(0)] - public int Argb; - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The alpha component. - /// - /// - /// The red component. - /// - /// - /// The green component. - /// - /// - /// The blue component. - /// - public Color32(byte alpha, byte red, byte green, byte blue) - : this() - { - this.A = alpha; - this.R = red; - this.G = green; - this.B = blue; - } - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The combined color components. - /// - public Color32(int argb) - : this() - { - this.Argb = argb; - } - - /// - /// Gets the color for this Color32 object - /// - public Color Color - { - get { return Color.FromArgb(this.A, this.R, this.G, this.B); } - } - - /// - /// Indicates whether this instance and a specified object are equal. - /// - /// - /// true if and this instance are the same type and represent the same value; otherwise, false. - /// - /// Another object to compare to. - public override bool Equals(object obj) - { - if (obj is Color32) - { - Color32 color32 = (Color32)obj; - - return this.Argb == color32.Argb; - } - - return false; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - return this.GetHashCode(this); - } - - /// - /// Returns the hash code for the given instance. - /// - /// - /// The instance of to return the hash code for. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - private int GetHashCode(Color32 obj) - { - unchecked - { - int hashCode = obj.B.GetHashCode(); - hashCode = (hashCode * 397) ^ obj.G.GetHashCode(); - hashCode = (hashCode * 397) ^ obj.R.GetHashCode(); - hashCode = (hashCode * 397) ^ obj.A.GetHashCode(); - return hashCode; - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Colors/ColorExtensions.cs b/old/src/ImageProcessor/Imaging/Colors/ColorExtensions.cs deleted file mode 100644 index 3d06f8c07..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/ColorExtensions.cs +++ /dev/null @@ -1,95 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides extensions for manipulating colors. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - using System; - using System.Drawing; - - using ImageProcessor.Common.Extensions; - - /// - /// Provides extensions for manipulating colors. - /// - internal static class ColorExtensions - { - /// - /// Adds colors together using the RGBA color format. - /// - /// - /// The color to add to. - /// - /// - /// The colors to add to the initial one. - /// - /// - /// The combined . - /// - public static Color Add(this Color color, params Color[] colors) - { - int red = color.A > 0 ? color.R : 0; - int green = color.A > 0 ? color.G : 0; - int blue = color.A > 0 ? color.B : 0; - int alpha = color.A; - - int counter = 0; - foreach (Color addColor in colors) - { - if (addColor.A > 0) - { - counter += 1; - red += addColor.R; - green += addColor.G; - blue += addColor.B; - alpha += addColor.A; - } - } - - counter = Math.Max(1, counter); - - return Color.FromArgb((alpha / counter).ToByte(), (red / counter).ToByte(), (green / counter).ToByte(), (blue / counter).ToByte()); - } - - /// - /// Adds colors together using the CMYK color format. - /// - /// - /// The color to add to. - /// - /// - /// The colors to add to the initial one. - /// - /// - /// The combined . - /// - public static CmykColor AddAsCmykColor(this Color color, params Color[] colors) - { - CmykColor cmyk = color; - float c = color.A > 0 ? cmyk.C : 0; - float m = color.A > 0 ? cmyk.M : 0; - float y = color.A > 0 ? cmyk.Y : 0; - float k = color.A > 0 ? cmyk.K : 0; - - foreach (Color addColor in colors) - { - if (addColor.A > 0) - { - CmykColor cmykAdd = addColor; - c += cmykAdd.C; - m += cmykAdd.M; - y += cmykAdd.Y; - k += cmykAdd.K; - } - } - - return CmykColor.FromCmykColor(c, m, y, k); - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Colors/HSLAColor.cs b/old/src/ImageProcessor/Imaging/Colors/HSLAColor.cs deleted file mode 100644 index 9958721db..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/HSLAColor.cs +++ /dev/null @@ -1,514 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - using System; - using System.Drawing; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Represents an HSLA (hue, saturation, luminosity, alpha) color. - /// Adapted from - /// - public struct HslaColor - { - /// - /// Represents a that is null. - /// - public static readonly HslaColor Empty = new HslaColor(); - - // Private data members below are on scale 0-1 - // They are scaled for use externally based on scale - - /// - /// The hue component. - /// - private readonly float h; - - /// - /// The luminosity component. - /// - private readonly float l; - - /// - /// The saturation component. - /// - private readonly float s; - - /// - /// The alpha component. - /// - private readonly float a; - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The hue component. - /// - /// - /// The saturation component. - /// - /// - /// The luminosity component. - /// - /// - /// The alpha component. - /// - private HslaColor(float hue, float saturation, float luminosity, float alpha) - { - this.h = Clamp(hue); - this.s = Clamp(saturation); - this.l = Clamp(luminosity); - this.a = Clamp(alpha); - } - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The to initialize from. - /// - private HslaColor(Color color) - { - HslaColor hslColor = color; - this.h = hslColor.h; - this.s = hslColor.s; - this.l = hslColor.l; - this.a = hslColor.a; - } - - /// - /// Gets the hue component. - /// A value ranging between 0 and 1. - /// - public float H - { - get - { - return this.h; - } - } - - /// - /// Gets the luminosity component. - /// A value ranging between 0 and 1. - /// - public float L - { - get - { - return this.l; - } - } - - /// - /// Gets the saturation component. - /// A value ranging between 0 and 1. - /// - public float S - { - get - { - return this.s; - } - } - - /// - /// Gets the alpha component. - /// A value ranging between 0 and 1. - /// - public float A - { - get - { - return this.a; - } - } - - /// - /// Creates a structure from the three 32-bit HSLA - /// components (hue, saturation, and luminosity) values. - /// - /// - /// The hue component. - /// - /// - /// The saturation component. - /// - /// - /// The luminosity component. - /// - /// - /// The . - /// - public static HslaColor FromHslaColor(float hue, float saturation, float luminosity) - { - return new HslaColor(hue, saturation, luminosity, 1.0f); - } - - /// - /// Creates a structure from the four 32-bit HSLA - /// components (hue, saturation, luminosity, and alpha) values. - /// - /// - /// The hue component. - /// - /// - /// The saturation component. - /// - /// - /// The luminosity component. - /// - /// - /// The alpha component. - /// - /// - /// The . - /// - public static HslaColor FromHslaColor(float hue, float saturation, float luminosity, float alpha) - { - return new HslaColor(hue, saturation, luminosity, alpha); - } - - /// - /// Creates a structure from the specified structure - /// - /// - /// The from which to create the new . - /// - /// - /// The . - /// - public static HslaColor FromColor(Color color) - { - return new HslaColor(color); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator HslaColor(Color color) - { - HslaColor hslColor = new HslaColor( - color.GetHue() / 360.0f, - color.GetSaturation(), - color.GetBrightness(), - color.A / 255f); - - return hslColor; - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator HslaColor(RgbaColor rgbaColor) - { - return FromColor(rgbaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator HslaColor(YCbCrColor ycbcrColor) - { - Color color = ycbcrColor; - HslaColor hslColor = new HslaColor( - color.GetHue() / 360.0f, - color.GetSaturation(), - color.GetBrightness(), - color.A / 255f); - - return hslColor; - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator Color(HslaColor hslaColor) - { - float r = 0, g = 0, b = 0; - if (Math.Abs(hslaColor.l - 0) > .0001) - { - if (Math.Abs(hslaColor.s - 0) <= .0001) - { - r = g = b = hslaColor.l; - } - else - { - float temp2 = GetTemp2(hslaColor); - float temp1 = (2.0f * hslaColor.l) - temp2; - - r = GetColorComponent(temp1, temp2, hslaColor.h + (1.0f / 3.0f)); - g = GetColorComponent(temp1, temp2, hslaColor.h); - b = GetColorComponent(temp1, temp2, hslaColor.h - (1.0f / 3.0f)); - } - } - - return Color.FromArgb( - Convert.ToInt32(255 * hslaColor.a), - Convert.ToInt32(255 * r), - Convert.ToInt32(255 * g), - Convert.ToInt32(255 * b)); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator RgbaColor(HslaColor hslaColor) - { - float r = 0, g = 0, b = 0; - if (Math.Abs(hslaColor.l - 0) > .0001) - { - if (Math.Abs(hslaColor.s - 0) <= .0001) - { - r = g = b = hslaColor.l; - } - else - { - float temp2 = GetTemp2(hslaColor); - float temp1 = (2.0f * hslaColor.l) - temp2; - - r = GetColorComponent(temp1, temp2, hslaColor.h + (1.0f / 3.0f)); - g = GetColorComponent(temp1, temp2, hslaColor.h); - b = GetColorComponent(temp1, temp2, hslaColor.h - (1.0f / 3.0f)); - } - } - - return RgbaColor.FromRgba( - Convert.ToByte(255 * r), - Convert.ToByte(255 * g), - Convert.ToByte(255 * b), - Convert.ToByte(255 * hslaColor.a)); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator YCbCrColor(HslaColor hslaColor) - { - return YCbCrColor.FromColor(hslaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator CmykColor(HslaColor hslaColor) - { - return CmykColor.FromColor(hslaColor); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - if (this.IsEmpty()) - { - return "HslaColor [Empty]"; - } - - return string.Format("HslaColor [ H={0:#0.##}, S={1:#0.##}, L={2:#0.##}, A={3:#0.##}]", this.H, this.S, this.L, this.A); - } - - /// - /// Indicates whether this instance and a specified object are equal. - /// - /// - /// true if and this instance are the same type and represent the same value; otherwise, false. - /// - /// Another object to compare to. - public override bool Equals(object obj) - { - if (obj is HslaColor) - { - Color thisColor = this; - Color otherColor = (HslaColor)obj; - - return thisColor.Equals(otherColor); - } - - return false; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - Color thisColor = this; - return thisColor.GetHashCode(); - } - - /// - /// Gets the color component from the given hue values. - /// - /// - /// The temp 1. - /// - /// - /// The temp 2. - /// - /// - /// The temp 3. - /// - /// - /// The . - /// - private static float GetColorComponent(float temp1, float temp2, float temp3) - { - temp3 = MoveIntoRange(temp3); - if (temp3 < 1.0 / 6.0) - { - return temp1 + ((temp2 - temp1) * 6.0f * temp3); - } - - if (temp3 < 0.5) - { - return temp2; - } - - if (temp3 < 2.0 / 3.0) - { - return temp1 + ((temp2 - temp1) * ((2.0f / 3.0f) - temp3) * 6.0f); - } - - return temp1; - } - - /// - /// The get temp 2. - /// - /// - /// The color. - /// - /// - /// The . - /// - private static float GetTemp2(HslaColor hslColor) - { - float temp2; - if (hslColor.l <= 0.5) - { - temp2 = hslColor.l * (1.0f + hslColor.s); - } - else - { - temp2 = hslColor.l + hslColor.s - (hslColor.l * hslColor.s); - } - - return temp2; - } - - /// - /// The move into range. - /// - /// - /// The temp 3. - /// - /// - /// The . - /// - private static float MoveIntoRange(float temp3) - { - if (temp3 < 0.0) - { - temp3 += 1.0f; - } - else if (temp3 > 1.0) - { - temp3 -= 1.0f; - } - - return temp3; - } - - /// - /// Checks the range of the given value to ensure that it remains within the acceptable boundaries. - /// - /// - /// The value to check. - /// - /// - /// The sanitized . - /// - private static float Clamp(float value) - { - return ImageMaths.Clamp(value, 0, 1); - } - - /// - /// Returns a value indicating whether the current instance is empty. - /// - /// - /// The true if this instance is empty; otherwise, false. - /// - private bool IsEmpty() - { - const float Epsilon = .0001f; - return Math.Abs(this.h - 0) <= Epsilon && Math.Abs(this.s - 0) <= Epsilon && - Math.Abs(this.l - 0) <= Epsilon && Math.Abs(this.a - 0) <= Epsilon; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Colors/RGBAColor.cs b/old/src/ImageProcessor/Imaging/Colors/RGBAColor.cs deleted file mode 100644 index e8b3bbb66..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/RGBAColor.cs +++ /dev/null @@ -1,335 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - using System.Drawing; - - /// - /// Represents an RGBA (red, green, blue, alpha) color. - /// - public struct RgbaColor - { - /// - /// Represents a that is null. - /// - public static readonly RgbaColor Empty = new RgbaColor(); - - /// - /// The red component. - /// - private readonly byte r; - - /// - /// The green component. - /// - private readonly byte g; - - /// - /// The blue component. - /// - private readonly byte b; - - /// - /// The alpha component. - /// - private readonly byte a; - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The red component. - /// - /// - /// The green component. - /// - /// - /// The blue component. - /// - /// - /// The alpha component. - /// - private RgbaColor(byte red, byte green, byte blue, byte alpha) - { - this.r = red; - this.g = green; - this.b = blue; - this.a = alpha; - } - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The color. - /// - private RgbaColor(Color color) - { - this.r = color.R; - this.g = color.G; - this.b = color.B; - this.a = color.A; - } - - /// - /// Gets the red component. - /// - public byte R - { - get - { - return this.r; - } - } - - /// - /// Gets the green component. - /// - public byte G - { - get - { - return this.g; - } - } - - /// - /// Gets the blue component. - /// - public byte B - { - get - { - return this.b; - } - } - - /// - /// Gets the alpha component. - /// - public byte A - { - get - { - return this.a; - } - } - - /// - /// Creates a structure from the three 8-bit RGBA - /// components (red, green, and blue) values. - /// - /// - /// The red component. - /// - /// - /// The green component. - /// - /// - /// The blue component. - /// - /// - /// The . - /// - public static RgbaColor FromRgba(byte red, byte green, byte blue) - { - return new RgbaColor(red, green, blue, 255); - } - - /// - /// Creates a structure from the four 8-bit RGBA - /// components (red, green, blue, and alpha) values. - /// - /// - /// The red component. - /// - /// - /// The green component. - /// - /// - /// The blue component. - /// - /// - /// The alpha component. - /// - /// - /// The . - /// - public static RgbaColor FromRgba(byte red, byte green, byte blue, byte alpha) - { - return new RgbaColor(red, green, blue, alpha); - } - - /// - /// Creates a structure from the specified structure - /// - /// - /// The from which to create the new . - /// - /// - /// The . - /// - public static RgbaColor FromColor(Color color) - { - return new RgbaColor(color); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator RgbaColor(Color color) - { - return FromColor(color); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator RgbaColor(HslaColor hslaColor) - { - return FromColor(hslaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator RgbaColor(YCbCrColor ycbcrColor) - { - return FromColor(ycbcrColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator Color(RgbaColor rgbaColor) - { - return Color.FromArgb(rgbaColor.A, rgbaColor.R, rgbaColor.G, rgbaColor.B); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator HslaColor(RgbaColor rgbaColor) - { - return HslaColor.FromColor(rgbaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator YCbCrColor(RgbaColor rgbaColor) - { - return YCbCrColor.FromColor(rgbaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator CmykColor(RgbaColor rgbaColor) - { - return CmykColor.FromColor(rgbaColor); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - if (this.R == 0 && this.G == 0 && this.B == 0 && this.A == 0) - { - return "RGBA [Empty]"; - } - - return string.Format("RGBA [R={0}, G={1}, B={2}, A={3}]", this.R, this.G, this.B, this.A); - } - - /// - /// Indicates whether this instance and a specified object are equal. - /// - /// - /// true if and this instance are the same type and represent the same value; otherwise, false. - /// - /// Another object to compare to. - public override bool Equals(object obj) - { - if (obj is RgbaColor) - { - Color thisColor = this; - Color otherColor = (RgbaColor)obj; - - return thisColor.Equals(otherColor); - } - - return false; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - Color thisColor = this; - return thisColor.GetHashCode(); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Colors/RgbaComponent.cs b/old/src/ImageProcessor/Imaging/Colors/RgbaComponent.cs deleted file mode 100644 index 03d077fa8..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/RgbaComponent.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Enumerates the RGBA (red, green, blue, alpha) color components. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - /// - /// Enumerates the RGBA (red, green, blue, alpha) color components. - /// - public enum RgbaComponent - { - /// - /// The blue component. - /// - B = 0, - - /// - /// The green component. - /// - G = 1, - - /// - /// The red component. - /// - R = 2, - - /// - /// The alpha component. - /// - A = 3 - } -} diff --git a/old/src/ImageProcessor/Imaging/Colors/YCbCrColor.cs b/old/src/ImageProcessor/Imaging/Colors/YCbCrColor.cs deleted file mode 100644 index 0035ea755..000000000 --- a/old/src/ImageProcessor/Imaging/Colors/YCbCrColor.cs +++ /dev/null @@ -1,309 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents an YCbCr (luminance, chroma, chroma) color conforming to the ITU-R BT.601 standard used in digital imaging systems. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Colors -{ - using System; - using System.Drawing; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Represents an YCbCr (luminance, chroma, chroma) color conforming to the ITU-R BT.601 standard used in digital imaging systems. - /// - /// - public struct YCbCrColor - { - /// - /// Represents a that is null. - /// - public static readonly YCbCrColor Empty = new YCbCrColor(); - - /// - /// The y luminance component. - /// - private readonly float y; - - /// - /// The u chroma component. - /// - private readonly float cb; - - /// - /// The v chroma component. - /// - private readonly float cr; - - /// - /// Initializes a new instance of the struct. - /// - /// The y luminance component. - /// The u chroma component. - /// The v chroma component. - private YCbCrColor(float y, float cb, float cr) - { - this.y = ImageMaths.Clamp(y, 0, 255); - this.cb = ImageMaths.Clamp(cb, 0, 255); - this.cr = ImageMaths.Clamp(cr, 0, 255); - } - - /// - /// Gets the Y luminance component. - /// A value ranging between 0 and 255. - /// - public float Y - { - get - { - return this.y; - } - } - - /// - /// Gets the U chroma component. - /// A value ranging between 0 and 255. - /// - public float Cb - { - get - { - return this.cb; - } - } - - /// - /// Gets the V chroma component. - /// A value ranging between 0 and 255. - /// - public float Cr - { - get - { - return this.cr; - } - } - - /// - /// Creates a structure from the three 32-bit YCbCr - /// components (luminance, chroma, and chroma) values. - /// - /// The y luminance component. - /// The u chroma component. - /// The v chroma component. - /// - /// The . - /// - public static YCbCrColor FromYCbCr(float y, float cb, float cr) - { - return new YCbCrColor(y, cb, cr); - } - - /// - /// Creates a structure from the specified structure - /// - /// - /// The from which to create the new . - /// - /// - /// The . - /// - public static YCbCrColor FromColor(Color color) - { - byte r = color.R; - byte g = color.G; - byte b = color.B; - - float y = (float)((0.299 * r) + (0.587 * g) + (0.114 * b)); - float cb = 128 + (float)((-0.168736 * r) - (0.331264 * g) + (0.5 * b)); - float cr = 128 + (float)((0.5 * r) - (0.418688 * g) - (0.081312 * b)); - - return new YCbCrColor(y, cb, cr); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator YCbCrColor(Color color) - { - return FromColor(color); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator YCbCrColor(RgbaColor rgbaColor) - { - return FromColor(rgbaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator YCbCrColor(HslaColor hslaColor) - { - return FromColor(hslaColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator Color(YCbCrColor ycbcrColor) - { - float y = ycbcrColor.Y; - float cb = ycbcrColor.Cb - 128; - float cr = ycbcrColor.Cr - 128; - - //byte r = Convert.ToByte(Math.Max(0.0f, Math.Min(255f, y + (1.402 * cr)))); - //byte g = Convert.ToByte(Math.Max(0.0f, Math.Min(255f, y - (0.34414 * cb) - (0.71414 * cr)))); - //byte b = Convert.ToByte(Math.Max(0.0f, Math.Min(255f, y + (1.772 * cb)))); - - byte r = Convert.ToByte(ImageMaths.Clamp(y + (1.402 * cr), 0, 255)); - byte g = Convert.ToByte(ImageMaths.Clamp(y - (0.34414 * cb) - (0.71414 * cr), 0, 255)); - byte b = Convert.ToByte(ImageMaths.Clamp(y + (1.772 * cb), 0, 255)); - - return Color.FromArgb(255, r, g, b); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator RgbaColor(YCbCrColor ycbcrColor) - { - return RgbaColor.FromColor(ycbcrColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator HslaColor(YCbCrColor ycbcrColor) - { - return HslaColor.FromColor(ycbcrColor); - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator CmykColor(YCbCrColor ycbcrColor) - { - return CmykColor.FromColor(ycbcrColor); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - if (this.IsEmpty()) - { - return "YCbCrColor [Empty]"; - } - - return string.Format("YCbCrColor [ Y={0:#0.##}, Cb={1:#0.##}, Cr={2:#0.##}]", this.Y, this.Cb, this.Cr); - } - - /// - /// Indicates whether this instance and a specified object are equal. - /// - /// - /// true if and this instance are the same type and represent the same value; otherwise, false. - /// - /// Another object to compare to. - public override bool Equals(object obj) - { - if (obj is YCbCrColor) - { - Color thisColor = this; - Color otherColor = (YCbCrColor)obj; - - return thisColor.Equals(otherColor); - } - - return false; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - Color thisColor = this; - return thisColor.GetHashCode(); - } - - /// - /// Returns a value indicating whether the current instance is empty. - /// - /// - /// The true if this instance is empty; otherwise, false. - /// - private bool IsEmpty() - { - const float Epsilon = .0001f; - return Math.Abs(this.y - 0) <= Epsilon && Math.Abs(this.cb - 0) <= Epsilon && - Math.Abs(this.cr - 0) <= Epsilon; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Convolution.cs b/old/src/ImageProcessor/Imaging/Convolution.cs deleted file mode 100644 index 554375b6d..000000000 --- a/old/src/ImageProcessor/Imaging/Convolution.cs +++ /dev/null @@ -1,426 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides methods for applying blurring and sharpening effects to an image.. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System; - using System.Drawing; - using System.Threading.Tasks; - - using ImageProcessor.Common.Extensions; - - /// - /// Provides methods for applying blurring and sharpening effects to an image.. - /// - public class Convolution - { - /// - /// The standard deviation 'sigma' value for calculating Gaussian curves. - /// - private readonly double standardDeviation = 1.4; - - /// - /// Whether to use dynamic divider for edges. - /// - private bool useDynamicDividerForEdges = true; - - /// - /// Initializes a new instance of the class. - /// - public Convolution() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The standard deviation. - /// - public Convolution(double standardDeviation) - { - this.standardDeviation = standardDeviation; - } - - /// - /// Gets or sets the threshold to add to the weighted sum. - /// - /// - /// Specifies the threshold value, which is added to each weighted - /// sum of pixels. - /// - /// - /// - public int Threshold { get; set; } - - /// - /// Gets or sets the value used to divide convolution; the weighted sum - /// of pixels is divided by this value. - /// - /// If not set this value will be automatically calculated. - /// - /// - public double Divider { get; set; } - - /// - /// Gets or sets a value indicating whether to use the dynamic divider for edges. - /// - /// - /// If it is set to , then the same divider, specified by - /// property or calculated automatically, will be applied both for non-edge regions - /// and for edge regions. If the value is set to , then the dynamically - /// calculated divider will be used for edge regions. This is calculated from the sum of the kernel - /// elements used at that region, which are taken into account for particular processed pixel - /// (elements, which are not outside image). - /// - /// Default value is set to . - /// - /// - public bool UseDynamicDividerForEdges - { - get - { - return this.useDynamicDividerForEdges; - } - - set - { - this.useDynamicDividerForEdges = value; - } - } - - /// - /// Create a 1 dimensional Gaussian kernel using the Gaussian G(x) function - /// - /// Kernel Size - /// A Gaussian Kernel with the given size and deviation. - public double[,] CreateGaussianKernel(int kernelSize) - { - double[,] kernel = new double[kernelSize, 1]; - double sum = 0.0d; - - int midpoint = kernelSize / 2; - for (int i = 0; i < kernelSize; i++) - { - int x = i - midpoint; - double gx = this.Gaussian(x); - sum += gx; - kernel[i, 0] = gx; - } - - // Normalise kernel so that the sum of all weights equals 1 - for (int i = 0; i < kernelSize; i++) - { - kernel[i, 0] = kernel[i, 0] / sum; - } - - return kernel; - } - - /// - /// Create a 2 dimensional Gaussian kernel using the Gaussian G(x y) function - /// - /// Kernel Size - /// A Gaussian Kernel with the given size and deviation. - public double[,] CreateGaussianKernel2D(int kernelSize) - { - double[,] kernel = new double[kernelSize, kernelSize]; - - int midpoint = kernelSize / 2; - - for (int i = 0; i < kernelSize; i++) - { - int x = i - midpoint; - - for (int j = 0; j < kernelSize; j++) - { - int y = j - midpoint; - double gxy = this.Gaussian2D(x, y); - kernel[i, j] = gxy; - } - } - - return kernel; - } - - /// - /// Create a 2 dimensional Gaussian kernel using the Gaussian G(x y) function for - /// blurring images. - /// - /// Kernel Size - /// A Gaussian Kernel with the given size. - public double[,] CreateGuassianBlurFilter(int kernelSize) - { - // Create kernel - double[,] kernel = this.CreateGaussianKernel2D(kernelSize); - double min = kernel[0, 0]; - - // Convert to integer blurring kernel. First of all the integer kernel is calculated from Kernel2D - // by dividing all elements by the element with the smallest value. - double[,] intKernel = new double[kernelSize, kernelSize]; - int divider = 0; - - for (int i = 0; i < kernelSize; i++) - { - for (int j = 0; j < kernelSize; j++) - { - double v = kernel[i, j] / min; - - if (v > ushort.MaxValue) - { - v = ushort.MaxValue; - } - - intKernel[i, j] = (int)v; - - // Collect the divider - divider += (int)intKernel[i, j]; - } - } - - // Update filter - this.Divider = divider; - return intKernel; - } - - /// - /// Create a 2 dimensional Gaussian kernel using the Gaussian G(x y) function for - /// sharpening images. - /// - /// Kernel Size - /// A Gaussian Kernel with the given size. - public double[,] CreateGuassianSharpenFilter(int kernelSize) - { - // Create kernel - double[,] kernel = this.CreateGaussianKernel2D(kernelSize); - double min = kernel[0, 0]; - - // integer kernel - double[,] intKernel = new double[kernelSize, kernelSize]; - int sum = 0; - int divider = 0; - - for (int i = 0; i < kernelSize; i++) - { - for (int j = 0; j < kernelSize; j++) - { - double v = kernel[i, j] / min; - - if (v > ushort.MaxValue) - { - v = ushort.MaxValue; - } - - intKernel[i, j] = (int)v; - - // Collect the sum. - sum += (int)intKernel[i, j]; - } - } - - // Recalculate the kernel. - int center = kernelSize >> 1; - - for (int i = 0; i < kernelSize; i++) - { - for (int j = 0; j < kernelSize; j++) - { - if ((i == center) && (j == center)) - { - // Calculate central value - intKernel[i, j] = (2 * sum) - intKernel[i, j]; - } - else - { - // invert value - intKernel[i, j] = -intKernel[i, j]; - } - - // Collect the divider - divider += (int)intKernel[i, j]; - } - } - - // Update filter - this.Divider = divider; - return intKernel; - } - - /// - /// Processes the given kernel to produce an array of pixels representing a bitmap. - /// - /// The image to process. - /// The Gaussian kernel to use when performing the method - /// A processed bitmap. - public Bitmap ProcessKernel(Bitmap source, double[,] kernel) - { - int width = source.Width; - int height = source.Height; - Bitmap destination = new Bitmap(width, height); - destination.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - using (FastBitmap sourceBitmap = new FastBitmap(source)) - { - using (FastBitmap destinationBitmap = new FastBitmap(destination)) - { - int kernelLength = kernel.GetLength(0); - int radius = kernelLength >> 1; - int kernelSize = kernelLength * kernelLength; - int threshold = this.Threshold; - - // For each line - Parallel.For( - 0, - height, - y => - { - // For each pixel - for (int x = 0; x < width; x++) - { - // The number of kernel elements taken into account - int processedKernelSize; - - // Colour sums - double blue; - double alpha; - double divider; - double green; - double red = green = blue = alpha = divider = processedKernelSize = 0; - - // For each kernel row - for (int i = 0; i < kernelLength; i++) - { - int ir = i - radius; - int offsetY = y + ir; - - // Skip the current row - if (offsetY < 0) - { - continue; - } - - // Outwith the current bounds so break. - if (offsetY >= height) - { - break; - } - - // For each kernel column - for (int j = 0; j < kernelLength; j++) - { - int jr = j - radius; - int offsetX = x + jr; - - // Skip the column - if (offsetX < 0) - { - continue; - } - - if (offsetX < width) - { - // ReSharper disable once AccessToDisposedClosure - Color color = sourceBitmap.GetPixel(offsetX, offsetY); - double k = kernel[i, j]; - divider += k; - - red += k * color.R; - green += k * color.G; - blue += k * color.B; - alpha += k * color.A; - - processedKernelSize++; - } - } - } - - // Check to see if all kernel elements were processed - if (processedKernelSize == kernelSize) - { - // All kernel elements are processed; we are not on the edge. - divider = this.Divider; - } - else - { - // We are on an edge; do we need to use dynamic divider or not? - if (!this.UseDynamicDividerForEdges) - { - // Apply the set divider. - divider = this.Divider; - } - } - - // Check and apply the divider - if ((long)divider != 0) - { - red /= divider; - green /= divider; - blue /= divider; - alpha /= divider; - } - - // Add any applicable threshold. - red += threshold; - green += threshold; - blue += threshold; - alpha += threshold; - - // ReSharper disable once AccessToDisposedClosure - destinationBitmap.SetPixel(x, y, Color.FromArgb(alpha.ToByte(), red.ToByte(), green.ToByte(), blue.ToByte())); - } - }); - } - } - - return destination; - } - - #region Private - /// - /// Implementation of 1D Gaussian G(x) function - /// - /// The x provided to G(x) - /// The Gaussian G(x) - private double Gaussian(double x) - { - const double Numerator = 1.0; - double denominator = Math.Sqrt(2 * Math.PI) * this.standardDeviation; - - double exponentNumerator = -x * x; - double exponentDenominator = 2 * Math.Pow(this.standardDeviation, 2); - - double left = Numerator / denominator; - double right = Math.Exp(exponentNumerator / exponentDenominator); - - return left * right; - } - - /// - /// Implementation of 2D Gaussian G(x) function - /// - /// The x provided to G(x y) - /// The y provided to G(x y) - /// The Gaussian G(x y) - private double Gaussian2D(double x, double y) - { - const double Numerator = 1.0; - double denominator = (2 * Math.PI) * Math.Pow(this.standardDeviation, 2); - - double exponentNumerator = (-x * x) + (-y * y); - double exponentDenominator = 2 * Math.Pow(this.standardDeviation, 2); - - double left = Numerator / denominator; - double right = Math.Exp(exponentNumerator / exponentDenominator); - - return left * right; - } - #endregion - } -} diff --git a/old/src/ImageProcessor/Imaging/CropLayer.cs b/old/src/ImageProcessor/Imaging/CropLayer.cs deleted file mode 100644 index a863ad6b2..000000000 --- a/old/src/ImageProcessor/Imaging/CropLayer.cs +++ /dev/null @@ -1,128 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the properties required to crop an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System; - - /// - /// Encapsulates the properties required to crop an image. - /// - public class CropLayer - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The left coordinate of the crop layer. - /// - /// - /// The top coordinate of the crop layer. - /// - /// - /// The right coordinate of the crop layer. - /// - /// - /// The bottom coordinate of the crop layer. - /// - /// - /// The . - /// - /// - /// If the is set to CropMode.Percentage then the four coordinates - /// become percentages to reduce from each edge. - /// - public CropLayer(float left, float top, float right, float bottom, CropMode cropMode = CropMode.Percentage) - { - if (left < 0 || top < 0 || right < 0 || bottom < 0) - { - throw new ArgumentOutOfRangeException(); - } - - this.Left = left; - this.Top = top; - this.Right = right; - this.Bottom = bottom; - this.CropMode = cropMode; - } - - /// - /// Gets or sets the left coordinate of the crop layer. - /// - public float Left { get; set; } - - /// - /// Gets or sets the top coordinate of the crop layer. - /// - public float Top { get; set; } - - /// - /// Gets or sets the right coordinate of the crop layer. - /// - public float Right { get; set; } - - /// - /// Gets or sets the bottom coordinate of the crop layer. - /// - public float Bottom { get; set; } - - /// - /// Gets or sets the . - /// - public CropMode CropMode { get; set; } - - /// - /// Determines whether the specified , is - /// equal to this instance. - /// - /// - /// The to compare with this instance. - /// - /// - /// true if the specified is equal to - /// this instance; otherwise, false. - /// - public override bool Equals(object obj) - { - CropLayer cropLayer = obj as CropLayer; - - if (cropLayer == null) - { - return false; - } - - // Define the tolerance for variation in their values - return Math.Abs(this.Top - cropLayer.Top) <= Math.Abs(this.Top * .0001) - && Math.Abs(this.Right - cropLayer.Right) <= Math.Abs(this.Right * .0001) - && Math.Abs(this.Bottom - cropLayer.Bottom) <= Math.Abs(this.Bottom * .0001) - && Math.Abs(this.Left - cropLayer.Left) <= Math.Abs(this.Left * .0001) - && this.CropMode.Equals(cropLayer.CropMode); - } - - /// - /// Serves as a hash function for a particular type. - /// - /// - /// A hash code for the current . - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.Left.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Top.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Right.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Bottom.GetHashCode(); - hashCode = (hashCode * 397) ^ (int)this.CropMode; - return hashCode; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/CropMode.cs b/old/src/ImageProcessor/Imaging/CropMode.cs deleted file mode 100644 index a0b9fe0d2..000000000 --- a/old/src/ImageProcessor/Imaging/CropMode.cs +++ /dev/null @@ -1,28 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Enumerated cop modes to apply to cropped images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - /// - /// Enumerated cop modes to apply to cropped images. - /// - public enum CropMode - { - /// - /// Crops the image using the standard rectangle model of x, y, width, height. - /// - Pixels, - - /// - /// Crops the image using percentages model left, top, right, bottom. - /// - Percentage - } -} diff --git a/old/src/ImageProcessor/Imaging/FastBitmap.cs b/old/src/ImageProcessor/Imaging/FastBitmap.cs deleted file mode 100644 index 195aa6fd5..000000000 --- a/old/src/ImageProcessor/Imaging/FastBitmap.cs +++ /dev/null @@ -1,681 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Allows fast access to 's pixel data. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System; - using System.Drawing; - using System.Drawing.Imaging; - using System.Runtime.InteropServices; - - using ImageProcessor.Imaging.Colors; - - /// - /// Allows fast access to 's pixel data. - /// - public unsafe class FastBitmap : IDisposable - { - /// - /// The integral representation of the 8bppIndexed pixel format. - /// - // ReSharper disable once InconsistentNaming - private const int Format8bppIndexed = (int)PixelFormat.Format8bppIndexed; - - /// - /// The integral representation of the 24bppRgb pixel format. - /// - // ReSharper disable once InconsistentNaming - private const int Format24bppRgb = (int)PixelFormat.Format24bppRgb; - - /// - /// The integral representation of the 32bppArgb pixel format. - /// - // ReSharper disable once InconsistentNaming - private const int Format32bppArgb = (int)PixelFormat.Format32bppArgb; - - /// - /// The integral representation of the 32bppPArgb pixel format. - /// - // ReSharper disable once InconsistentNaming - private const int Format32bppPArgb = (int)PixelFormat.Format32bppPArgb; - - /// - /// The bitmap. - /// - private readonly Bitmap bitmap; - - /// - /// The width of the bitmap. - /// - private readonly int width; - - /// - /// The height of the bitmap. - /// - private readonly int height; - - /// - /// The color channel - blue, green, red, alpha. - /// - private readonly int channel; - - /// - /// Whether to compute integral rectangles. - /// - private readonly bool computeIntegrals; - - /// - /// Whether to compute tilted integral rectangles. - /// - private readonly bool computeTilted; - - /// - /// The normal integral image. - /// - private long[,] normalSumImage; - - /// - /// The squared integral image. - /// - private long[,] squaredSumImage; - - /// - /// The tilted sum image. - /// - private long[,] tiltedSumImage; - - /// - /// The normal width. - /// - private int normalWidth; - - /// - /// The tilted width. - /// - private int tiltedWidth; - - /// - /// The number of bytes in a row. - /// - private int bytesInARow; - - /// - /// The normal integral sum. - /// - private long* normalSum; - - /// - /// The squared integral sum. - /// - private long* squaredSum; - - /// - /// The tilted integral sum. - /// - private long* tiltedSum; - - /// - /// The normal sum handle. - /// - private GCHandle normalSumHandle; - - /// - /// The squared sum handle. - /// - private GCHandle squaredSumHandle; - - /// - /// The tilted sum handle. - /// - private GCHandle tiltedSumHandle; - - /// - /// The size of the color32 structure. - /// - private int pixelSize; - - /// - /// The bitmap data. - /// - private BitmapData bitmapData; - - /// - /// The position of the first pixel in the bitmap. - /// - private byte* pixelBase; - - /// - /// A value indicating whether this instance of the given entity has been disposed. - /// - /// if this instance has been disposed; otherwise, . - /// - /// If the entity is disposed, it must not be disposed a second - /// time. The isDisposed field is set the first time the entity - /// is disposed. If the isDisposed field is true, then the Dispose() - /// method will not dispose again. This help not to prolong the entity's - /// life in the Garbage Collector. - /// - private bool isDisposed; - - /// - /// Initializes a new instance of the class. - /// - /// The input bitmap. - public FastBitmap(Image bitmap) - : this(bitmap, false) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The input bitmap. - /// - /// Whether to compute integral rectangles. - /// - public FastBitmap(Image bitmap, bool computeIntegrals) - : this(bitmap, computeIntegrals, false) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The input bitmap. - /// - /// Whether to compute integral rectangles. - /// - /// - /// Whether to compute tilted integral rectangles. - /// - public FastBitmap(Image bitmap, bool computeIntegrals, bool computeTilted) - { - int pixelFormat = (int)bitmap.PixelFormat; - - // Check image format - if (!(pixelFormat == Format8bppIndexed || - pixelFormat == Format24bppRgb || - pixelFormat == Format32bppArgb || - pixelFormat == Format32bppPArgb)) - { - throw new ArgumentException("Only 8bpp, 24bpp and 32bpp images are supported."); - } - - this.bitmap = (Bitmap)bitmap; - this.width = this.bitmap.Width; - this.height = this.bitmap.Height; - - this.channel = pixelFormat == Format8bppIndexed ? 0 : 2; - this.computeIntegrals = computeIntegrals; - this.computeTilted = computeTilted; - - this.LockBitmap(); - } - - /// - /// Gets the width, in pixels of the . - /// - public int Width - { - get - { - return this.width; - } - } - - /// - /// Gets the height, in pixels of the . - /// - public int Height - { - get - { - return this.height; - } - } - - /// - /// Gets the Integral Image for values' sum. - /// - public long[,] NormalImage - { - get { return this.normalSumImage; } - } - - /// - /// Gets the Integral Image for values' squared sum. - /// - public long[,] SquaredImage - { - get { return this.squaredSumImage; } - } - - /// - /// Gets the Integral Image for tilted values' sum. - /// - public long[,] TiltedImage - { - get { return this.tiltedSumImage; } - } - - /// - /// Gets the pixel data for the given position. - /// - /// - /// The x position of the pixel. - /// - /// - /// The y position of the pixel. - /// - /// - /// The . - /// - private Color32* this[int x, int y] - { - get { return (Color32*)(this.pixelBase + (y * this.bytesInARow) + (x * this.pixelSize)); } - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator Image(FastBitmap fastBitmap) - { - return fastBitmap.bitmap; - } - - /// - /// Allows the implicit conversion of an instance of to a - /// . - /// - /// - /// The instance of to convert. - /// - /// - /// An instance of . - /// - public static implicit operator Bitmap(FastBitmap fastBitmap) - { - return fastBitmap.bitmap; - } - - /// - /// Gets the color at the specified pixel of the . - /// - /// The x-coordinate of the pixel to retrieve. - /// The y-coordinate of the pixel to retrieve. - /// The at the given pixel. - public Color GetPixel(int x, int y) - { -#if DEBUG - if ((x < 0) || (x >= this.width)) - { - throw new ArgumentOutOfRangeException("x", "Value cannot be less than zero or greater than the bitmap width."); - } - - if ((y < 0) || (y >= this.height)) - { - throw new ArgumentOutOfRangeException("y", "Value cannot be less than zero or greater than the bitmap height."); - } -#endif - Color32* data = this[x, y]; - return Color.FromArgb(data->A, data->R, data->G, data->B); - } - - /// - /// Sets the color of the specified pixel of the . - /// - /// The x-coordinate of the pixel to set. - /// The y-coordinate of the pixel to set. - /// - /// A color structure that represents the - /// color to set the specified pixel. - /// - public void SetPixel(int x, int y, Color color) - { -#if DEBUG - if ((x < 0) || (x >= this.width)) - { - throw new ArgumentOutOfRangeException("x", "Value cannot be less than zero or greater than the bitmap width."); - } - - if ((y < 0) || (y >= this.height)) - { - throw new ArgumentOutOfRangeException("y", "Value cannot be less than zero or greater than the bitmap height."); - } -#endif - Color32* data = this[x, y]; - data->R = color.R; - data->G = color.G; - data->B = color.B; - data->A = color.A; - } - - /// - /// Gets the sum of the pixels in a rectangle of the Integral image. - /// - /// The horizontal position of the rectangle x. - /// The vertical position of the rectangle y. - /// The rectangle's width w. - /// The rectangle's height h. - /// - /// The sum of all pixels contained in the rectangle, computed - /// as I[y, x] + I[y + h, x + w] - I[y + h, x] - I[y, x + w]. - /// - public long GetSum(int x, int y, int rectangleWidth, int rectangleHeight) - { - int a = (this.normalWidth * y) + x; - int b = (this.normalWidth * (y + rectangleHeight)) + (x + rectangleWidth); - int c = (this.normalWidth * (y + rectangleHeight)) + x; - int d = (this.normalWidth * y) + (x + rectangleWidth); - - return this.normalSum[a] + this.normalSum[b] - this.normalSum[c] - this.normalSum[d]; - } - - /// - /// Gets the sum of the squared pixels in a rectangle of the Integral image. - /// - /// The horizontal position of the rectangle x. - /// The vertical position of the rectangle y. - /// The rectangle's width w. - /// The rectangle's height h. - /// - /// The sum of all pixels contained in the rectangle, computed - /// as I²[y, x] + I²[y + h, x + w] - I²[y + h, x] - I²[y, x + w]. - /// - public long GetSum2(int x, int y, int rectangleWidth, int rectangleHeight) - { - int a = (this.normalWidth * y) + x; - int b = (this.normalWidth * (y + rectangleHeight)) + (x + rectangleWidth); - int c = (this.normalWidth * (y + rectangleHeight)) + x; - int d = (this.normalWidth * y) + (x + rectangleWidth); - - return this.squaredSum[a] + this.squaredSum[b] - this.squaredSum[c] - this.squaredSum[d]; - } - - /// - /// Gets the sum of the pixels in a tilted rectangle of the Integral image. - /// - /// The horizontal position of the rectangle x. - /// The vertical position of the rectangle y. - /// The rectangle's width w. - /// The rectangle's height h. - /// - /// The sum of all pixels contained in the rectangle, computed - /// as T[y + w, x + w + 1] + T[y + h, x - h + 1] - T[y, x + 1] - T[y + w + h, x + w - h + 1]. - /// - public long GetSumT(int x, int y, int rectangleWidth, int rectangleHeight) - { - int a = (this.tiltedWidth * (y + rectangleWidth)) + (x + rectangleWidth + 1); - int b = (this.tiltedWidth * (y + rectangleHeight)) + (x - rectangleHeight + 1); - int c = (this.tiltedWidth * y) + (x + 1); - int d = (this.tiltedWidth * (y + rectangleWidth + rectangleHeight)) + (x + rectangleWidth - rectangleHeight + 1); - - return this.tiltedSum[a] + this.tiltedSum[b] - this.tiltedSum[c] - this.tiltedSum[d]; - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - public void Dispose() - { - this.Dispose(true); - - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SuppressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - /// - /// Determines whether the specified is equal to the current . - /// - /// - /// true if the specified object is equal to the current object; otherwise, false. - /// - /// The object to compare with the current object. - public override bool Equals(object obj) - { - FastBitmap fastBitmap = obj as FastBitmap; - - if (fastBitmap == null) - { - return false; - } - - return this.bitmap == fastBitmap.bitmap; - } - - /// - /// Serves as a hash function for a particular type. - /// - /// - /// A hash code for the current . - /// - public override int GetHashCode() - { - return this.bitmap.GetHashCode(); - } - - /// - /// Disposes the object and frees resources for the Garbage Collector. - /// - /// If true, the object gets disposed. - protected virtual void Dispose(bool disposing) - { - if (this.isDisposed) - { - return; - } - - if (disposing) - { - // Dispose of any managed resources here. - this.UnlockBitmap(); - } - - // Call the appropriate methods to clean up - // unmanaged resources here. - if (this.normalSumHandle.IsAllocated) - { - this.normalSumHandle.Free(); - this.normalSum = null; - } - - if (this.squaredSumHandle.IsAllocated) - { - this.squaredSumHandle.Free(); - this.squaredSum = null; - } - - if (this.tiltedSumHandle.IsAllocated) - { - this.tiltedSumHandle.Free(); - this.tiltedSum = null; - } - - // Note disposing is done. - this.isDisposed = true; - } - - /// - /// Locks the bitmap into system memory. - /// - private void LockBitmap() - { - Rectangle bounds = new Rectangle(Point.Empty, this.bitmap.Size); - - // Figure out the number of bytes in a row. This is rounded up to be a multiple - // of 4 bytes, since a scan line in an image must always be a multiple of 4 bytes - // in length. - this.pixelSize = Image.GetPixelFormatSize(this.bitmap.PixelFormat) / 8; - this.bytesInARow = bounds.Width * this.pixelSize; - if (this.bytesInARow % 4 != 0) - { - this.bytesInARow = 4 * ((this.bytesInARow / 4) + 1); - } - - // Lock the bitmap - this.bitmapData = this.bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb); - - // Set the value to the first scan line - this.pixelBase = (byte*)this.bitmapData.Scan0.ToPointer(); - - if (this.computeIntegrals) - { - // Allocate values for integral image calculation. - this.normalWidth = this.width + 1; - int normalHeight = this.height + 1; - - this.tiltedWidth = this.width + 2; - int tiltedHeight = this.height + 2; - - this.normalSumImage = new long[normalHeight, this.normalWidth]; - this.normalSumHandle = GCHandle.Alloc(this.normalSumImage, GCHandleType.Pinned); - this.normalSum = (long*)this.normalSumHandle.AddrOfPinnedObject().ToPointer(); - - this.squaredSumImage = new long[normalHeight, this.normalWidth]; - this.squaredSumHandle = GCHandle.Alloc(this.squaredSumImage, GCHandleType.Pinned); - this.squaredSum = (long*)this.squaredSumHandle.AddrOfPinnedObject().ToPointer(); - - if (this.computeTilted) - { - this.tiltedSumImage = new long[tiltedHeight, this.tiltedWidth]; - this.tiltedSumHandle = GCHandle.Alloc(this.tiltedSumImage, GCHandleType.Pinned); - this.tiltedSum = (long*)this.tiltedSumHandle.AddrOfPinnedObject().ToPointer(); - } - - this.CalculateIntegrals(); - } - } - - /// - /// Computes all possible rectangular areas in the image. - /// - private void CalculateIntegrals() - { - // Calculate integral and integral squared values. - int stride = this.bitmapData.Stride; - int offset = stride - this.bytesInARow; - byte* srcStart = this.pixelBase + this.channel; - - // Do the job - byte* src = srcStart; - - // For each line - for (int y = 1; y <= this.height; y++) - { - int yy = this.normalWidth * y; - int y1 = this.normalWidth * (y - 1); - - // For each pixel - for (int x = 1; x <= this.width; x++, src += this.pixelSize) - { - int pixel = *src; - int pixelSquared = pixel * pixel; - - int r = yy + x; - int a = yy + (x - 1); - int b = y1 + x; - int g = y1 + (x - 1); - - this.normalSum[r] = pixel + this.normalSum[a] + this.normalSum[b] - this.normalSum[g]; - this.squaredSum[r] = pixelSquared + this.squaredSum[a] + this.squaredSum[b] - this.squaredSum[g]; - } - - src += offset; - } - - if (this.computeTilted) - { - src = srcStart; - - // Left-to-right, top-to-bottom pass - for (int y = 1; y <= this.height; y++, src += offset) - { - int yy = this.tiltedWidth * y; - int y1 = this.tiltedWidth * (y - 1); - - for (int x = 2; x < this.width + 2; x++, src += this.pixelSize) - { - int a = y1 + (x - 1); - int b = yy + (x - 1); - int g = y1 + (x - 2); - int r = yy + x; - - this.tiltedSum[r] = *src + this.tiltedSum[a] + this.tiltedSum[b] - this.tiltedSum[g]; - } - } - - { - int yy = this.tiltedWidth * this.height; - int y1 = this.tiltedWidth * (this.height + 1); - - for (int x = 2; x < this.width + 2; x++, src += this.pixelSize) - { - int a = yy + (x - 1); - int c = yy + (x - 2); - int b = y1 + (x - 1); - int r = y1 + x; - - this.tiltedSum[r] = this.tiltedSum[a] + this.tiltedSum[b] - this.tiltedSum[c]; - } - } - - // Right-to-left, bottom-to-top pass - for (int y = this.height; y >= 0; y--) - { - int yy = this.tiltedWidth * y; - int y1 = this.tiltedWidth * (y + 1); - - for (int x = this.width + 1; x >= 1; x--) - { - int r = yy + x; - int b = y1 + (x - 1); - - this.tiltedSum[r] += this.tiltedSum[b]; - } - } - - for (int y = this.height + 1; y >= 0; y--) - { - int yy = this.tiltedWidth * y; - - for (int x = this.width + 1; x >= 2; x--) - { - int r = yy + x; - int b = yy + (x - 2); - - this.tiltedSum[r] -= this.tiltedSum[b]; - } - } - } - } - - /// - /// Unlocks the bitmap from system memory. - /// - private void UnlockBitmap() - { - // Copy the RGB values back to the bitmap and unlock the bitmap. - this.bitmap.UnlockBits(this.bitmapData); - this.bitmapData = null; - this.pixelBase = null; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Artistic/HalftoneFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Artistic/HalftoneFilter.cs deleted file mode 100644 index 3bab509a7..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Artistic/HalftoneFilter.cs +++ /dev/null @@ -1,440 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The halftone filter applies a classical CMYK filter to the given image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Artistic -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Threading.Tasks; - - using ImageProcessor.Imaging.Colors; - using ImageProcessor.Imaging.Helpers; - - /// - /// The halftone filter applies a classical CMYK filter to the given image. - /// - public class HalftoneFilter - { - /// - /// The angle of the cyan component in degrees. - /// - private float cyanAngle = 15f; - - /// - /// The angle of the magenta component in degrees. - /// - private float magentaAngle = 75f; - - /// - /// The angle of the yellow component in degrees. - /// - // ReSharper disable once RedundantDefaultMemberInitializer - private float yellowAngle = 0f; - - /// - /// The angle of the keyline component in degrees. - /// - private float keylineAngle = 45f; - - /// - /// The distance between component points. - /// - private int distance = 4; - - /// - /// Initializes a new instance of the class. - /// - public HalftoneFilter() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The distance. - /// - public HalftoneFilter(int distance) - { - this.distance = distance; - } - - /// - /// Gets or sets the angle of the cyan component in degrees. - /// - public float CyanAngle - { - get - { - return this.cyanAngle; - } - - set - { - this.cyanAngle = value; - } - } - - /// - /// Gets or sets the angle of the magenta component in degrees. - /// - public float MagentaAngle - { - get - { - return this.magentaAngle; - } - - set - { - this.magentaAngle = value; - } - } - - /// - /// Gets or sets the angle of the yellow component in degrees. - /// - public float YellowAngle - { - get - { - return this.yellowAngle; - } - - set - { - this.yellowAngle = value; - } - } - - /// - /// Gets or sets the angle of the keyline black component in degrees. - /// - public float KeylineAngle - { - get - { - return this.keylineAngle; - } - - set - { - this.keylineAngle = value; - } - } - - /// - /// Gets or sets the distance between component points. - /// - public int Distance - { - get - { - return this.distance; - } - - set - { - this.distance = value; - } - } - - /// - /// Applies the halftone filter. - /// - /// - /// The to apply the filter to. - /// - /// - /// The with the filter applied. - /// - public Bitmap ApplyFilter(Bitmap source) - { - // TODO: Make this class implement an interface? - Bitmap padded = null; - Bitmap cyan = null; - Bitmap magenta = null; - Bitmap yellow = null; - Bitmap keyline = null; - Bitmap newImage = null; - - try - { - int sourceWidth = source.Width; - int sourceHeight = source.Height; - int width = source.Width + this.distance; - int height = source.Height + this.distance; - - // Draw a slightly larger image, flipping the top/left pixels to prevent - // jagged edge of output. - padded = new Bitmap(width, height); - padded.SetResolution(source.HorizontalResolution, source.VerticalResolution); - using (Graphics graphicsPadded = Graphics.FromImage(padded)) - { - graphicsPadded.Clear(Color.White); - Rectangle destinationRectangle = new Rectangle(0, 0, sourceWidth + this.distance, source.Height + this.distance); - using (TextureBrush tb = new TextureBrush(source)) - { - tb.WrapMode = WrapMode.TileFlipXY; - tb.TranslateTransform(this.distance, this.distance); - graphicsPadded.FillRectangle(tb, destinationRectangle); - } - } - - // Calculate min and max widths/heights. - Rectangle rotatedBounds = this.GetBoundingRectangle(width, height); - int minY = -(rotatedBounds.Height + height); - int maxY = rotatedBounds.Height + height; - int minX = -(rotatedBounds.Width + width); - int maxX = rotatedBounds.Width + width; - Point center = Point.Empty; - - // Yellow oversaturates the output. - int offset = this.distance; - float yellowMultiplier = this.distance * 1.334f; - float magentaMultiplier = this.distance * 1.667f; - float multiplier = this.distance * 2.2f; - float max = this.distance * (float)Math.Sqrt(2); - - // Bump up the keyline max so that black looks black. - float keylineMax = max * (float)Math.Sqrt(2); - - // Color sampled process colours from Wikipedia pages. - // Keyline brush is declared separately. - Brush cyanBrush = new SolidBrush(Color.FromArgb(0, 183, 235)); - Brush magentaBrush = new SolidBrush(Color.FromArgb(255, 0, 144)); - Brush yellowBrush = new SolidBrush(Color.FromArgb(255, 239, 0)); - - // Create our images. - cyan = new Bitmap(width, height); - magenta = new Bitmap(width, height); - yellow = new Bitmap(width, height); - keyline = new Bitmap(width, height); - newImage = new Bitmap(sourceWidth, sourceHeight); - - // Ensure the correct resolution is set. - cyan.SetResolution(source.HorizontalResolution, source.VerticalResolution); - magenta.SetResolution(source.HorizontalResolution, source.VerticalResolution); - yellow.SetResolution(source.HorizontalResolution, source.VerticalResolution); - keyline.SetResolution(source.HorizontalResolution, source.VerticalResolution); - newImage.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - // Check bounds against this. - Rectangle rectangle = new Rectangle(0, 0, width, height); - - using (Graphics graphicsCyan = Graphics.FromImage(cyan)) - using (Graphics graphicsMagenta = Graphics.FromImage(magenta)) - using (Graphics graphicsYellow = Graphics.FromImage(yellow)) - using (Graphics graphicsKeyline = Graphics.FromImage(keyline)) - { - // Set the quality properties. - graphicsCyan.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphicsMagenta.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphicsYellow.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphicsKeyline.PixelOffsetMode = PixelOffsetMode.HighQuality; - - graphicsCyan.SmoothingMode = SmoothingMode.AntiAlias; - graphicsMagenta.SmoothingMode = SmoothingMode.AntiAlias; - graphicsYellow.SmoothingMode = SmoothingMode.AntiAlias; - graphicsKeyline.SmoothingMode = SmoothingMode.AntiAlias; - - graphicsCyan.CompositingQuality = CompositingQuality.HighQuality; - graphicsMagenta.CompositingQuality = CompositingQuality.HighQuality; - graphicsYellow.CompositingQuality = CompositingQuality.HighQuality; - graphicsKeyline.CompositingQuality = CompositingQuality.HighQuality; - - // Set up the canvas. - graphicsCyan.Clear(Color.White); - graphicsMagenta.Clear(Color.White); - graphicsYellow.Clear(Color.White); - graphicsKeyline.Clear(Color.White); - - // This is too slow. The graphics object can't be called within a parallel - // loop so we have to do it old school. :( - using (FastBitmap sourceBitmap = new FastBitmap(padded)) - { - for (int y = minY; y < maxY; y += offset) - { - for (int x = minX; x < maxX; x += offset) - { - Color color; - CmykColor cmykColor; - float brushWidth; - - // Cyan - Point rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.cyanAngle, center); - int angledX = rotatedPoint.X; - int angledY = rotatedPoint.Y; - if (rectangle.Contains(new Point(angledX, angledY))) - { - color = sourceBitmap.GetPixel(angledX, angledY); - cmykColor = color; - brushWidth = Math.Min((cmykColor.C / 100f) * multiplier, max); - graphicsCyan.FillEllipse(cyanBrush, angledX, angledY, brushWidth, brushWidth); - } - - // Magenta - rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.magentaAngle, center); - angledX = rotatedPoint.X; - angledY = rotatedPoint.Y; - if (rectangle.Contains(new Point(angledX, angledY))) - { - color = sourceBitmap.GetPixel(angledX, angledY); - cmykColor = color; - brushWidth = Math.Min((cmykColor.M / 100f) * magentaMultiplier, max); - graphicsMagenta.FillEllipse(magentaBrush, angledX, angledY, brushWidth, brushWidth); - } - - // Yellow - rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.yellowAngle, center); - angledX = rotatedPoint.X; - angledY = rotatedPoint.Y; - if (rectangle.Contains(new Point(angledX, angledY))) - { - color = sourceBitmap.GetPixel(angledX, angledY); - cmykColor = color; - brushWidth = Math.Min((cmykColor.Y / 100f) * yellowMultiplier, max); - graphicsYellow.FillEllipse(yellowBrush, angledX, angledY, brushWidth, brushWidth); - } - - // Keyline - rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.keylineAngle, center); - angledX = rotatedPoint.X; - angledY = rotatedPoint.Y; - if (rectangle.Contains(new Point(angledX, angledY))) - { - color = sourceBitmap.GetPixel(angledX, angledY); - cmykColor = color; - brushWidth = Math.Min((cmykColor.K / 100f) * multiplier, keylineMax); - - // Just using black is too dark. - Brush keylineBrush = new SolidBrush(CmykColor.FromCmykColor(0, 0, 0, cmykColor.K)); - graphicsKeyline.FillEllipse(keylineBrush, angledX, angledY, brushWidth, brushWidth); - } - } - } - } - - // Set our white background. - using (Graphics graphics = Graphics.FromImage(newImage)) - { - graphics.Clear(Color.White); - } - - // Blend the colors now to mimic adaptive blending. - using (FastBitmap cyanBitmap = new FastBitmap(cyan)) - using (FastBitmap magentaBitmap = new FastBitmap(magenta)) - using (FastBitmap yellowBitmap = new FastBitmap(yellow)) - using (FastBitmap keylineBitmap = new FastBitmap(keyline)) - using (FastBitmap destinationBitmap = new FastBitmap(newImage)) - { - Parallel.For( - offset, - height, - y => - { - for (int x = offset; x < width; x++) - { - // ReSharper disable AccessToDisposedClosure - Color cyanPixel = cyanBitmap.GetPixel(x, y); - Color magentaPixel = magentaBitmap.GetPixel(x, y); - Color yellowPixel = yellowBitmap.GetPixel(x, y); - Color keylinePixel = keylineBitmap.GetPixel(x, y); - - // Negate the offset. - int xBack = x - offset; - int yBack = y - offset; - - CmykColor blended = cyanPixel.AddAsCmykColor(magentaPixel, yellowPixel, keylinePixel); - if (rectangle.Contains(new Point(xBack, yBack))) - { - destinationBitmap.SetPixel(xBack, yBack, blended); - } - // ReSharper restore AccessToDisposedClosure - } - }); - } - } - - padded.Dispose(); - cyan.Dispose(); - magenta.Dispose(); - yellow.Dispose(); - keyline.Dispose(); - source.Dispose(); - source = newImage; - } - catch - { - if (padded != null) - { - padded.Dispose(); - } - - if (cyan != null) - { - cyan.Dispose(); - } - - if (magenta != null) - { - magenta.Dispose(); - } - - if (yellow != null) - { - yellow.Dispose(); - } - - if (keyline != null) - { - keyline.Dispose(); - } - - if (newImage != null) - { - newImage.Dispose(); - } - } - - return source; - } - - /// - /// Gets the bounding rectangle of the image based on the rotating angles. - /// - /// - /// The width of the image. - /// - /// - /// The height of the image. - /// - /// - /// The . - /// - private Rectangle GetBoundingRectangle(int width, int height) - { - int maxWidth = 0; - int maxHeight = 0; - List angles = new List { this.CyanAngle, this.MagentaAngle, this.YellowAngle, this.KeylineAngle }; - - foreach (float angle in angles) - { - Size rotatedSize = ImageMaths.GetBoundingRotatedRectangle(width, height, angle).Size; - maxWidth = Math.Max(maxWidth, rotatedSize.Width); - maxHeight = Math.Max(maxHeight, rotatedSize.Height); - } - - return new Rectangle(0, 0, maxWidth, maxHeight); - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Artistic/OilPaintingFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Artistic/OilPaintingFilter.cs deleted file mode 100644 index bc5bc7e11..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Artistic/OilPaintingFilter.cs +++ /dev/null @@ -1,193 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The oil painting filter. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Artistic -{ - using System; - using System.Drawing; - using System.Threading.Tasks; - - using ImageProcessor.Common.Extensions; - - /// - /// The oil painting filter. - /// - public class OilPaintingFilter - { - /// - /// The levels. - /// - private int levels; - - /// - /// The brush size. - /// - private int brushSize; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The number of levels. - /// - /// - /// The brush size. - /// - public OilPaintingFilter(int levels, int brushSize) - { - this.levels = levels; - this.brushSize = brushSize; - } - - /// - /// Gets or sets the number of levels. - /// - public int Levels - { - get - { - return this.levels; - } - - set - { - if (value > 0) - { - this.levels = value; - } - } - } - - /// - /// Gets or sets the brush size. - /// - public int BrushSize - { - get - { - return this.brushSize; - } - - set - { - if (value > 0) - { - this.brushSize = value; - } - } - } - - /// - /// Applies the oil painting filter. - /// - /// - /// The source. - /// - /// - /// The . - /// - public Bitmap ApplyFilter(Bitmap source) - { - // TODO: Make this class implement an interface? - int width = source.Width; - int height = source.Height; - - int radius = this.brushSize >> 1; - - Bitmap destination = new Bitmap(width, height); - destination.SetResolution(source.HorizontalResolution, source.VerticalResolution); - using (FastBitmap sourceBitmap = new FastBitmap(source)) - { - using (FastBitmap destinationBitmap = new FastBitmap(destination)) - { - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - int maxIntensity = 0; - int maxIndex = 0; - int[] intensityBin = new int[this.levels]; - int[] blueBin = new int[this.levels]; - int[] greenBin = new int[this.levels]; - int[] redBin = new int[this.levels]; - byte sourceAlpha = 255; - - for (int i = 0; i <= radius; i++) - { - int ir = i - radius; - int offsetY = y + ir; - - // Skip the current row - if (offsetY < 0) - { - continue; - } - - // Outwith the current bounds so break. - if (offsetY >= height) - { - break; - } - - for (int fx = 0; fx <= radius; fx++) - { - int jr = fx - radius; - int offsetX = x + jr; - - // Skip the column - if (offsetX < 0) - { - continue; - } - - if (offsetX < width) - { - // ReSharper disable once AccessToDisposedClosure - Color color = sourceBitmap.GetPixel(offsetX, offsetY); - - byte sourceBlue = color.B; - byte sourceGreen = color.G; - byte sourceRed = color.R; - sourceAlpha = color.A; - - int currentIntensity = (int)Math.Round(((sourceBlue + sourceGreen + sourceRed) / 3.0 * (this.levels - 1)) / 255.0); - - intensityBin[currentIntensity] += 1; - blueBin[currentIntensity] += sourceBlue; - greenBin[currentIntensity] += sourceGreen; - redBin[currentIntensity] += sourceRed; - - if (intensityBin[currentIntensity] > maxIntensity) - { - maxIntensity = intensityBin[currentIntensity]; - maxIndex = currentIntensity; - } - } - } - } - - byte blue = Math.Abs(blueBin[maxIndex] / maxIntensity).ToByte(); - byte green = Math.Abs(greenBin[maxIndex] / maxIntensity).ToByte(); - byte red = Math.Abs(redBin[maxIndex] / maxIntensity).ToByte(); - - // ReSharper disable once AccessToDisposedClosure - destinationBitmap.SetPixel(x, y, Color.FromArgb(sourceAlpha, red, green, blue)); - } - }); - } - } - - return destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Binarization/BinaryThreshold.cs b/old/src/ImageProcessor/Imaging/Filters/Binarization/BinaryThreshold.cs deleted file mode 100644 index 41eb3530c..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Binarization/BinaryThreshold.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Performs binary threshold filtering against a given greyscale image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Binarization -{ - using System.Drawing; - using System.Threading.Tasks; - - /// - /// Performs binary threshold filtering against a given greyscale image. - /// - public class BinaryThreshold - { - /// - /// The threshold value. - /// - private byte threshold; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The threshold. - /// - public BinaryThreshold(byte threshold = 10) - { - this.threshold = threshold; - } - - /// - /// Gets or sets the threshold. - /// - public byte Threshold - { - get - { - return this.threshold; - } - - set - { - this.threshold = value; - } - } - - /// - /// Processes the given bitmap to apply the threshold. - /// - /// - /// The image to process. - /// - /// - /// A processed bitmap. - /// - public Bitmap ProcessFilter(Bitmap source) - { - int width = source.Width; - int height = source.Height; - - using (FastBitmap sourceBitmap = new FastBitmap(source)) - { - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - // ReSharper disable AccessToDisposedClosure - Color color = sourceBitmap.GetPixel(x, y); - sourceBitmap.SetPixel(x, y, color.B >= this.threshold ? Color.White : Color.Black); - - // ReSharper restore AccessToDisposedClosure - } - }); - } - - return source; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/ConvolutionFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/ConvolutionFilter.cs deleted file mode 100644 index f974f6b9d..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/ConvolutionFilter.cs +++ /dev/null @@ -1,343 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The convolution filter for applying gradient operators to detect edges within an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - using System; - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Drawing.Imaging; - using System.Threading.Tasks; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging.Filters.Photo; - - /// - /// The convolution filter for applying gradient operators to detect edges within an image. - /// - public class ConvolutionFilter - { - /// - /// The edge filter. - /// - private readonly IEdgeFilter edgeFilter; - - /// - /// Whether to produce a greyscale output. - /// - private readonly bool greyscale; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The to apply. - /// - /// - /// Whether to produce a greyscale output. - /// - public ConvolutionFilter(IEdgeFilter edgeFilter, bool greyscale) - { - this.edgeFilter = edgeFilter; - this.greyscale = greyscale; - } - - /// - /// Processes the given bitmap to apply the current instance of . - /// - /// The image to process. - /// A processed bitmap. - public Bitmap ProcessFilter(Image source) - { - int width = source.Width; - int height = source.Height; - int maxWidth = width + 1; - int maxHeight = height + 1; - int bufferedWidth = width + 2; - int bufferedHeight = height + 2; - - Bitmap destination = new Bitmap(width, height); - Bitmap input = new Bitmap(bufferedWidth, bufferedHeight); - destination.SetResolution(source.HorizontalResolution, source.VerticalResolution); - input.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - using (Graphics graphics = Graphics.FromImage(input)) - { - // Fixes an issue with transparency not converting properly. - graphics.Clear(Color.Transparent); - - Rectangle destinationRectangle = new Rectangle(0, 0, bufferedWidth, bufferedHeight); - Rectangle rectangle = new Rectangle(0, 0, width, height); - - // If it's greyscale apply a colormatrix to the image. - using (ImageAttributes attributes = new ImageAttributes()) - { - if (this.greyscale) - { - attributes.SetColorMatrix(ColorMatrixes.GreyScale); - } - - // We use a trick here to detect right to the edges of the image. - // flip/tile the image with a pixel in excess in each direction to duplicate pixels. - // Later on we draw pixels without that excess. - using (TextureBrush tb = new TextureBrush(source, rectangle, attributes)) - { - tb.WrapMode = WrapMode.TileFlipXY; - tb.TranslateTransform(1, 1); - - graphics.FillRectangle(tb, destinationRectangle); - } - } - } - - try - { - double[,] horizontalFilter = this.edgeFilter.HorizontalGradientOperator; - - int kernelLength = horizontalFilter.GetLength(0); - int radius = kernelLength >> 1; - - using (FastBitmap sourceBitmap = new FastBitmap(input)) - { - using (FastBitmap destinationBitmap = new FastBitmap(destination)) - { - // Loop through the pixels. - Parallel.For( - 0, - bufferedHeight, - y => - { - for (int x = 0; x < bufferedWidth; x++) - { - double rX = 0; - double gX = 0; - double bX = 0; - - // Apply each matrix multiplier to the color components for each pixel. - for (int fy = 0; fy < kernelLength; fy++) - { - int fyr = fy - radius; - int offsetY = y + fyr; - - // Skip the current row - if (offsetY < 0) - { - continue; - } - - // Outwith the current bounds so break. - if (offsetY >= bufferedHeight) - { - break; - } - - for (int fx = 0; fx < kernelLength; fx++) - { - int fxr = fx - radius; - int offsetX = x + fxr; - - // Skip the column - if (offsetX < 0) - { - continue; - } - - if (offsetX < bufferedWidth) - { - // ReSharper disable once AccessToDisposedClosure - Color currentColor = sourceBitmap.GetPixel(offsetX, offsetY); - double r = currentColor.R; - double g = currentColor.G; - double b = currentColor.B; - - rX += horizontalFilter[fy, fx] * r; - - gX += horizontalFilter[fy, fx] * g; - - bX += horizontalFilter[fy, fx] * b; - } - } - } - - // Apply the equation and sanitize. - byte red = rX.ToByte(); - byte green = gX.ToByte(); - byte blue = bX.ToByte(); - - Color newColor = Color.FromArgb(red, green, blue); - if (y > 0 && x > 0 && y < maxHeight && x < maxWidth) - { - // ReSharper disable once AccessToDisposedClosure - destinationBitmap.SetPixel(x - 1, y - 1, newColor); - } - } - }); - } - } - } - finally - { - // We created a new image. Cleanup. - input.Dispose(); - } - - return destination; - } - - /// - /// Processes the given bitmap to apply the current instance of . - /// - /// The image to process. - /// A processed bitmap. - public Bitmap Process2DFilter(Image source) - { - int width = source.Width; - int height = source.Height; - int maxWidth = width + 1; - int maxHeight = height + 1; - int bufferedWidth = width + 2; - int bufferedHeight = height + 2; - - Bitmap destination = new Bitmap(width, height); - Bitmap input = new Bitmap(bufferedWidth, bufferedHeight); - destination.SetResolution(source.HorizontalResolution, source.VerticalResolution); - input.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - using (Graphics graphics = Graphics.FromImage(input)) - { - // Fixes an issue with transparency not converting properly. - graphics.Clear(Color.Transparent); - - Rectangle destinationRectangle = new Rectangle(0, 0, bufferedWidth, bufferedHeight); - Rectangle rectangle = new Rectangle(0, 0, width, height); - - // If it's greyscale apply a colormatrix to the image. - using (ImageAttributes attributes = new ImageAttributes()) - { - if (this.greyscale) - { - attributes.SetColorMatrix(ColorMatrixes.GreyScale); - } - - // We use a trick here to detect right to the edges of the image. - // flip/tile the image with a pixel in excess in each direction to duplicate pixels. - // Later on we draw pixels without that excess. - using (TextureBrush tb = new TextureBrush(source, rectangle, attributes)) - { - tb.WrapMode = WrapMode.TileFlipXY; - tb.TranslateTransform(1, 1); - - graphics.FillRectangle(tb, destinationRectangle); - } - } - } - - try - { - double[,] horizontalFilter = this.edgeFilter.HorizontalGradientOperator; - double[,] verticalFilter = ((I2DEdgeFilter)this.edgeFilter).VerticalGradientOperator; - - int kernelLength = horizontalFilter.GetLength(0); - int radius = kernelLength >> 1; - - using (FastBitmap sourceBitmap = new FastBitmap(input)) - { - using (FastBitmap destinationBitmap = new FastBitmap(destination)) - { - // Loop through the pixels. - Parallel.For( - 0, - bufferedHeight, - y => - { - for (int x = 0; x < bufferedWidth; x++) - { - double rX = 0; - double rY = 0; - double gX = 0; - double gY = 0; - double bX = 0; - double bY = 0; - - // Apply each matrix multiplier to the color components for each pixel. - for (int fy = 0; fy < kernelLength; fy++) - { - int fyr = fy - radius; - int offsetY = y + fyr; - - // Skip the current row - if (offsetY < 0) - { - continue; - } - - // Outwith the current bounds so break. - if (offsetY >= bufferedHeight) - { - break; - } - - for (int fx = 0; fx < kernelLength; fx++) - { - int fxr = fx - radius; - int offsetX = x + fxr; - - // Skip the column - if (offsetX < 0) - { - continue; - } - - if (offsetX < bufferedWidth) - { - // ReSharper disable once AccessToDisposedClosure - Color currentColor = sourceBitmap.GetPixel(offsetX, offsetY); - double r = currentColor.R; - double g = currentColor.G; - double b = currentColor.B; - - rX += horizontalFilter[fy, fx] * r; - rY += verticalFilter[fy, fx] * r; - - gX += horizontalFilter[fy, fx] * g; - gY += verticalFilter[fy, fx] * g; - - bX += horizontalFilter[fy, fx] * b; - bY += verticalFilter[fy, fx] * b; - } - } - } - - // Apply the equation and sanitize. - byte red = Math.Sqrt((rX * rX) + (rY * rY)).ToByte(); - byte green = Math.Sqrt((gX * gX) + (gY * gY)).ToByte(); - byte blue = Math.Sqrt((bX * bX) + (bY * bY)).ToByte(); - - Color newColor = Color.FromArgb(red, green, blue); - if (y > 0 && x > 0 && y < maxHeight && x < maxWidth) - { - // ReSharper disable once AccessToDisposedClosure - destinationBitmap.SetPixel(x - 1, y - 1, newColor); - } - } - }); - } - } - } - finally - { - // We created a new image. Cleanup. - input.Dispose(); - } - - return destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/I2DEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/I2DEdgeFilter.cs deleted file mode 100644 index 7e3fb9be8..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/I2DEdgeFilter.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Describes properties for creating 2 dimension edge detection filters. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// Describes properties for creating 2 dimension edge detection filters. - /// - public interface I2DEdgeFilter : IEdgeFilter - { - /// - /// Gets the vertical gradient operator. - /// - double[,] VerticalGradientOperator { get; } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/IEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/IEdgeFilter.cs deleted file mode 100644 index b89ce902d..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/IEdgeFilter.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Describes properties for creating edge detection filters. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// Describes properties for creating edge detection filters. - /// - public interface IEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - double[,] HorizontalGradientOperator { get; } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/KayyaliEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/KayyaliEdgeFilter.cs deleted file mode 100644 index 001d40511..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/KayyaliEdgeFilter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Kayyali operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Kayyali operator filter. - /// - /// - public class KayyaliEdgeFilter : I2DEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { 6, 0, -6 }, - { 0, 0, 0 }, - { -6, 0, 6 } - }; - } - } - - /// - /// Gets the vertical gradient operator. - /// - public double[,] VerticalGradientOperator - { - get - { - return new double[,] - { - { -6, 0, 6 }, - { 0, 0, 0 }, - { 6, 0, -6 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/KirschEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/KirschEdgeFilter.cs deleted file mode 100644 index 47987078e..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/KirschEdgeFilter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Kirsch operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Kirsch operator filter. - /// - /// - public class KirschEdgeFilter : I2DEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { 5, 5, 5 }, - { -3, 0, -3 }, - { -3, -3, -3 } - }; - } - } - - /// - /// Gets the vertical gradient operator. - /// - public double[,] VerticalGradientOperator - { - get - { - return new double[,] - { - { 5, -3, -3 }, - { 5, 0, -3 }, - { 5, -3, -3 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/Laplacian3X3EdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/Laplacian3X3EdgeFilter.cs deleted file mode 100644 index ccaa3d35e..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/Laplacian3X3EdgeFilter.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Laplacian 3 x 3 operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Laplacian 3 x 3 operator filter. - /// - /// - public class Laplacian3X3EdgeFilter : IEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { -1, -1, -1 }, - { -1, 8, -1 }, - { -1, -1, -1 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/Laplacian5X5EdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/Laplacian5X5EdgeFilter.cs deleted file mode 100644 index b25abbac7..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/Laplacian5X5EdgeFilter.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Laplacian 5 x 5 operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Laplacian 5 x 5 operator filter. - /// - /// - public class Laplacian5X5EdgeFilter : IEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { -1, -1, -1, -1, -1 }, - { -1, -1, -1, -1, -1 }, - { -1, -1, 24, -1, -1 }, - { -1, -1, -1, -1, -1 }, - { -1, -1, -1, -1, -1 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/LaplacianOfGaussianEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/LaplacianOfGaussianEdgeFilter.cs deleted file mode 100644 index 947796a38..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/LaplacianOfGaussianEdgeFilter.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Laplacian of Gaussian operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Laplacian of Gaussian operator filter. - /// - /// - public class LaplacianOfGaussianEdgeFilter : IEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { 0, 0, -1, 0, 0 }, - { 0, -1, -2, -1, 0 }, - { -1, -2, 16, -2, -1 }, - { 0, -1, -2, -1, 0 }, - { 0, 0, -1, 0, 0 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/PrewittEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/PrewittEdgeFilter.cs deleted file mode 100644 index 91b3272de..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/PrewittEdgeFilter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Prewitt operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Prewitt operator filter. - /// - /// - public class PrewittEdgeFilter : I2DEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { -1, 0, 1 }, - { -1, 0, 1 }, - { -1, 0, 1 } - }; - } - } - - /// - /// Gets the vertical gradient operator. - /// - public double[,] VerticalGradientOperator - { - get - { - return new double[,] - { - { 1, 1, 1 }, - { 0, 0, 0 }, - { -1, -1, -1 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/RobertsCrossEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/RobertsCrossEdgeFilter.cs deleted file mode 100644 index b121f9a45..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/RobertsCrossEdgeFilter.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Roberts Cross operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Roberts Cross operator filter. - /// - /// - public class RobertsCrossEdgeFilter : I2DEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { 1, 0 }, - { 0, -1 } - }; - } - } - - /// - /// Gets the vertical gradient operator. - /// - public double[,] VerticalGradientOperator - { - get - { - return new double[,] - { - { 0, 1 }, - { -1, 0 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/ScharrEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/ScharrEdgeFilter.cs deleted file mode 100644 index c346cb083..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/ScharrEdgeFilter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Scharr operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Scharr operator filter. - /// - /// - public class ScharrEdgeFilter : I2DEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { -3, 0, 3 }, - { -10, 0, 10 }, - { -3, 0, 3 } - }; - } - } - - /// - /// Gets the vertical gradient operator. - /// - public double[,] VerticalGradientOperator - { - get - { - return new double[,] - { - { 3, 10, 3 }, - { 0, 0, 0 }, - { -3, -10, -3 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/SobelEdgeFilter.cs b/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/SobelEdgeFilter.cs deleted file mode 100644 index 99fd1cf5e..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/EdgeDetection/SobelEdgeFilter.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The Sobel operator filter. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.EdgeDetection -{ - /// - /// The Sobel operator filter. - /// - /// - public class SobelEdgeFilter : I2DEdgeFilter - { - /// - /// Gets the horizontal gradient operator. - /// - public double[,] HorizontalGradientOperator - { - get - { - return new double[,] - { - { -1, 0, 1 }, - { -2, 0, 2 }, - { -1, 0, 1 } - }; - } - } - - /// - /// Gets the vertical gradient operator. - /// - public double[,] VerticalGradientOperator - { - get - { - return new double[,] - { - { 1, 2, 1 }, - { 0, 0, 0 }, - { -1, -2, -1 } - }; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Class1.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Class1.cs deleted file mode 100644 index 6597c73c8..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Class1.cs +++ /dev/null @@ -1,338 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] - public partial class opencv_storage - { - - private opencv_storageCascade cascadeField; - - /// - public opencv_storageCascade cascade - { - get - { - return this.cascadeField; - } - set - { - this.cascadeField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - public partial class opencv_storageCascade - { - - private string stageTypeField; - - private string featureTypeField; - - private byte heightField; - - private byte widthField; - - private opencv_storageCascadeStageParams stageParamsField; - - private opencv_storageCascadeFeatureParams featureParamsField; - - private byte stageNumField; - - private opencv_storageCascade_[] stagesField; - - private opencv_storageCascade_2[] featuresField; - - private string type_idField; - - /// - public string stageType - { - get - { - return this.stageTypeField; - } - set - { - this.stageTypeField = value; - } - } - - /// - public string featureType - { - get - { - return this.featureTypeField; - } - set - { - this.featureTypeField = value; - } - } - - /// - public byte height - { - get - { - return this.heightField; - } - set - { - this.heightField = value; - } - } - - /// - public byte width - { - get - { - return this.widthField; - } - set - { - this.widthField = value; - } - } - - /// - public opencv_storageCascadeStageParams stageParams - { - get - { - return this.stageParamsField; - } - set - { - this.stageParamsField = value; - } - } - - /// - public opencv_storageCascadeFeatureParams featureParams - { - get - { - return this.featureParamsField; - } - set - { - this.featureParamsField = value; - } - } - - /// - public byte stageNum - { - get - { - return this.stageNumField; - } - set - { - this.stageNumField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("_", IsNullable = false)] - public opencv_storageCascade_[] stages - { - get - { - return this.stagesField; - } - set - { - this.stagesField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("_", IsNullable = false)] - public opencv_storageCascade_2[] features - { - get - { - return this.featuresField; - } - set - { - this.featuresField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string type_id - { - get - { - return this.type_idField; - } - set - { - this.type_idField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - public partial class opencv_storageCascadeStageParams - { - - private byte maxWeakCountField; - - /// - public byte maxWeakCount - { - get - { - return this.maxWeakCountField; - } - set - { - this.maxWeakCountField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - public partial class opencv_storageCascadeFeatureParams - { - - private byte maxCatCountField; - - /// - public byte maxCatCount - { - get - { - return this.maxCatCountField; - } - set - { - this.maxCatCountField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - public partial class opencv_storageCascade_ - { - - private byte maxWeakCountField; - - private double stageThresholdField; - - private opencv_storageCascade__[] weakClassifiersField; - - /// - public byte maxWeakCount - { - get - { - return this.maxWeakCountField; - } - set - { - this.maxWeakCountField = value; - } - } - - /// - public double stageThreshold - { - get - { - return this.stageThresholdField; - } - set - { - this.stageThresholdField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("_", IsNullable = false)] - public opencv_storageCascade__[] weakClassifiers - { - get - { - return this.weakClassifiersField; - } - set - { - this.weakClassifiersField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - public partial class opencv_storageCascade__ - { - - private string internalNodesField; - - private string leafValuesField; - - /// - public string internalNodes - { - get - { - return this.internalNodesField; - } - set - { - this.internalNodesField = value; - } - } - - /// - public string leafValues - { - get - { - return this.leafValuesField; - } - set - { - this.leafValuesField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] - public partial class opencv_storageCascade_2 - { - - private string[] rectsField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("_", IsNullable = false)] - public string[] rects - { - get - { - return this.rectsField; - } - set - { - this.rectsField = value; - } - } - } - - -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/EmbeddedHaarCascades.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/EmbeddedHaarCascades.cs deleted file mode 100644 index d59a6417d..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/EmbeddedHaarCascades.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System.IO; - using System.Reflection; - - using ImageProcessor.Common.Extensions; - - public static class EmbeddedHaarCascades - { - private static HaarCascade frontFaceDefault; - - public static HaarCascade FrontFaceDefault - { - get - { - return frontFaceDefault ?? (frontFaceDefault = GetCascadeFromResource("haarcascade_frontalface_legacy.xml")); - } - } - - private static HaarCascade GetCascadeFromResource(string identifier) - { - HaarCascade cascade; - var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("ImageProcessor.Imaging.Filters.ObjectDetection.Resources." + identifier); - - //using (StringReader stringReader = new StringReader(resource)) - //{ - cascade = HaarCascade.FromXml(resource); - //} - - return cascade; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/GroupMatching.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/GroupMatching.cs deleted file mode 100644 index 9cb79cc3c..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/GroupMatching.cs +++ /dev/null @@ -1,239 +0,0 @@ -// Accord Vision Library -// The Accord.NET Framework -// http://accord-framework.net -// -// Copyright © César Souza, 2009-2015 -// cesarsouza at gmail.com -// -// This code has been submitted as an user contribution by darko.juric2 -// GCode Issue #12 https://code.google.com/p/accord/issues/detail?id=12 -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// - -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Collections.Generic; - - /// - /// Group matching algorithm for detection region averaging. - /// - /// - /// - /// This class can be seen as a post-processing filter. Its goal is to - /// group near or contained regions together in order to produce more - /// robust and smooth estimates of the detected regions. - /// - /// - public abstract class GroupMatching - { - - private int classCount; - private int minNeighbors; - - private int[] labels; - private int[] equals; - - private List filter; - - /// - /// Creates a new object. - /// - /// - /// - /// The minimum number of neighbors needed to keep a detection. If a rectangle - /// has less than this minimum number, it will be discarded as a false positive. - /// - protected GroupMatching(int minimumNeighbors = 2) - { - this.minNeighbors = minimumNeighbors; - this.filter = new List(); - } - - /// - /// Gets or sets the minimum number of neighbors necessary to keep a detection. - /// If a rectangle has less neighbors than this number, it will be discarded as - /// a false positive. - /// - /// - public int MinimumNeighbors - { - get { return minNeighbors; } - set - { - if (minNeighbors < 0) - throw new ArgumentOutOfRangeException("value", "Value must be equal to or higher than zero."); - minNeighbors = value; - } - } - - /// - /// Gets how many classes were found in the - /// last call to . - /// - /// - public int Classes - { - get { return classCount; } - } - - /// - /// Groups possibly near rectangles into a smaller - /// set of distinct and averaged rectangles. - /// - /// - /// The rectangles to group. - /// - public T[] Group(T[] shapes) - { - // Start by classifying rectangles according to distance - classify(shapes); // assign label for near rectangles - - int[] neighborCount; - - // Average the rectangles contained in each labeled group - T[] output = Average(labels, shapes, out neighborCount); - - // Check suppression - if (minNeighbors > 0) - { - filter.Clear(); - - // Discard weak rectangles which don't have enough neighbors - for (int i = 0; i < output.Length; i++) - if (neighborCount[i] >= minNeighbors) filter.Add(output[i]); - - return filter.ToArray(); - } - - return output; - } - - - - /// - /// Detects rectangles which are near and - /// assigns similar class labels accordingly. - /// - /// - private void classify(T[] shapes) - { - equals = new int[shapes.Length]; - for (int i = 0; i < equals.Length; i++) - equals[i] = -1; - - labels = new int[shapes.Length]; - for (int i = 0; i < labels.Length; i++) - labels[i] = i; - - classCount = 0; - - // If two rectangles are near, or contained in - // each other, merge then in a single rectangle - for (int i = 0; i < shapes.Length - 1; i++) - { - for (int j = i + 1; j < shapes.Length; j++) - { - if (Near(shapes[i], shapes[j])) - merge(labels[i], labels[j]); - } - } - - // Count the number of classes and centroids - int[] centroids = new int[shapes.Length]; - for (int i = 0; i < centroids.Length; i++) - if (equals[i] == -1) centroids[i] = classCount++; - - // Classify all rectangles with their labels - for (int i = 0; i < shapes.Length; i++) - { - int root = labels[i]; - while (equals[root] != -1) - root = equals[root]; - - labels[i] = centroids[root]; - } - } - - /// - /// Merges two labels. - /// - /// - private void merge(int label1, int label2) - { - int root1 = label1; - int root2 = label2; - - // Get the roots associated with the two labels - while (equals[root1] != -1) root1 = equals[root1]; - while (equals[root2] != -1) root2 = equals[root2]; - - if (root1 == root2) // labels are already connected - return; - - int minRoot, maxRoot; - int labelWithMinRoot, labelWithMaxRoot; - - if (root1 > root2) - { - maxRoot = root1; - minRoot = root2; - - labelWithMaxRoot = label1; - labelWithMinRoot = label2; - } - else - { - maxRoot = root2; - minRoot = root1; - - labelWithMaxRoot = label2; - labelWithMinRoot = label1; - } - - equals[maxRoot] = minRoot; - - for (int root = maxRoot + 1; root <= labelWithMaxRoot; root++) - { - if (equals[root] == maxRoot) - equals[root] = minRoot; - } - } - - /// - /// When overridden in a child class, should compute - /// whether two given shapes are near. Definition of - /// near is up to the implementation. - /// - /// - /// True if the two shapes are near; false otherwise. - /// - protected abstract bool Near(T shape1, T shape2); - - /// - /// When overridden in a child class, should compute - /// an average of the shapes given as parameters. - /// - /// - /// The label of each shape. - /// The shapes themselves. - /// Should return how many neighbors each shape had. - /// - /// The averaged shapes found in the given parameters. - /// - protected abstract T[] Average(int[] labels, T[] shapes, out int[] neighborCounts); - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascade.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascade.cs deleted file mode 100644 index 1d0ff06df..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascade.cs +++ /dev/null @@ -1,243 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Globalization; - using System.IO; - using System.Xml; - using System.Xml.Serialization; - - /// - /// Cascade of Haar-like features' weak classification stages. - /// - /// - /// - /// - /// The Viola-Jones object detection framework is the first object detection framework - /// to provide competitive object detection rates in real-time proposed in 2001 by Paul - /// Viola and Michael Jones. Although it can be trained to detect a variety of object - /// classes, it was motivated primarily by the problem of face detection. - /// - /// - /// The implementation of this code has used Viola and Jones' original publication, the - /// OpenCV Library and the Marilena Project as reference. OpenCV is released under a BSD - /// license, it is free for both academic and commercial use. Please be aware that some - /// particular versions of the Haar object detection framework are patented by Viola and - /// Jones and may be subject to restrictions for use in commercial applications. - /// - /// - /// References: - /// - /// - /// - /// Viola, P. and Jones, M. (2001). Rapid Object Detection using a Boosted Cascade - /// of Simple Features. - /// - /// - /// Wikipedia, The Free Encyclopedia. Viola-Jones object detection framework - /// - /// - /// - /// - /// - /// - /// To load an OpenCV-compatible XML definition for a Haar cascade, you can use HaarCascade's - /// FromXml static method. An example would be: - /// - /// String path = @"C:\Users\haarcascade-frontalface_alt2.xml"; - /// HaarCascade cascade1 = HaarCascade.FromXml(path); - /// - /// - /// - /// After the cascade has been loaded, it is possible to create a new - /// using the cascade. Please see for more details. It is also - /// possible to generate embeddable C# definitions from a cascade, avoiding the need to load - /// XML files on program startup. Please see method or - /// class for details. - /// - /// - [Serializable] - public class HaarCascade : ICloneable - { - /// - /// Gets the stages' base width. - /// - /// - public int Width { get; protected set; } - - /// - /// Gets the stages' base height. - /// - /// - public int Height { get; protected set; } - - /// - /// Gets the classification stages. - /// - /// - public HaarCascadeStage[] Stages { get; protected set; } - - /// - /// Gets a value indicating whether this cascade has tilted features. - /// - /// - /// - /// true if this cascade has tilted features; otherwise, false. - /// - /// - public bool HasTiltedFeatures { get; protected set; } - - /// - /// Constructs a new Haar Cascade. - /// - /// - /// Base feature width. - /// Base feature height. - /// Haar-like features classification stages. - /// - public HaarCascade(int baseWidth, int baseHeight, HaarCascadeStage[] stages) - { - Width = baseWidth; - Height = baseHeight; - Stages = stages; - - // check if the classifier has tilted features - HasTiltedFeatures = checkTiltedFeatures(stages); - } - - /// - /// Constructs a new Haar Cascade. - /// - /// - /// Base feature width. - /// Base feature height. - /// - protected HaarCascade(int baseWidth, int baseHeight) - { - Width = baseWidth; - Height = baseHeight; - } - - - /// - /// Checks if the classifier contains tilted (rotated) features - /// - /// - private static bool checkTiltedFeatures(HaarCascadeStage[] stages) - { - foreach (var stage in stages) - foreach (var tree in stage.Trees) - foreach (var node in tree) - if (node.Feature.Tilted == true) - return true; - return false; - } - - /// - /// Creates a new object that is a copy of the current instance. - /// - /// - /// - /// A new object that is a copy of this instance. - /// - /// - public object Clone() - { - HaarCascadeStage[] newStages = new HaarCascadeStage[Stages.Length]; - for (int i = 0; i < newStages.Length; i++) - newStages[i] = (HaarCascadeStage)Stages[i].Clone(); - - HaarCascade r = new HaarCascade(Width, Height); - r.HasTiltedFeatures = this.HasTiltedFeatures; - r.Stages = newStages; - - return r; - } - - - /// - /// Loads a HaarCascade from a OpenCV-compatible XML file. - /// - /// - /// - /// A containing the file stream - /// for the xml definition of the classifier to be loaded. - /// - /// The HaarCascadeClassifier loaded from the file. - /// - public static HaarCascade FromXml(Stream stream) - { - return FromXml(new StreamReader(stream)); - } - - /// - /// Loads a HaarCascade from a OpenCV-compatible XML file. - /// - /// - /// - /// The file path for the xml definition of the classifier to be loaded. - /// - /// The HaarCascadeClassifier loaded from the file. - /// - public static HaarCascade FromXml(string path) - { - return FromXml(new StreamReader(path)); - } - - /// - /// Loads a HaarCascade from a OpenCV-compatible XML file. - /// - /// - /// - /// A containing the file stream - /// for the xml definition of the classifier to be loaded. - /// - /// The HaarCascadeClassifier loaded from the file. - /// - public static HaarCascade FromXml(TextReader stringReader) - { - XmlTextReader xmlReader = new XmlTextReader(stringReader); - - // Gathers the base window size - xmlReader.ReadToFollowing("size"); - string size = xmlReader.ReadElementContentAsString(); - //xmlReader.ReadToFollowing("height"); - //int baseHeight = int.Parse(xmlReader.ReadElementContentAsString().Trim(), CultureInfo.InvariantCulture); - - //xmlReader.ReadToFollowing("width"); - //int baseWidth = int.Parse(xmlReader.ReadElementContentAsString().Trim(), CultureInfo.InvariantCulture); - - - // Proceeds to load the cascade stages - xmlReader.ReadToFollowing("stages"); - XmlSerializer serializer = new XmlSerializer(typeof(HaarCascadeSerializationObject)); - var stages = (HaarCascadeSerializationObject)serializer.Deserialize(xmlReader); - - // Process base window size - string[] s = size.Trim().Split(' '); - int baseWidth = int.Parse(s[0], CultureInfo.InvariantCulture); - int baseHeight = int.Parse(s[1], CultureInfo.InvariantCulture); - - // Create and return the new cascade - return new HaarCascade(baseWidth, baseHeight, stages.Stages); - } - - /// - /// Saves a HaarCascade to C# code. - /// - /// - public void ToCode(string path, string className) - { - ToCode(new StreamWriter(path), className); - } - - /// - /// Saves a HaarCascade to C# code. - /// - /// - public void ToCode(TextWriter textWriter, string className) - { - new HaarCascadeWriter(textWriter).Write(this, className); - } - - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeSerializationObject.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeSerializationObject.cs deleted file mode 100644 index 765bae6bd..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeSerializationObject.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Xml.Serialization; - - /// - /// Haar Cascade Serialization Root. This class is used - /// only for XML serialization/deserialization. - /// - /// - [Serializable] - [XmlRoot(Namespace = "", IsNullable = false, ElementName = "stages")] - public class HaarCascadeSerializationObject - { - /// - /// The stages retrieved after deserialization. - /// - [XmlElement("_")] - public HaarCascadeStage[] Stages { get; set; } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeStage.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeStage.cs deleted file mode 100644 index a9d51dbbc..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeStage.cs +++ /dev/null @@ -1,168 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Xml.Serialization; - - /// - /// Haar Cascade Classifier Stage. - /// - /// - /// - /// A Haar Cascade Classifier is composed of several stages. Each stage - /// contains a set of classifier trees used in the decision process. - /// - /// - [Serializable] - [XmlRoot("_")] - public class HaarCascadeStage : ICloneable - { - /// - /// Gets or sets the feature trees and its respective - /// feature tree nodes which compose this stage. - /// - /// - [XmlArray("trees")] - [XmlArrayItem("_")] - [XmlArrayItem("_", NestingLevel = 1)] - public HaarFeatureNode[][] Trees { get; set; } - - /// - /// Gets or sets the threshold associated with this stage, - /// i.e. the minimum value the classifiers should output - /// to decide if the image contains the object or not. - /// - /// - [XmlElement("stage_threshold")] - public double Threshold { get; set; } - - /// - /// Gets the index of the parent stage from this stage. - /// - /// - [XmlElement("parent")] - public int ParentIndex { get; set; } - - /// - /// Gets the index of the next stage from this stage. - /// - /// - [XmlElement("next")] - public int NextIndex { get; set; } - - /// - /// Constructs a new Haar Cascade Stage. - /// - /// - public HaarCascadeStage() - { - } - - /// - /// Constructs a new Haar Cascade Stage. - /// - /// - public HaarCascadeStage(double threshold) - { - this.Threshold = threshold; - } - - /// - /// Constructs a new Haar Cascade Stage. - /// - /// - public HaarCascadeStage(double threshold, int parentIndex, int nextIndex) - { - this.Threshold = threshold; - this.ParentIndex = parentIndex; - this.NextIndex = nextIndex; - } - - /// - /// Classifies an image as having the searched object or not. - /// - /// - public bool Classify(FastBitmap image, int x, int y, double factor) - { - double value = 0; - - // For each feature in the feature tree of the current stage, - foreach (HaarFeatureNode[] tree in Trees) - { - int current = 0; - - do - { - // Get the feature node from the tree - HaarFeatureNode node = tree[current]; - - // Evaluate the node's feature - double sum = node.Feature.GetSum(image, x, y); - - // And increase the value accumulator - if (sum < node.Threshold * factor) - { - value += node.LeftValue; - current = node.LeftNodeIndex; - } - else - { - value += node.RightValue; - current = node.RightNodeIndex; - } - - } while (current > 0); - - // Stop early if we have already surpassed the stage threshold value. - //if (value > this.Threshold) return true; - } - - // After we have evaluated the output for the - // current stage, we will check if the value - // is still lesser than the stage threshold. - if (value < this.Threshold) - { - // If it is, the stage has rejected the current - // image and it doesn't contains our object. - return false; - } - else - { - // The stage has accepted the current image - return true; - } - } - - - /// - /// Creates a new object that is a copy of the current instance. - /// - /// - /// - /// A new object that is a copy of this instance. - /// - /// - public object Clone() - { - HaarFeatureNode[][] newTrees = new HaarFeatureNode[Trees.Length][]; - - for (int i = 0; i < newTrees.Length; i++) - { - HaarFeatureNode[] tree = Trees[i]; - HaarFeatureNode[] newTree = newTrees[i] = - new HaarFeatureNode[tree.Length]; - - for (int j = 0; j < newTree.Length; j++) - newTree[j] = (HaarFeatureNode)tree[j].Clone(); - } - - HaarCascadeStage r = new HaarCascadeStage(); - r.NextIndex = NextIndex; - r.ParentIndex = ParentIndex; - r.Threshold = Threshold; - r.Trees = newTrees; - - return r; - } - - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeWriter.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeWriter.cs deleted file mode 100644 index ef3f76bac..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarCascadeWriter.cs +++ /dev/null @@ -1,154 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Globalization; - using System.IO; - - /// - /// Automatic transcriber for Haar cascades. - /// - /// - /// - /// This class can be used to generate code-only definitions for Haar cascades, - /// avoiding the need for loading and parsing XML files during application startup. - /// This class generates C# code for a class inheriting from - /// which may be used to create a . - /// - /// - public class HaarCascadeWriter - { - private TextWriter writer; - - /// - /// Constructs a new class. - /// - /// The stream to write to. - /// - public HaarCascadeWriter(TextWriter stream) - { - this.writer = stream; - } - - /// - /// Writes the specified cascade. - /// - /// The cascade to write. - /// The name for the generated class. - /// - public void Write(HaarCascade cascade, string className) - { - for (int i = 0; i < cascade.Stages.Length; i++) - for (int j = 0; j < cascade.Stages[i].Trees.Length; j++) - if (cascade.Stages[i].Trees[j].Length != 1) - throw new ArgumentException("Only cascades with single node trees are currently supported."); - - - writer.WriteLine("// This file has been automatically transcribed by the"); - writer.WriteLine("//"); - writer.WriteLine("// Accord Vision Library"); - writer.WriteLine("// The Accord.NET Framework"); - writer.WriteLine("// http://accord-framework.net"); - writer.WriteLine("//"); - writer.WriteLine(); - writer.WriteLine("namespace HaarCascades"); - writer.WriteLine("{"); - writer.WriteLine(" using System.CodeDom.Compiler;"); - writer.WriteLine(" using System.Collections.Generic;"); - writer.WriteLine(); - writer.WriteLine(" /// "); - writer.WriteLine(" /// Automatically generated haar-cascade definition"); - writer.WriteLine(" /// to use with the Accord.NET Framework object detectors."); - writer.WriteLine(" /// "); - writer.WriteLine(" /// "); - writer.WriteLine(" [GeneratedCode(\"Accord.NET HaarCascadeWriter\", \"2.7\")]"); - writer.WriteLine(" public class {0} : Accord.Vision.Detection.HaarCascade", className); - writer.WriteLine(" {"); - writer.WriteLine(); - writer.WriteLine(" /// "); - writer.WriteLine(" /// Automatically generated transcription"); - writer.WriteLine(" /// "); - writer.WriteLine(" public {0}()", className); - writer.WriteLine(" : base({0}, {1})", cascade.Width, cascade.Height); - writer.WriteLine(" {"); - writer.WriteLine(" List stages = new List();"); - writer.WriteLine(" List nodes;"); - writer.WriteLine(" HaarCascadeStage stage;"); - writer.WriteLine(); - - if (cascade.HasTiltedFeatures) - { - writer.WriteLine(" HasTiltedFeatures = true;"); - writer.WriteLine(); - } - - // Write cascade stages - for (int i = 0; i < cascade.Stages.Length; i++) - writeStage(i, cascade.Stages[i]); - - writer.WriteLine(); - writer.WriteLine(" Stages = stages.ToArray();"); - writer.WriteLine(" }"); - writer.WriteLine(" }"); - writer.WriteLine("}"); - } - - private void writeStage(int i, HaarCascadeStage stage) - { - writer.WriteLine(" #region Stage {0}", i); - writer.WriteLine(" stage = new HaarCascadeStage({0}, {1}, {2}); nodes = new List();", - stage.Threshold.ToString("R", NumberFormatInfo.InvariantInfo), - stage.ParentIndex, stage.NextIndex); - - // Write stage trees - for (int j = 0; j < stage.Trees.Length; j++) - writeTrees(stage, j); - - writer.WriteLine(" stage.Trees = nodes.ToArray(); stages.Add(stage);"); - writer.WriteLine(" #endregion"); - writer.WriteLine(); - } - - private void writeTrees(HaarCascadeStage stage, int j) - { - writer.Write(" nodes.Add(new[] { "); - - // Assume trees have single node - writeFeature(stage.Trees[j][0]); - - writer.WriteLine(" });"); - } - - private void writeFeature(HaarFeatureNode node) - { - - writer.Write("new HaarFeatureNode({0}, {1}, {2}, ", - node.Threshold.ToString("R", NumberFormatInfo.InvariantInfo), - node.LeftValue.ToString("R", NumberFormatInfo.InvariantInfo), - node.RightValue.ToString("R", NumberFormatInfo.InvariantInfo)); - - if (node.Feature.Tilted) - writer.Write("true, "); - - // Write Haar-like rectangular features - for (int k = 0; k < node.Feature.Rectangles.Length; k++) - { - writeRectangle(node.Feature.Rectangles[k]); - - if (k < node.Feature.Rectangles.Length - 1) - writer.Write(", "); - } - - writer.Write(" )"); - } - - private void writeRectangle(HaarRectangle rectangle) - { - writer.Write("new int[] {{ {0}, {1}, {2}, {3}, {4} }}", - rectangle.X.ToString(NumberFormatInfo.InvariantInfo), - rectangle.Y.ToString(NumberFormatInfo.InvariantInfo), - rectangle.Width.ToString(NumberFormatInfo.InvariantInfo), - rectangle.Height.ToString(NumberFormatInfo.InvariantInfo), - rectangle.Weight.ToString("R", NumberFormatInfo.InvariantInfo)); - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarClassifier.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarClassifier.cs deleted file mode 100644 index e5e3b056a..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarClassifier.cs +++ /dev/null @@ -1,175 +0,0 @@ -// Accord Vision Library -// The Accord.NET Framework (LGPL) -// http://accord-framework.net -// -// Copyright © César Souza, 2009-2015 -// cesarsouza at gmail.com -// -// Copyright © Masakazu Ohtsuka, 2008 -// This work is partially based on the original Project Marilena code, -// distributed under a 2-clause BSD License. Details are listed below. -// -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// - -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Drawing; - - /// - /// Strong classifier based on a weaker cascade of - /// classifiers using Haar-like rectangular features. - /// - /// - /// - /// - /// The Viola-Jones object detection framework is the first object detection framework - /// to provide competitive object detection rates in real-time proposed in 2001 by Paul - /// Viola and Michael Jones. Although it can be trained to detect a variety of object - /// classes, it was motivated primarily by the problem of face detection. - /// - /// - /// The implementation of this code has used Viola and Jones' original publication, the - /// OpenCV Library and the Marilena Project as reference. OpenCV is released under a BSD - /// license, it is free for both academic and commercial use. Please be aware that some - /// particular versions of the Haar object detection framework are patented by Viola and - /// Jones and may be subject to restrictions for use in commercial applications. The code - /// has been implemented with full support for tilted Haar features. - /// - /// - /// References: - /// - /// - /// - /// Viola, P. and Jones, M. (2001). Rapid Object Detection using a Boosted Cascade - /// of Simple Features. - /// - /// - /// http://en.wikipedia.org/wiki/Viola-Jones_object_detection_framework - /// - /// - /// - /// - /// - [Serializable] - public class HaarClassifier - { - private HaarCascade cascade; - - private float invArea; - private float scale; - - - /// - /// Constructs a new classifier. - /// - /// - public HaarClassifier(HaarCascade cascade) - { - this.cascade = cascade; - } - - /// - /// Constructs a new classifier. - /// - /// - public HaarClassifier(int baseWidth, int baseHeight, HaarCascadeStage[] stages) - : this(new HaarCascade(baseWidth, baseHeight, stages)) { } - - - /// - /// Gets the cascade of weak-classifiers - /// used by this strong classifier. - /// - /// - public HaarCascade Cascade - { - get { return cascade; } - } - - /// - /// Gets or sets the scale of the search window - /// being currently used by the classifier. - /// - /// - public float Scale - { - get { return this.scale; } - set - { - if (this.scale == value) - return; - - this.scale = value; - this.invArea = 1f / (cascade.Width * cascade.Height * scale * scale); - - // For each stage in the cascade - foreach (HaarCascadeStage stage in cascade.Stages) - { - // For each tree in the cascade - foreach (HaarFeatureNode[] tree in stage.Trees) - { - // For each feature node in the tree - foreach (HaarFeatureNode node in tree) - { - // Set the scale and weight for the node feature - node.Feature.SetScaleAndWeight(value, invArea); - } - } - } - } - } - - - /// - /// Detects the presence of an object in a given window. - /// - public bool Compute(FastBitmap image, Rectangle rectangle) - { - int x = rectangle.X; - int y = rectangle.Y; - int w = rectangle.Width; - int h = rectangle.Height; - - double mean = image.GetSum(x, y, w, h) * invArea; - double var = image.GetSum2(x, y, w, h) * invArea - (mean * mean); - - double sdev = (var >= 0) ? Math.Sqrt(var) : 1; - - // For each classification stage in the cascade - foreach (HaarCascadeStage stage in cascade.Stages) - { - // Check if the stage has rejected the image - if (stage.Classify(image, x, y, sdev) == false) - { - return false; // The image has been rejected. - } - } - - // If the object has gone all stages and has not - // been rejected, the object has been detected. - return true; // The image has been detected. - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarFeature.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarFeature.cs deleted file mode 100644 index 09e33b0cf..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarFeature.cs +++ /dev/null @@ -1,223 +0,0 @@ -// Accord Vision Library -// The Accord.NET Framework (LGPL) -// http://accord-framework.net -// -// Copyright © César Souza, 2009-2015 -// cesarsouza at gmail.com -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// - -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Collections.Generic; - using System.Xml; - using System.Xml.Schema; - using System.Xml.Serialization; - - /// - /// Rectangular Haar-like feature container. - /// - /// - /// References: - /// - http://en.wikipedia.org/wiki/Haar-like_features#Rectangular_Haar-like_features - /// - [Serializable] - public sealed class HaarFeature : IXmlSerializable, ICloneable - { - /// - /// Gets or sets whether this feature is tilted. - /// - /// - public bool Tilted { get; set; } - - /// - /// Gets or sets the Haar rectangles for this feature. - /// - /// - public HaarRectangle[] Rectangles { get; set; } - - - /// - /// Constructs a new Haar-like feature. - /// - /// - public HaarFeature() - { - this.Rectangles = new HaarRectangle[2]; - } - - /// - /// Constructs a new Haar-like feature. - /// - /// - public HaarFeature(params HaarRectangle[] rectangles) - { - this.Rectangles = rectangles; - } - - /// - /// Constructs a new Haar-like feature. - /// - /// - public HaarFeature(params int[][] rectangles) - : this(false, rectangles) { } - - /// - /// Constructs a new Haar-like feature. - /// - /// - public HaarFeature(bool tilted, params int[][] rectangles) - { - this.Tilted = tilted; - this.Rectangles = new HaarRectangle[rectangles.Length]; - for (int i = 0; i < rectangles.Length; i++) - this.Rectangles[i] = new HaarRectangle(rectangles[i]); - } - - /// - /// Gets the sum of the areas of the rectangular features in an integral image. - /// - /// The containing integral rectangle information. - /// The x coordinate. - /// The y coordinate. - /// - /// The representing the sum. - /// - public double GetSum(FastBitmap image, int x, int y) - { - double sum = 0.0; - - if (!Tilted) - { - // Compute the sum for a standard feature - foreach (HaarRectangle rect in Rectangles) - { - sum += image.GetSum(x + rect.ScaledX, y + rect.ScaledY, - rect.ScaledWidth, rect.ScaledHeight) * rect.ScaledWeight; - } - } - else - { - // Compute the sum for a rotated feature - foreach (HaarRectangle rect in Rectangles) - { - sum += image.GetSumT(x + rect.ScaledX, y + rect.ScaledY, - rect.ScaledWidth, rect.ScaledHeight) * rect.ScaledWeight; - } - } - - return sum; - } - - /// - /// Sets the scale and weight of a Haar-like rectangular feature container. - /// - /// - public void SetScaleAndWeight(float scale, float weight) - { - // Manual loop unfolding - if (Rectangles.Length == 2) - { - HaarRectangle a = Rectangles[0]; - HaarRectangle b = Rectangles[1]; - - b.ScaleRectangle(scale); - b.ScaleWeight(weight); - - a.ScaleRectangle(scale); - a.ScaledWeight = -(b.Area * b.ScaledWeight) / a.Area; - } - else // rectangles.Length == 3 - { - HaarRectangle a = Rectangles[0]; - HaarRectangle b = Rectangles[1]; - HaarRectangle c = Rectangles[2]; - - c.ScaleRectangle(scale); - c.ScaleWeight(weight); - - b.ScaleRectangle(scale); - b.ScaleWeight(weight); - - a.ScaleRectangle(scale); - a.ScaledWeight = -(b.Area * b.ScaledWeight - + c.Area * c.ScaledWeight) / (a.Area); - } - } - - - #region IXmlSerializable Members - - XmlSchema IXmlSerializable.GetSchema() - { - throw new NotSupportedException(); - } - - void IXmlSerializable.ReadXml(XmlReader reader) - { - reader.ReadStartElement("feature"); - - reader.ReadToFollowing("rects"); - reader.ReadToFollowing("_"); - - var rec = new List(); - while (reader.Name == "_") - { - string str = reader.ReadElementContentAsString(); - rec.Add(HaarRectangle.Parse(str)); - - while (reader.Name != "_" && reader.Name != "tilted" && - reader.NodeType != XmlNodeType.EndElement) - reader.Read(); - } - - Rectangles = rec.ToArray(); - - reader.ReadToFollowing("tilted", reader.BaseURI); - Tilted = reader.ReadElementContentAsInt() == 1; - - reader.ReadEndElement(); - } - - void IXmlSerializable.WriteXml(XmlWriter writer) - { - throw new NotSupportedException(); - } - - #endregion - - - - /// - /// Creates a new object that is a copy of the current instance. - /// - /// - /// A new object that is a copy of this instance. - /// - public object Clone() - { - HaarRectangle[] newRectangles = new HaarRectangle[this.Rectangles.Length]; - for (int i = 0; i < newRectangles.Length; i++) - { - HaarRectangle rect = Rectangles[i]; - newRectangles[i] = new HaarRectangle(rect.X, rect.Y, rect.Width, rect.Height, rect.Weight); - } - - return new HaarFeature { Rectangles = newRectangles, Tilted = this.Tilted }; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarFeatureNode.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarFeatureNode.cs deleted file mode 100644 index e81004f72..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarFeatureNode.cs +++ /dev/null @@ -1,122 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Xml.Serialization; - - /// - /// Haar Cascade Feature Tree Node. - /// - /// - /// - /// The Feature Node is a node belonging to a feature tree, - /// containing information about child nodes and an associated - /// . - /// - /// - [Serializable] - public class HaarFeatureNode : ICloneable - { - private int rightNodeIndex = -1; - private int leftNodeIndex = -1; - - /// - /// Gets the threshold for this feature. - /// - /// - [XmlElement("threshold")] - public double Threshold { get; set; } - - /// - /// Gets the left value for this feature. - /// - /// - [XmlElement("left_val")] - public double LeftValue { get; set; } - - /// - /// Gets the right value for this feature. - /// - /// - [XmlElement("right_val")] - public double RightValue { get; set; } - - /// - /// Gets the left node index for this feature. - /// - /// - [XmlElement("left_node")] - public int LeftNodeIndex - { - get { return leftNodeIndex; } - set { leftNodeIndex = value; } - } - - /// - /// Gets the right node index for this feature. - /// - /// - [XmlElement("right_node")] - public int RightNodeIndex - { - get { return rightNodeIndex; } - set { rightNodeIndex = value; } - } - - /// - /// Gets the feature associated with this node. - /// - /// - [XmlElement("feature", IsNullable = false)] - public HaarFeature Feature { get; set; } - - /// - /// Constructs a new feature tree node. - /// - public HaarFeatureNode() - { - } - - /// - /// Constructs a new feature tree node. - /// - /// - public HaarFeatureNode(double threshold, double leftValue, double rightValue, params int[][] rectangles) - : this(threshold, leftValue, rightValue, false, rectangles) { } - - /// - /// Constructs a new feature tree node. - /// - /// - public HaarFeatureNode(double threshold, double leftValue, double rightValue, bool tilted, params int[][] rectangles) - { - this.Feature = new HaarFeature(tilted, rectangles); - this.Threshold = threshold; - this.LeftValue = leftValue; - this.RightValue = rightValue; - } - - - /// - /// Creates a new object that is a copy of the current instance. - /// - /// - /// A new object that is a copy of this instance. - /// - /// - public object Clone() - { - HaarFeatureNode r = new HaarFeatureNode(); - - r.Feature = (HaarFeature)Feature.Clone(); - r.Threshold = Threshold; - - r.RightValue = RightValue; - r.LeftValue = LeftValue; - - r.LeftNodeIndex = leftNodeIndex; - r.RightNodeIndex = rightNodeIndex; - - return r; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarRectangle.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarRectangle.cs deleted file mode 100644 index dd4889884..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarCascade/HaarRectangle.cs +++ /dev/null @@ -1,203 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents a rectangle which can be at any position and scale within the original image. -// Based on original code found in the Accord Framework at -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Globalization; - - /// - /// Represents a rectangle which can be at any position and scale within the original image. - /// Based on original code found in the Accord Framework at - /// - [Serializable] - public class HaarRectangle : ICloneable - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The values for this rectangle. - /// - public HaarRectangle(int[] values) - { - this.X = values[0]; - this.Y = values[1]; - this.Width = values[2]; - this.Height = values[3]; - this.Weight = values[4]; - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The x coordinate marking the top-left point to apply to this rectangle. - /// - /// - /// The y coordinate marking the top-left point to apply to this rectangle. - /// - /// - /// The width to apply to this rectangle. - /// - /// - /// The height to apply to this rectangle. - /// - /// - /// The weight to apply to this rectangle. - /// - public HaarRectangle(int x, int y, int width, int height, float weight) - { - this.X = x; - this.Y = y; - this.Width = width; - this.Height = height; - this.Weight = weight; - } - - /// - /// Prevents a default instance of the class from being created. - /// - private HaarRectangle() - { - } - - /// - /// Gets or sets the x-coordinate of this Haar feature rectangle. - /// - public int X { get; set; } - - /// - /// Gets or sets the y-coordinate of this Haar feature rectangle. - /// - public int Y { get; set; } - - /// - /// Gets or sets the width of this Haar feature rectangle. - /// - public int Width { get; set; } - - /// - /// Gets or sets the height of this Haar feature rectangle. - /// - public int Height { get; set; } - - /// - /// Gets or sets the weight of this Haar feature rectangle. - /// - public float Weight { get; set; } - - /// - /// Gets or sets the scaled x-coordinate of this Haar feature rectangle. - /// - public int ScaledX { get; set; } - - /// - /// Gets or sets the scaled y-coordinate of this Haar feature rectangle. - /// - public int ScaledY { get; set; } - - /// - /// Gets or sets the scaled width of this Haar feature rectangle. - /// - public int ScaledWidth { get; set; } - - /// - /// Gets or sets the scaled height of this Haar feature rectangle. - /// - public int ScaledHeight { get; set; } - - /// - /// Gets or sets the scaled weight of this Haar feature rectangle. - /// - public float ScaledWeight { get; set; } - - /// - /// Gets the area of this rectangle. - /// - public int Area - { - get { return this.ScaledWidth * this.ScaledHeight; } - } - - /// - /// Converts a from a string representation. - /// - /// - /// The value to parse. - /// - /// - /// The . - /// - public static HaarRectangle Parse(string value) - { - string[] values = value.Trim().Split(' '); - - int x = int.Parse(values[0], CultureInfo.InvariantCulture); - int y = int.Parse(values[1], CultureInfo.InvariantCulture); - int w = int.Parse(values[2], CultureInfo.InvariantCulture); - int h = int.Parse(values[3], CultureInfo.InvariantCulture); - float weight = float.Parse(values[4], CultureInfo.InvariantCulture); - - return new HaarRectangle(x, y, w, h, weight); - } - - /// - /// Scales the values of this rectangle. - /// - /// - /// The scale. - /// - public void ScaleRectangle(float scale) - { - this.ScaledX = (int)(this.X * scale); - this.ScaledY = (int)(this.Y * scale); - this.ScaledWidth = (int)(this.Width * scale); - this.ScaledHeight = (int)(this.Height * scale); - } - - /// - /// Scales the weight of this rectangle. - /// - /// - /// The scale. - /// - public void ScaleWeight(float scale) - { - this.ScaledWeight = this.Weight * scale; - } - - /// - /// Creates a new object that is a copy of the current instance. - /// - /// - /// A new object that is a copy of this instance. - /// - public object Clone() - { - HaarRectangle r = new HaarRectangle - { - Height = this.Height, - ScaledHeight = this.ScaledHeight, - ScaledWeight = this.ScaledWeight, - ScaledWidth = this.ScaledWidth, - ScaledX = this.ScaledX, - ScaledY = this.ScaledY, - Weight = this.Weight, - Width = this.Width, - X = this.X, - Y = this.Y - }; - - return r; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarObjectDetector.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarObjectDetector.cs deleted file mode 100644 index 674495d1c..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/HaarObjectDetector.cs +++ /dev/null @@ -1,594 +0,0 @@ -// Accord Vision Library -// The Accord.NET Framework (LGPL) -// http://accord-framework.net -// -// Copyright © César Souza, 2009-2015 -// cesarsouza at gmail.com -// -// Copyright © Masakazu Ohtsuka, 2008 -// This work is partially based on the original Project Marilena code, -// distributed under a 2-clause BSD License. Details are listed below. -// -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// - -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - using System.Threading.Tasks; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging.Colors; - - /// - /// Viola-Jones Object Detector based on Haar-like features. - /// - /// - /// - /// - /// The Viola-Jones object detection framework is the first object detection framework - /// to provide competitive object detection rates in real-time proposed in 2001 by Paul - /// Viola and Michael Jones. Although it can be trained to detect a variety of object - /// classes, it was motivated primarily by the problem of face detection. - /// - /// - /// The implementation of this code has used Viola and Jones' original publication, the - /// OpenCV Library and the Marilena Project as reference. OpenCV is released under a BSD - /// license, it is free for both academic and commercial use. Please be aware that some - /// particular versions of the Haar object detection framework are patented by Viola and - /// Jones and may be subject to restrictions for use in commercial applications. The code - /// has been implemented with full support for tilted Haar features from the ground up. - /// - /// - /// References: - /// - /// - /// - /// Viola, P. and Jones, M. (2001). Rapid Object Detection using a Boosted Cascade - /// of Simple Features. - /// - /// - /// http://en.wikipedia.org/wiki/Viola-Jones_object_detection_framework - /// - /// - /// - /// - /// - public class HaarObjectDetector - { - - private List detectedObjects; - private HaarClassifier classifier; - - private ObjectDetectorSearchMode searchMode = ObjectDetectorSearchMode.NoOverlap; - private ObjectDetectorScalingMode scalingMode = ObjectDetectorScalingMode.GreaterToSmaller; - - // TODO: Support ROI - // private Rectangle searchWindow; - - private Size minSize = new Size(15, 15); - private Size maxSize = new Size(500, 500); - private float factor = 1.2f; - // private int channel = new Color32().R; - - private Rectangle[] lastObjects; - private int steadyThreshold = 2; - - private int baseWidth; - private int baseHeight; - - private int lastWidth; - private int lastHeight; - private float[] steps; - - private RectangleGroupMatching match; - - #region Constructors - - /// - /// Constructs a new Haar object detector. - /// - /// - /// - /// The to use in the detector's classifier. - /// For the default face cascade, please take a look on - /// . - /// - /// - public HaarObjectDetector(HaarCascade cascade) - : this(cascade, 15) { } - - /// - /// Constructs a new Haar object detector. - /// - /// - /// - /// The to use in the detector's classifier. - /// For the default face cascade, please take a look on - /// . - /// - /// Minimum window size to consider when searching for - /// objects. Default value is 15. - /// - public HaarObjectDetector(HaarCascade cascade, int minSize) - : this(cascade, minSize, ObjectDetectorSearchMode.NoOverlap) { } - - /// - /// Constructs a new Haar object detector. - /// - /// - /// - /// The to use in the detector's classifier. - /// For the default face cascade, please take a look on - /// . - /// - /// - /// Minimum window size to consider when searching for - /// objects. Default value is 15. - /// The to use - /// during search. Please see documentation of - /// for details. Default value is - /// - public HaarObjectDetector(HaarCascade cascade, int minSize, ObjectDetectorSearchMode searchMode) - : this(cascade, minSize, searchMode, 1.2f) { } - - /// - /// Constructs a new Haar object detector. - /// - /// - /// - /// The to use in the detector's classifier. - /// For the default face cascade, please take a look on - /// . - /// - /// Minimum window size to consider when searching for - /// objects. Default value is 15. - /// - /// The to use - /// during search. Please see documentation of - /// for details. Default value is - /// The re-scaling factor to use when re-scaling the window during search. - /// - public HaarObjectDetector(HaarCascade cascade, int minSize, - ObjectDetectorSearchMode searchMode, float scaleFactor) - : this(cascade, minSize, searchMode, scaleFactor, ObjectDetectorScalingMode.SmallerToGreater) { } - - /// - /// Constructs a new Haar object detector. - /// - /// - /// - /// The to use in the detector's classifier. - /// For the default face cascade, please take a look on - /// . - /// - /// Minimum window size to consider when searching for - /// objects. Default value is 15. - /// The to use - /// during search. Please see documentation of - /// for details. Default is . - /// The scaling factor to rescale the window - /// during search. Default value is 1.2f. - /// The to use - /// when re-scaling the search window during search. Default is - /// . - /// - public HaarObjectDetector(HaarCascade cascade, int minSize, - ObjectDetectorSearchMode searchMode, float scaleFactor, - ObjectDetectorScalingMode scalingMode) - { - this.classifier = new HaarClassifier(cascade); - this.minSize = new Size(minSize, minSize); - this.searchMode = searchMode; - this.ScalingMode = scalingMode; - this.factor = scaleFactor; - this.detectedObjects = new List(); - - this.baseWidth = cascade.Width; - this.baseHeight = cascade.Height; - - this.match = new RectangleGroupMatching(0, 0.2); - } - #endregion - - #region Properties - /// - /// Minimum window size to consider when searching objects. - /// - /// - public Size MinSize - { - get { return minSize; } - set { minSize = value; } - } - - /// - /// Maximum window size to consider when searching objects. - /// - public Size MaxSize - { - get { return maxSize; } - set { maxSize = value; } - } - - /// - /// Gets or sets the color channel to use when processing color images. - /// - /// - //public int Channel - //{ - // get { return channel; } - // set { channel = value; } - //} - - /// - /// Gets or sets the scaling factor to rescale the window during search. - /// - /// - public float ScalingFactor - { - get { return factor; } - set - { - if (value != factor) - { - factor = value; - steps = null; - } - } - } - - /// - /// Gets or sets the desired searching method. - /// - /// - public ObjectDetectorSearchMode SearchMode - { - get { return searchMode; } - set { searchMode = value; } - } - - /// - /// Gets or sets the desired scaling method. - /// - /// - public ObjectDetectorScalingMode ScalingMode - { - get { return scalingMode; } - set - { - if (value != scalingMode) - { - scalingMode = value; - steps = null; - } - } - } - - /// - /// Gets or sets the minimum threshold used to suppress rectangles which - /// have not been detected sufficient number of times. This property only - /// has effect when is set to . - /// - /// - /// - /// - /// The value of this property represents the minimum amount of detections - /// made inside a region to report this region as an actual detection. For - /// example, setting this property to two will discard all regions which - /// had not achieved at least two detected rectangles within it. - /// - /// - /// Setting this property to a value higher than zero may decrease the - /// number of false positives. - /// - /// - public int Suppression - { - get { return match.MinimumNeighbors; } - set { match.MinimumNeighbors = value; } - } - - /// - /// Gets the detected objects bounding boxes. - /// - /// - public Rectangle[] DetectedObjects - { - get { return detectedObjects.ToArray(); } - } - - /// - /// Gets the internal Cascade Classifier used by this detector. - /// - /// - public HaarClassifier Classifier - { - get { return classifier; } - } - - /// - /// Gets how many frames the object has - /// been detected in a steady position. - /// - /// - /// The number of frames the detected object - /// has been in a steady position. - /// - public int Steady { get; private set; } - - #endregion - - - /// - /// Performs object detection on the given frame. - /// - /// - //public Rectangle[] ProcessFrame(Bitmap frame) - //{ - // using (FastBitmap fastBitmap = new FastBitmap(frame)) - // { - // return ProcessFrame(fastBitmap); - // } - //} - - /// - /// Performs object detection on the given frame. - /// - /// - public Rectangle[] ProcessFrame(Bitmap image) - { - // int colorChannel = - // image.PixelFormat == PixelFormat.Format8bppIndexed ? 0 : channel; - - Rectangle[] objects; - - // Creates an integral image representation of the frame - using (FastBitmap fastBitmap = new FastBitmap(image, this.classifier.Cascade.HasTiltedFeatures)) - { - // Creates a new list of detected objects. - this.detectedObjects.Clear(); - - int width = fastBitmap.Width; - int height = fastBitmap.Height; - - // Update parameters only if different size - if (steps == null || width != lastWidth || height != lastHeight) - update(width, height); - - - Rectangle window = Rectangle.Empty; - - // For each scaling step - for (int i = 0; i < steps.Length; i++) - { - float scaling = steps[i]; - - // Set the classifier window scale - classifier.Scale = scaling; - - // Get the scaled window size - window.Width = (int)(baseWidth * scaling); - window.Height = (int)(baseHeight * scaling); - - // Check if the window is lesser than the minimum size - if (window.Width < minSize.Width || window.Height < minSize.Height) - { - // If we are searching in greater to smaller mode, - if (scalingMode == ObjectDetectorScalingMode.GreaterToSmaller) - { - break; // it won't get bigger, so we should stop. - } - else continue; // continue until it gets greater. - } - - // Check if the window is greater than the maximum size - else if (window.Width > maxSize.Width || window.Height > maxSize.Height) - { - // If we are searching in greater to smaller mode, - if (scalingMode == ObjectDetectorScalingMode.GreaterToSmaller) - { - continue; // continue until it gets smaller. - } - - break; // it won't get smaller, so we should stop. - } - - // Grab some scan loop parameters - int xStep = window.Width >> 3; - int yStep = window.Height >> 3; - - int xEnd = width - window.Width; - int yEnd = height - window.Height; - - - // Parallel mode. Scan the integral image searching - // for objects in the window with parallelization. - var bag = new System.Collections.Concurrent.ConcurrentBag(); - - int numSteps = (int)Math.Ceiling((double)yEnd / yStep); - - // For each pixel in the window column - var window1 = window; - Parallel.For( - 0, - numSteps, - (j, options) => - { - int y = j * yStep; - - // Create a local window reference - Rectangle localWindow = window1; - - localWindow.Y = y; - - // For each pixel in the window row - for (int x = 0; x < xEnd; x += xStep) - { - if (options.ShouldExitCurrentIteration) return; - - localWindow.X = x; - - // Try to detect and object inside the window - if (classifier.Compute(fastBitmap, localWindow)) - { - // an object has been detected - bag.Add(localWindow); - - if (searchMode == ObjectDetectorSearchMode.Single) - options.Stop(); - } - } - }); - - // If required, avoid adding overlapping objects at - // the expense of extra computation. Otherwise, only - // add objects to the detected objects collection. - if (searchMode == ObjectDetectorSearchMode.NoOverlap) - { - foreach (Rectangle obj in bag) - { - if (!overlaps(obj)) - { - detectedObjects.Add(obj); - } - } - } - else if (searchMode == ObjectDetectorSearchMode.Single) - { - if (bag.TryPeek(out window)) - { - detectedObjects.Add(window); - break; - } - } - else - { - foreach (Rectangle obj in bag) - { - detectedObjects.Add(obj); - } - } - } - } - - objects = detectedObjects.ToArray(); - - if (searchMode == ObjectDetectorSearchMode.Average) - { - objects = match.Group(objects); - } - - checkSteadiness(objects); - lastObjects = objects; - - return objects; // Returns the array of detected objects. - } - - private void update(int width, int height) - { - List listSteps = new List(); - - // Set initial parameters according to scaling mode - if (scalingMode == ObjectDetectorScalingMode.SmallerToGreater) - { - float start = 1f; - float stop = Math.Min(width / (float)baseWidth, height / (float)baseHeight); - float step = factor; - - for (float f = start; f < stop; f *= step) - listSteps.Add(f); - } - else - { - float start = Math.Min(width / (float)baseWidth, height / (float)baseHeight); - float stop = 1f; - float step = 1f / factor; - - for (float f = start; f > stop; f *= step) - listSteps.Add(f); - } - - steps = listSteps.ToArray(); - - lastWidth = width; - lastHeight = height; - } - - private void checkSteadiness(Rectangle[] rectangles) - { - if (lastObjects == null || - rectangles == null || - rectangles.Length == 0) - { - Steady = 0; - return; - } - - bool equals = true; - foreach (Rectangle current in rectangles) - { - bool found = false; - foreach (Rectangle last in lastObjects) - { - if (current.IsEqual(last, steadyThreshold)) - { - found = true; - continue; - } - } - - if (!found) - { - equals = false; - break; - } - } - - if (equals) - { - Steady++; - } - else - { - Steady = 0; - } - } - - private bool overlaps(Rectangle rect) - { - foreach (Rectangle r in detectedObjects) - { - if (rect.IntersectsWith(r)) - { - return true; - } - } - - return false; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/ObjectDetectorScalingMode.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/ObjectDetectorScalingMode.cs deleted file mode 100644 index 2899d01fa..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/ObjectDetectorScalingMode.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - /// - /// Object detector options for window scaling. - /// - /// - public enum ObjectDetectorScalingMode - { - /// - /// Will start with a big search window and - /// gradually scale into smaller ones. - /// - /// - GreaterToSmaller, - - /// - /// Will start with small search windows and - /// gradually scale into greater ones. - /// - /// - SmallerToGreater, - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/ObjectDetectorSearchMode.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/ObjectDetectorSearchMode.cs deleted file mode 100644 index f20e00eda..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/ObjectDetectorSearchMode.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - /// - /// Object detector options for the search procedure. - /// - /// - public enum ObjectDetectorSearchMode - { - /// - /// Entire image will be scanned. - /// - /// - Default = 0, - - /// - /// Only a single object will be retrieved. - /// - /// - Single, - - /// - /// If a object has already been detected inside an area, - /// it will not be scanned twice for inner or overlapping - /// objects, saving computation time. - /// - /// - NoOverlap, - - /// - /// If several objects are located within one another, - /// they will be averaged. Additionally, objects which - /// have not been detected sufficient times may be dropped - /// by setting . - /// - /// - Average, - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/RectangleGroupMatching.cs b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/RectangleGroupMatching.cs deleted file mode 100644 index bc2bd1039..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/RectangleGroupMatching.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Accord Vision Library -// The Accord.NET Framework -// http://accord-framework.net -// -// Copyright © César Souza, 2009-2015 -// cesarsouza at gmail.com -// -// This code has been submitted as an user contribution by darko.juric2 -// GCode Issue #12 https://code.google.com/p/accord/issues/detail?id=12 -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// - -namespace ImageProcessor.Imaging.Filters.ObjectDetection -{ - using System; - using System.Drawing; - - /// - /// Group matching algorithm for detection region averaging. - /// - /// - /// - /// This class can be seen as a post-processing filter. Its goal is to - /// group near or contained regions together in order to produce more - /// robust and smooth estimates of the detected regions. - /// - /// - public class RectangleGroupMatching : GroupMatching - { - private double threshold; - - /// - /// Creates a new object. - /// - /// - /// - /// The minimum number of neighbors needed to keep a detection. If a rectangle - /// has less than this minimum number, it will be discarded as a false positive. - /// - /// The minimum distance threshold to consider two rectangles as neighbors. - /// Default is 0.2. - /// - public RectangleGroupMatching(int minimumNeighbors = 2, double threshold = 0.2) - : base(minimumNeighbors) - { - this.threshold = threshold; - } - - /// - /// Gets the minimum distance threshold to consider - /// two rectangles as neighbors. Default is 0.2. - /// - /// - protected double Threshold - { - get { return threshold; } - } - - /// - /// Checks if two rectangles are near. - /// - /// - protected override bool Near(Rectangle shape1, Rectangle shape2) - { - if (shape1.Contains(shape2) || shape2.Contains(shape1)) - return true; - - int minHeight = Math.Min(shape1.Height, shape2.Height); - int minWidth = Math.Min(shape1.Width, shape2.Width); - double delta = 0.5 * threshold * (minHeight + minWidth); - - return Math.Abs(shape1.X - shape2.X) <= delta - && Math.Abs(shape1.Y - shape2.Y) <= delta - && Math.Abs(shape1.Right - shape2.Right) <= delta - && Math.Abs(shape1.Bottom - shape2.Bottom) <= delta; - } - - /// - /// Averages rectangles which belongs to the - /// same class (have the same class label) - /// - /// - protected override Rectangle[] Average(int[] labels, Rectangle[] shapes, out int[] neighborCounts) - { - neighborCounts = new int[Classes]; - - Rectangle[] centroids = new Rectangle[Classes]; - for (int i = 0; i < shapes.Length; i++) - { - int j = labels[i]; - - centroids[j].X += shapes[i].X; - centroids[j].Y += shapes[i].Y; - centroids[j].Width += shapes[i].Width; - centroids[j].Height += shapes[i].Height; - - neighborCounts[j]++; - } - - for (int i = 0; i < centroids.Length; i++) - { - centroids[i] = new Rectangle( - x: (int)Math.Ceiling((float)centroids[i].X / neighborCounts[i]), - y: (int)Math.Ceiling((float)centroids[i].Y / neighborCounts[i]), - width: (int)Math.Ceiling((float)centroids[i].Width / neighborCounts[i]), - height: (int)Math.Ceiling((float)centroids[i].Height / neighborCounts[i])); - } - - return centroids; - } - } - -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_alt.xml.REMOVED.git-id b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_alt.xml.REMOVED.git-id deleted file mode 100644 index 7b391478a..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_alt.xml.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -b3860ad6afc1b4eeab715c0de52156a24ec976e7 \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_default.xml.REMOVED.git-id b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_default.xml.REMOVED.git-id deleted file mode 100644 index 71674c521..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_default.xml.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -bc2aa3c73e580998987cc543593cff2ffb48aa31 \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_legacy.xml.REMOVED.git-id b/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_legacy.xml.REMOVED.git-id deleted file mode 100644 index 5dc16bacd..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/ObjectDetection/Resources/haarcascade_frontalface_legacy.xml.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -eb6792a3e6ca1e3ab14c44ba04153ab71328f027 \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/BlackWhiteMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/BlackWhiteMatrixFilter.cs deleted file mode 100644 index 2f11cc931..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/BlackWhiteMatrixFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a black and white filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Encapsulates methods with which to add a black and white filter to an image. - /// - internal class BlackWhiteMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.BlackWhite; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/ColorMatrixes.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/ColorMatrixes.cs deleted file mode 100644 index 36a72a161..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/ColorMatrixes.cs +++ /dev/null @@ -1,265 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// A list of available color matrices to apply to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing.Imaging; - - /// - /// A list of available color matrices to apply to an image. - /// - internal static class ColorMatrixes - { - /// - /// The for generating the black and white filter. - /// - private static ColorMatrix blackWhite; - - /// - /// Gets the for generating the high pass - /// on the comic book filter. - /// - private static ColorMatrix comicHigh; - - /// - /// Gets for generating the low pass - /// on the comic book filter. - /// - private static ColorMatrix comicLow; - - /// - /// The for generating the greyscale filter. - /// - private static ColorMatrix greyScale; - - /// - /// The for generating the high saturation filter. - /// - private static ColorMatrix hiSatch; - - /// - /// The for generating the invert filter. - /// - private static ColorMatrix invert; - - /// - /// The for generating the lomograph filter. - /// - private static ColorMatrix lomograph; - - /// - /// The for generating the low saturation filter. - /// - private static ColorMatrix loSatch; - - /// - /// The for generating the polaroid filter. - /// - private static ColorMatrix polaroid; - - /// - /// The for generating the sepia filter. - /// - private static ColorMatrix sepia; - - /// - /// Gets the for generating the black and white filter. - /// - internal static ColorMatrix BlackWhite - { - get - { - return blackWhite ?? (blackWhite = new ColorMatrix( - new[] - { - new[] { 1.5f, 1.5f, 1.5f, 0, 0 }, - new[] { 1.5f, 1.5f, 1.5f, 0, 0 }, - new[] { 1.5f, 1.5f, 1.5f, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { -1, -1, -1, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the high pass - /// on the comic book filter. - /// - internal static ColorMatrix ComicHigh - { - get - { - return comicHigh ?? (comicHigh = new ColorMatrix( - new[] - { - new[] { 2, -0.5f, -0.5f, 0, 0 }, - new[] { -0.5f, 2, -0.5f, 0, 0 }, - new[] { -0.5f, -0.5f, 2, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { 0, 0, 0, 0, 1 } - })); - } - } - - /// - /// Gets for generating the low pass - /// on the comic book filter. - /// - internal static ColorMatrix ComicLow - { - get - { - return comicLow ?? (comicLow = new ColorMatrix( - new[] - { - new float[] { 1, 0, 0, 0, 0 }, - new float[] { 0, 1, 0, 0, 0 }, - new float[] { 0, 0, 1, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new[] { .075f, .075f, .075f, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the greyscale filter. - /// - internal static ColorMatrix GreyScale - { - get - { - return greyScale ?? (greyScale = new ColorMatrix( - new[] - { - new[] { .33f, .33f, .33f, 0, 0 }, - new[] { .59f, .59f, .59f, 0, 0 }, - new[] { .11f, .11f, .11f, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { 0, 0, 0, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the high saturation filter. - /// - internal static ColorMatrix HiSatch - { - get - { - return hiSatch ?? (hiSatch = new ColorMatrix( - new[] - { - new float[] { 3, -1, -1, 0, 0 }, - new float[] { -1, 3, -1, 0, 0 }, - new float[] { -1, -1, 3, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { 0, 0, 0, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the invert filter. - /// - internal static ColorMatrix Invert - { - get - { - return invert ?? (invert = new ColorMatrix( - new[] - { - new float[] { -1, 0, 0, 0, 0 }, - new float[] { 0, -1, 0, 0, 0 }, - new float[] { 0, 0, -1, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { 1, 1, 1, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the lomograph filter. - /// - internal static ColorMatrix Lomograph - { - get - { - return lomograph - ?? (lomograph = new ColorMatrix( - new[] - { - new[] { 1.50f, 0, 0, 0, 0 }, - new[] { 0, 1.45f, 0, 0, 0 }, - new[] { 0, 0, 1.09f, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new[] { -0.10f, 0.05f, -0.08f, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the low saturation filter. - /// - internal static ColorMatrix LoSatch - { - get - { - return loSatch ?? (loSatch = new ColorMatrix( - new[] - { - new float[] { 1, 0, 0, 0, 0 }, - new float[] { 0, 1, 0, 0, 0 }, - new float[] { 0, 0, 1, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new[] { .10f, .10f, .10f, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the polaroid filter. - /// - internal static ColorMatrix Polaroid - { - get - { - return polaroid ?? (polaroid = new ColorMatrix( - new[] - { - new[] { 1.638f, -0.062f, -0.262f, 0, 0 }, - new[] { -0.122f, 1.378f, -0.122f, 0, 0 }, - new[] { 1.016f, -0.016f, 1.383f, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new[] { 0.06f, -0.05f, -0.05f, 0, 1 } - })); - } - } - - /// - /// Gets the for generating the sepia filter. - /// - internal static ColorMatrix Sepia - { - get - { - return sepia ?? (sepia = new ColorMatrix( - new[] - { - new[] { .393f, .349f, .272f, 0, 0 }, - new[] { .769f, .686f, .534f, 0, 0 }, - new[] { .189f, .168f, .131f, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { 0, 0, 0, 0, 1 } - })); - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/ComicMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/ComicMatrixFilter.cs deleted file mode 100644 index d9c635940..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/ComicMatrixFilter.cs +++ /dev/null @@ -1,170 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a comic filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.Filters.Artistic; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods with which to add a comic filter to an image. - /// - internal class ComicMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.ComicLow; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image image, Image newImage) - { - // Bitmaps for comic pattern - Bitmap highBitmap = null; - Bitmap lowBitmap = null; - Bitmap patternBitmap = null; - Bitmap edgeBitmap = null; - int width = image.Width; - int height = image.Height; - - try - { - using (ImageAttributes attributes = new ImageAttributes()) - { - Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height); - - attributes.SetColorMatrix(ColorMatrixes.ComicHigh); - - // Draw the image with the high comic colormatrix. - highBitmap = new Bitmap(rectangle.Width, rectangle.Height); - highBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Apply a oil painting filter to the image. - highBitmap = new OilPaintingFilter(3, 5).ApplyFilter((Bitmap)image); - - // Draw the edges. - edgeBitmap = new Bitmap(width, height); - edgeBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); - edgeBitmap = Effects.Trace(image, edgeBitmap, 120); - - using (Graphics graphics = Graphics.FromImage(highBitmap)) - { - graphics.DrawImage(highBitmap, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); - } - - // Create a bitmap for overlaying. - lowBitmap = new Bitmap(rectangle.Width, rectangle.Height); - lowBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Set the color matrix - attributes.SetColorMatrix(this.Matrix); - - // Draw the image with the losatch colormatrix. - using (Graphics graphics = Graphics.FromImage(lowBitmap)) - { - graphics.DrawImage(highBitmap, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); - } - - // We need to create a new image now with a pattern mask to paint it - // onto the other image with. - patternBitmap = new Bitmap(rectangle.Width, rectangle.Height); - patternBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Create the pattern mask. - using (Graphics graphics = Graphics.FromImage(patternBitmap)) - { - graphics.Clear(Color.Transparent); - - for (int y = 0; y < height; y += 8) - { - for (int x = 0; x < width; x += 4) - { - graphics.FillEllipse(Brushes.White, x, y, 3, 3); - graphics.FillEllipse(Brushes.White, x + 2, y + 4, 3, 3); - } - } - } - - // Transfer the alpha channel from the mask to the low saturation image. - lowBitmap = Effects.ApplyMask(lowBitmap, patternBitmap); - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - graphics.Clear(Color.Transparent); - - // Overlay the image. - graphics.DrawImage(highBitmap, 0, 0); - graphics.DrawImage(lowBitmap, 0, 0); - graphics.DrawImage(edgeBitmap, 0, 0); - - // Draw an edge around the image. - using (Pen blackPen = new Pen(Color.Black)) - { - blackPen.Width = 4; - graphics.DrawRectangle(blackPen, rectangle); - } - - // Dispose of the other images - highBitmap.Dispose(); - lowBitmap.Dispose(); - patternBitmap.Dispose(); - edgeBitmap.Dispose(); - } - } - - // Reassign the image. - image.Dispose(); - image = newImage; - } - catch - { - if (newImage != null) - { - newImage.Dispose(); - } - - if (highBitmap != null) - { - highBitmap.Dispose(); - } - - if (lowBitmap != null) - { - lowBitmap.Dispose(); - } - - if (patternBitmap != null) - { - patternBitmap.Dispose(); - } - - if (edgeBitmap != null) - { - edgeBitmap.Dispose(); - } - } - - return (Bitmap)image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/GothamMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/GothamMatrixFilter.cs deleted file mode 100644 index 66adcb440..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/GothamMatrixFilter.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a Gotham filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods with which to add a gotham filter to an image. - /// - internal class GothamMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.GreyScale; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - - // Overlay the image with some semi-transparent colors to finish the effect. - using (GraphicsPath path = new GraphicsPath()) - { - path.AddRectangle(rectangle); - - // Paint a burgundy rectangle with a transparency of ~30% over the image. - // Paint a blue rectangle with a transparency of 20% over the image. - using (SolidBrush brush = new SolidBrush(Color.FromArgb(77, 38, 14, 28))) - { - Region oldClip = graphics.Clip; - graphics.Clip = new Region(rectangle); - graphics.FillRectangle(brush, rectangle); - - // Fill the blue. - brush.Color = Color.FromArgb(51, 29, 32, 59); - graphics.FillRectangle(brush, rectangle); - graphics.Clip = oldClip; - } - } - } - } - - // Add brightness and contrast to finish the effect. - destination = Adjustments.Brightness(destination, 5); - destination = Adjustments.Contrast(destination, 85); - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/GreyScaleMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/GreyScaleMatrixFilter.cs deleted file mode 100644 index 49ac84b86..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/GreyScaleMatrixFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a greyscale filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Encapsulates methods with which to add a greyscale filter to an image. - /// - internal class GreyScaleMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.GreyScale; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/HiSatchMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/HiSatchMatrixFilter.cs deleted file mode 100644 index 421f49e94..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/HiSatchMatrixFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a high saturated filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Encapsulates methods with which to add a high saturated filter to an image. - /// - internal class HiSatchMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.HiSatch; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - return (Bitmap)destination; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/IMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/IMatrixFilter.cs deleted file mode 100644 index e4508f94a..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/IMatrixFilter.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Defines properties and methods for ColorMatrix based filters. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Defines properties and methods for ColorMatrix based filters. - /// - public interface IMatrixFilter - { - /// - /// Gets the for this filter instance. - /// - ColorMatrix Matrix { get; } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - Bitmap TransformImage(Image source, Image destination); - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/InvertMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/InvertMatrixFilter.cs deleted file mode 100644 index 7cd944183..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/InvertMatrixFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add an inverted filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Encapsulates methods with which to add an inverted filter to an image. - /// - internal class InvertMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.Invert; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - return (Bitmap)destination; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/LoSatchMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/LoSatchMatrixFilter.cs deleted file mode 100644 index 222a7c037..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/LoSatchMatrixFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a low saturated filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Encapsulates methods with which to add a low saturated filter to an image. - /// - internal class LoSatchMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.LoSatch; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/LomographMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/LomographMatrixFilter.cs deleted file mode 100644 index e181d03ad..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/LomographMatrixFilter.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a lomograph filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods with which to add a lomograph filter to an image. - /// - internal class LomographMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.Lomograph; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - // Add a vignette to finish the effect. - destination = Effects.Vignette(destination, Color.FromArgb(220, 0, 10, 0)); - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/MatrixFilterBase.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/MatrixFilterBase.cs deleted file mode 100644 index 720f73c51..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/MatrixFilterBase.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The matrix filter base contains equality methods. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// The matrix filter base contains equality methods. - /// - public abstract class MatrixFilterBase : IMatrixFilter - { - /// - /// Gets the for this filter instance. - /// - public abstract ColorMatrix Matrix { get; } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public abstract Bitmap TransformImage(Image image, Image newImage); - - /// - /// Determines whether the specified , is equal to this instance. - /// - /// The to compare with this instance. - /// - /// true if the specified is equal to this instance; otherwise, false. - /// - public override bool Equals(object obj) - { - IMatrixFilter filter = obj as IMatrixFilter; - - if (filter == null) - { - return false; - } - - return this.GetType().Name == filter.GetType().Name - && this.Matrix.Equals(filter.Matrix); - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = GetType().Name.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Matrix.GetHashCode(); - return hashCode; - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/MatrixFilters.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/MatrixFilters.cs deleted file mode 100644 index 3acc45468..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/MatrixFilters.cs +++ /dev/null @@ -1,130 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The filters available to the Filter . -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using ImageProcessor.Processors; - - /// - /// The filters available to the Filter . - /// - public static class MatrixFilters - { - /// - /// Gets the for generating the black and white filter. - /// - public static IMatrixFilter BlackWhite - { - get - { - return new BlackWhiteMatrixFilter(); - } - } - - /// - /// Gets the for generating the comic filter. - /// - public static IMatrixFilter Comic - { - get - { - return new ComicMatrixFilter(); - } - } - - /// - /// Gets the for generating the gotham filter. - /// - public static IMatrixFilter Gotham - { - get - { - return new GothamMatrixFilter(); - } - } - - /// - /// Gets the for generating the greyscale filter. - /// - public static IMatrixFilter GreyScale - { - get - { - return new GreyScaleMatrixFilter(); - } - } - - /// - /// Gets the for generating the high saturation filter. - /// - public static IMatrixFilter HiSatch - { - get - { - return new HiSatchMatrixFilter(); - } - } - - /// - /// Gets the for generating the invert filter. - /// - public static IMatrixFilter Invert - { - get - { - return new InvertMatrixFilter(); - } - } - - /// - /// Gets the for generating the lomograph filter. - /// - public static IMatrixFilter Lomograph - { - get - { - return new LomographMatrixFilter(); - } - } - - /// - /// Gets the for generating the low saturation filter. - /// - public static IMatrixFilter LoSatch - { - get - { - return new LoSatchMatrixFilter(); - } - } - - /// - /// Gets the for generating the polaroid filter. - /// - public static IMatrixFilter Polaroid - { - get - { - return new PolaroidMatrixFilter(); - } - } - - /// - /// Gets the for generating the sepia filter. - /// - public static IMatrixFilter Sepia - { - get - { - return new SepiaMatrixFilter(); - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/PolaroidMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/PolaroidMatrixFilter.cs deleted file mode 100644 index 9d9eb3fb5..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/PolaroidMatrixFilter.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a Polaroid filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods with which to add a Polaroid filter to an image. - /// - internal class PolaroidMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.Polaroid; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - // Fade the contrast - destination = Adjustments.Contrast(destination, -25); - - // Add a glow to the image. - destination = Effects.Glow(destination, Color.FromArgb(70, 255, 153, 102)); - - // Add a vignette to finish the effect. - destination = Effects.Vignette(destination, Color.FromArgb(220, 102, 34, 0)); - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Filters/Photo/SepiaMatrixFilter.cs b/old/src/ImageProcessor/Imaging/Filters/Photo/SepiaMatrixFilter.cs deleted file mode 100644 index 3c78b075b..000000000 --- a/old/src/ImageProcessor/Imaging/Filters/Photo/SepiaMatrixFilter.cs +++ /dev/null @@ -1,54 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a sepia filter to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Filters.Photo -{ - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Encapsulates methods with which to add a sepia filter to an image. - /// - internal class SepiaMatrixFilter : MatrixFilterBase - { - /// - /// Gets the for this filter instance. - /// - public override ColorMatrix Matrix - { - get { return ColorMatrixes.Sepia; } - } - - /// - /// Processes the image. - /// - /// The current image to process - /// The new Image to return - /// - /// The processed . - /// - public override Bitmap TransformImage(Image source, Image destination) - { - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(this.Matrix); - - Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height); - - graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); - } - } - - return (Bitmap)destination; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/BitmapFormat.cs b/old/src/ImageProcessor/Imaging/Formats/BitmapFormat.cs deleted file mode 100644 index de1efd4c0..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/BitmapFormat.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides the necessary information to support bitmap images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System.Drawing.Imaging; - using System.Text; - - /// - /// Provides the necessary information to support bitmap images. - /// - public class BitmapFormat : FormatBase - { - /// - /// Gets the file headers. - /// - public override byte[][] FileHeaders - { - get - { - return new[] { Encoding.ASCII.GetBytes("BM") }; - } - } - - /// - /// Gets the list of file extensions. - /// - public override string[] FileExtensions - { - get - { - return new[] { "bmp" }; - } - } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public override string MimeType - { - get - { - return "image/bmp"; - } - } - - /// - /// Gets the . - /// - public override ImageFormat ImageFormat - { - get - { - return ImageFormat.Bmp; - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/FormatBase.cs b/old/src/ImageProcessor/Imaging/Formats/FormatBase.cs deleted file mode 100644 index cfad02046..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/FormatBase.cs +++ /dev/null @@ -1,165 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The supported format base implement this class when building a supported format. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - - /// - /// The supported format base. Implement this class when building a supported format. - /// - public abstract class FormatBase : ISupportedImageFormat - { - /// - /// Initializes a new instance of the class. - /// - protected FormatBase() - { - this.Quality = 90; - } - - /// - /// Gets the file headers. - /// - public abstract byte[][] FileHeaders { get; } - - /// - /// Gets the list of file extensions. - /// - public abstract string[] FileExtensions { get; } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public abstract string MimeType { get; } - - /// - /// Gets the default file extension. - /// - public string DefaultExtension - { - get - { - return this.MimeType.Replace("image/", string.Empty); - } - } - - /// - /// Gets the file format of the image. - /// - public abstract ImageFormat ImageFormat { get; } - - /// - /// Gets or sets a value indicating whether the image format is indexed. - /// - public bool IsIndexed { get; set; } - - /// - /// Gets or sets the quality of output for images. - /// - public int Quality { get; set; } - - /// - /// Applies the given processor the current image. - /// - /// The processor delegate. - /// The . - public virtual void ApplyProcessor(Func processor, ImageFactory factory) - { - factory.Image = processor.Invoke(factory); - } - - /// - /// Decodes the image to process. - /// - /// - /// The containing the image information. - /// - /// - /// The . - /// - public virtual Image Load(Stream stream) - { -#if !__MonoCS__ - return Image.FromStream(stream, true); -#else - return Image.FromStream(stream); -#endif - } - - /// - /// Saves the current image to the specified output stream. - /// - /// The to save the image information to. - /// The to save. - /// - /// The . - /// - public virtual Image Save(Stream stream, Image image) - { - image.Save(stream, this.ImageFormat); - return image; - } - - /// - /// Saves the current image to the specified file path. - /// - /// The path to save the image to. - /// The - /// to save. - /// - /// The . - /// - public virtual Image Save(string path, Image image) - { - image.Save(path, this.ImageFormat); - return image; - } - - /// - /// Determines whether the specified , is equal to this instance. - /// - /// The to compare with this instance. - /// - /// true if the specified is equal to this instance; otherwise, false. - /// - public override bool Equals(object obj) - { - ISupportedImageFormat format = obj as ISupportedImageFormat; - - if (format == null) - { - return false; - } - - return this.MimeType.Equals(format.MimeType) && this.IsIndexed.Equals(format.IsIndexed); - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.MimeType.GetHashCode(); - hashCode = (hashCode * 397) ^ this.IsIndexed.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Quality; - return hashCode; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Formats/FormatUtilities.cs b/old/src/ImageProcessor/Imaging/Formats/FormatUtilities.cs deleted file mode 100644 index c35db1852..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/FormatUtilities.cs +++ /dev/null @@ -1,179 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Utility methods for working with supported image formats. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - using System.Linq; - using System.Reflection; - using System.Threading.Tasks; - - using ImageProcessor.Configuration; - - /// - /// Utility methods for working with supported image formats. - /// - public static class FormatUtilities - { - /// - /// Gets the correct from the given stream. - /// - /// - /// - /// The to read from. - /// - /// - /// The . - /// - public static ISupportedImageFormat GetFormat(Stream stream) - { - // Reset the position of the stream to ensure we're reading the correct part. - stream.Position = 0; - - IEnumerable supportedImageFormats = - ImageProcessorBootstrapper.Instance.SupportedImageFormats; - - byte[] buffer = new byte[4]; - stream.Read(buffer, 0, buffer.Length); - - foreach (ISupportedImageFormat supportedImageFormat in supportedImageFormats) - { - byte[][] headers = supportedImageFormat.FileHeaders; - - // ReSharper disable once LoopCanBeConvertedToQuery - foreach (byte[] header in headers) - { - if (header.SequenceEqual(buffer.Take(header.Length))) - { - stream.Position = 0; - - // Return a new instance as we want to use instance properties. - return Activator.CreateInstance(supportedImageFormat.GetType()) as ISupportedImageFormat; - } - } - } - - stream.Position = 0; - return null; - } - - /// - /// Returns a value indicating whether the given image is indexed. - /// - /// - /// The to test. - /// - /// - /// The true if the image is indexed; otherwise, false. - /// - public static bool IsIndexed(Image image) - { - // Test value of flags using bitwise AND. - // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags - return (image.PixelFormat & PixelFormat.Indexed) != 0; - } - - /// - /// Returns the color count from the palette of the given image. - /// - /// - /// The to get the colors from. - /// - /// - /// The representing the color count. - /// - public static int GetColorCount(Image image) - { - ConcurrentDictionary colors = new ConcurrentDictionary(); - int width = image.Width; - int height = image.Height; - - using (FastBitmap fastBitmap = new FastBitmap(image)) - { - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - // ReSharper disable once AccessToDisposedClosure - Color color = fastBitmap.GetPixel(x, y); - colors.TryAdd(color, color); - } - }); - } - - int count = colors.Count; - colors.Clear(); - return count; - } - - /// - /// Returns a value indicating whether the given image is indexed. - /// - /// - /// The to test. - /// - /// - /// The true if the image is animated; otherwise, false. - /// - public static bool IsAnimated(Image image) - { - return ImageAnimator.CanAnimate(image); - } - - /// - /// Returns an instance of EncodingParameters for jpeg compression. - /// - /// The quality to return the image at. - /// The encodingParameters for jpeg compression. - public static EncoderParameters GetEncodingParameters(int quality) - { - EncoderParameters encoderParameters = null; - try - { - // Create a series of encoder parameters. - encoderParameters = new EncoderParameters(1); - - // Set the quality. - encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality); - } - catch - { - if (encoderParameters != null) - { - encoderParameters.Dispose(); - } - } - - return encoderParameters; - } - - /// - /// Uses reflection to allow the creation of an instance of . - /// - /// - /// The . - /// - public static PropertyItem CreatePropertyItem() - { - Type type = typeof(PropertyItem); - ConstructorInfo constructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[] { }, null); - - return (PropertyItem)constructor.Invoke(null); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/GifDecoder.cs b/old/src/ImageProcessor/Imaging/Formats/GifDecoder.cs deleted file mode 100644 index a7008d162..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/GifDecoder.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Decodes gifs to provides information. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.MetaData; - - /// - /// Decodes gifs to provides information. - /// - public class GifDecoder - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The to decode. - /// - public GifDecoder(Image image) - { - this.Height = image.Height; - this.Width = image.Width; - - if (FormatUtilities.IsAnimated(image)) - { - this.IsAnimated = true; - - if (this.IsAnimated) - { - int frameCount = image.GetFrameCount(FrameDimension.Time); - int last = frameCount - 1; - double length = 0; - - List gifFrames = new List(); - - // Get the times stored in the gif. - byte[] times = image.GetPropertyItem((int)ExifPropertyTag.FrameDelay).Value; - - for (int i = 0; i < frameCount; i++) - { - // Convert each 4-byte chunk into an integer. - // GDI returns a single array with all delays, while Mono returns a different array for each frame. - TimeSpan delay = TimeSpan.FromMilliseconds(BitConverter.ToInt32(times, (4 * i) % times.Length) * 10); - - // Find the frame - image.SelectActiveFrame(FrameDimension.Time, i); - - // TODO: Get positions. - gifFrames.Add(new GifFrame { Delay = delay, Image = new Bitmap(image) }); - - // Reset the position. - if (i == last) - { - image.SelectActiveFrame(FrameDimension.Time, 0); - } - - length += delay.TotalMilliseconds; - } - - this.GifFrames = gifFrames; - this.AnimationLength = length; - - // Loop info is stored at byte 20737. - this.LoopCount = BitConverter.ToInt16(image.GetPropertyItem((int)ExifPropertyTag.LoopCount).Value, 0); - this.IsLooped = this.LoopCount != 1; - } - } - } - - /// - /// Gets or sets the image width. - /// - public int Width { get; set; } - - /// - /// Gets or sets the image height. - /// - public int Height { get; set; } - - /// - /// Gets or sets a value indicating whether the image is animated. - /// - public bool IsAnimated { get; set; } - - /// - /// Gets or sets a value indicating whether the image is looped. - /// - public bool IsLooped { get; set; } - - /// - /// Gets or sets the loop count. - /// - public int LoopCount { get; set; } - - /// - /// Gets or sets the gif frames. - /// - public ICollection GifFrames { get; set; } - - /// - /// Gets or sets the animation length in milliseconds. - /// - public double AnimationLength { get; set; } - } -} diff --git a/old/src/ImageProcessor/Imaging/Formats/GifEncoder.cs b/old/src/ImageProcessor/Imaging/Formats/GifEncoder.cs deleted file mode 100644 index 249d5d12c..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/GifEncoder.cs +++ /dev/null @@ -1,395 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encodes multiple images as an animated gif to a stream. -// -// Always wire this up in a using block. -// Disposing the encoder will complete the file. -// Uses default .NET GIF encoding and adds animation headers. -// Adapted from -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - using System.Linq; - - /// - /// Encodes multiple images as an animated gif to a stream. - /// - /// Uses default .NET GIF encoding and adds animation headers. - /// Adapted from - /// - /// - public class GifEncoder - { - #region Constants - /// - /// The application block size. - /// - private const byte ApplicationBlockSize = 0x0b; - - /// - /// The application extension block identifier. - /// - private const int ApplicationExtensionBlockIdentifier = 0xff21; - - /// - /// The application identification. - /// - private const string ApplicationIdentification = "NETSCAPE2.0"; - - /// - /// The file trailer. - /// - private const byte FileTrailer = 0x3b; - - /// - /// The file type. - /// - private const string FileType = "GIF"; - - /// - /// The file version. - /// - private const string FileVersion = "89a"; - - /// - /// The graphic control extension block identifier. - /// - private const int GraphicControlExtensionBlockIdentifier = 0xf921; - - /// - /// The graphic control extension block size. - /// - private const byte GraphicControlExtensionBlockSize = 0x04; - - /// - /// The source color block length. - /// - private const long SourceColorBlockLength = 768; - - /// - /// The source color block position. - /// - private const long SourceColorBlockPosition = 13; - - /// - /// The source global color info position. - /// - private const long SourceGlobalColorInfoPosition = 10; - - /// - /// The source graphic control extension length. - /// - private const long SourceGraphicControlExtensionLength = 8; - - /// - /// The source graphic control extension position. - /// - private const long SourceGraphicControlExtensionPosition = 781; - - /// - /// The source image block header length. - /// - private const long SourceImageBlockHeaderLength = 11; - - /// - /// The source image block position. - /// - private const long SourceImageBlockPosition = 789; - #endregion - - #region Fields - /// - /// The converter for creating the output image from a byte array. - /// - private static readonly ImageConverter Converter = new ImageConverter(); - - /// - /// The stream. - /// - // ReSharper disable once FieldCanBeMadeReadOnly.Local - private MemoryStream imageStream; - - /// - /// The height. - /// - private int? height; - - /// - /// The is first image. - /// - private bool isFirstImage = true; - - /// - /// The repeat count. - /// - private int? repeatCount; - - /// - /// The width. - /// - private int? width; - #endregion - - #region Constructors - /// - /// Initializes a new instance of the class. - /// - /// - /// Sets the width for this gif or null to use the first frame's width. - /// - /// - /// Sets the height for this gif or null to use the first frame's height. - /// - /// - /// The number of times to repeat the animation. - /// - public GifEncoder(int? width = null, int? height = null, int? repeatCount = null) - { - this.imageStream = new MemoryStream(); - this.width = width; - this.height = height; - this.repeatCount = repeatCount; - } - #endregion - - #region Public Methods and Operators - /// - /// Adds a frame to the gif. - /// - /// - /// The containing the image. - /// - public void AddFrame(GifFrame frame) - { - using (MemoryStream gifStream = new MemoryStream()) - { - frame.Image.Save(gifStream, ImageFormat.Gif); - if (this.isFirstImage) - { - // Steal the global color table info - this.WriteHeaderBlock(gifStream, frame.Image.Width, frame.Image.Height); - } - - this.WriteGraphicControlBlock(gifStream, Convert.ToInt32(frame.Delay.TotalMilliseconds / 10F)); - this.WriteImageBlock(gifStream, !this.isFirstImage, frame.X, frame.Y, frame.Image.Width, frame.Image.Height); - } - - this.isFirstImage = false; - } - - /// - /// Saves the completed gif to an - /// - /// The completed animated gif. - public Image Save() - { - // Complete File - this.WriteByte(FileTrailer); - - // Push the data - this.imageStream.Flush(); - this.imageStream.Position = 0; - byte[] bytes = this.imageStream.ToArray(); - this.imageStream.Dispose(); - return (Image)Converter.ConvertFrom(bytes); - } - #endregion - - #region Methods - /// - /// Writes the header block of the animated gif to the stream. - /// - /// - /// The source gif. - /// - /// - /// The width of the image. - /// - /// - /// The height of the image. - /// - private void WriteHeaderBlock(Stream sourceGif, int w, int h) - { - // File Header signature and version. - this.WriteString(FileType); - this.WriteString(FileVersion); - - // Write the logical screen descriptor. - this.WriteShort(this.width.GetValueOrDefault(w)); // Initial Logical Width - this.WriteShort(this.height.GetValueOrDefault(h)); // Initial Logical Height - - // Read the global color table info. - sourceGif.Position = SourceGlobalColorInfoPosition; - this.WriteByte(sourceGif.ReadByte()); - - this.WriteByte(0); // Background Color Index - this.WriteByte(0); // Pixel aspect ratio - this.WriteColorTable(sourceGif); - - // Application Extension Header - int count = this.repeatCount.GetValueOrDefault(0); - if (count != 1) - { - // 0 means loop indefinitely. count is set as play n + 1 times. - count = Math.Max(0, count - 1); - this.WriteShort(ApplicationExtensionBlockIdentifier); - this.WriteByte(ApplicationBlockSize); - - this.WriteString(ApplicationIdentification); - this.WriteByte(3); // Application block length - this.WriteByte(1); - this.WriteShort(count); // Repeat count for images. - - this.WriteByte(0); // Terminator - } - } - - /// - /// The write byte. - /// - /// - /// The value. - /// - private void WriteByte(int value) - { - this.imageStream.WriteByte(Convert.ToByte(value)); - } - - /// - /// The write color table. - /// - /// - /// The source gif. - /// - private void WriteColorTable(Stream sourceGif) - { - sourceGif.Position = SourceColorBlockPosition; // Locating the image color table - byte[] colorTable = new byte[SourceColorBlockLength]; - sourceGif.Read(colorTable, 0, colorTable.Length); - this.imageStream.Write(colorTable, 0, colorTable.Length); - } - - /// - /// The write graphic control block. - /// - /// - /// The source gif. - /// - /// - /// The frame delay. - /// - private void WriteGraphicControlBlock(Stream sourceGif, int frameDelay) - { - sourceGif.Position = SourceGraphicControlExtensionPosition; // Locating the source GCE - byte[] blockhead = new byte[SourceGraphicControlExtensionLength]; - sourceGif.Read(blockhead, 0, blockhead.Length); // Reading source GCE - - this.WriteShort(GraphicControlExtensionBlockIdentifier); // Identifier - this.WriteByte(GraphicControlExtensionBlockSize); // Block Size - this.WriteByte(blockhead[3] & 0xf7 | 0x08); // Setting disposal flag - this.WriteShort(frameDelay); // Setting frame delay - this.WriteByte(blockhead[6]); // Transparent color index - this.WriteByte(0); // Terminator - } - - /// - /// The write image block. - /// - /// - /// The source gif. - /// - /// - /// The include color table. - /// - /// - /// The x position to write the image block. - /// - /// - /// The y position to write the image block. - /// - /// - /// The height of the image block. - /// - /// - /// The width of the image block. - /// - private void WriteImageBlock(Stream sourceGif, bool includeColorTable, int x, int y, int h, int w) - { - // Local Image Descriptor - sourceGif.Position = SourceImageBlockPosition; // Locating the image block - byte[] header = new byte[SourceImageBlockHeaderLength]; - sourceGif.Read(header, 0, header.Length); - this.WriteByte(header[0]); // Separator - this.WriteShort(x); // Position X - this.WriteShort(y); // Position Y - this.WriteShort(h); // Height - this.WriteShort(w); // Width - - if (includeColorTable) - { - // If first frame, use global color table - else use local - sourceGif.Position = SourceGlobalColorInfoPosition; - this.WriteByte(sourceGif.ReadByte() & 0x3f | 0x80); // Enabling local color table - this.WriteColorTable(sourceGif); - } - else - { - this.WriteByte(header[9] & 0x07 | 0x07); // Disabling local color table - } - - this.WriteByte(header[10]); // LZW Min Code Size - - // Read/Write image data - sourceGif.Position = SourceImageBlockPosition + SourceImageBlockHeaderLength; - - int dataLength = sourceGif.ReadByte(); - while (dataLength > 0) - { - byte[] imgData = new byte[dataLength]; - sourceGif.Read(imgData, 0, dataLength); - - this.imageStream.WriteByte(Convert.ToByte(dataLength)); - this.imageStream.Write(imgData, 0, dataLength); - dataLength = sourceGif.ReadByte(); - } - - this.imageStream.WriteByte(0); // Terminator - } - - /// - /// The write short. - /// - /// - /// The value. - /// - private void WriteShort(int value) - { - // Leave only one significant byte. - this.imageStream.WriteByte(Convert.ToByte(value & 0xff)); - this.imageStream.WriteByte(Convert.ToByte((value >> 8) & 0xff)); - } - - /// - /// The write string. - /// - /// - /// The value. - /// - private void WriteString(string value) - { - this.imageStream.Write(value.ToArray().Select(c => (byte)c).ToArray(), 0, value.Length); - } - #endregion - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/GifFormat.cs b/old/src/ImageProcessor/Imaging/Formats/GifFormat.cs deleted file mode 100644 index 81b1df7e6..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/GifFormat.cs +++ /dev/null @@ -1,181 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides the necessary information to support gif images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - using System.Text; - - using ImageProcessor.Imaging.Helpers; - using ImageProcessor.Imaging.Quantizers; - - /// - /// Provides the necessary information to support gif images. - /// - public class GifFormat : FormatBase, IQuantizableImageFormat - { - /// - /// The quantizer for reducing the image palette. - /// - private IQuantizer quantizer = new OctreeQuantizer(255, 8); - - /// - /// The color count. - /// - private int colorCount; - - /// - /// Gets the file headers. - /// - public override byte[][] FileHeaders - { - get - { - return new[] { Encoding.ASCII.GetBytes("GIF") }; - } - } - - /// - /// Gets the list of file extensions. - /// - public override string[] FileExtensions - { - get - { - return new[] { "gif" }; - } - } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public override string MimeType - { - get - { - return "image/gif"; - } - } - - /// - /// Gets the . - /// - public override ImageFormat ImageFormat - { - get - { - return ImageFormat.Gif; - } - } - - /// - /// Gets or sets the quantizer for reducing the image palette. - /// - public IQuantizer Quantizer - { - get - { - return this.quantizer; - } - - set - { - this.quantizer = value; - } - } - - /// - /// Gets or sets the color count. - /// - public int ColorCount - { - get - { - return this.colorCount; - } - - set - { - int count = ImageMaths.Clamp(value, 0, 255); - this.colorCount = count; - this.quantizer = new OctreeQuantizer(count, 8); - } - } - - /// - /// Applies the given processor the current image. - /// - /// The processor delegate. - /// The . - public override void ApplyProcessor(Func processor, ImageFactory factory) - { - GifDecoder decoder = new GifDecoder(factory.Image); - - if (decoder.IsAnimated) - { - GifEncoder encoder = new GifEncoder(null, null, decoder.LoopCount); - foreach (GifFrame frame in decoder.GifFrames) - { - factory.Image = frame.Image; - frame.Image = this.Quantizer.Quantize(processor.Invoke(factory)); - encoder.AddFrame(frame); - } - - factory.Image = encoder.Save(); - } - else - { - base.ApplyProcessor(processor, factory); - } - } - - /// - /// Saves the current image to the specified output stream. - /// - /// - /// The to save the image information to. - /// - /// The to save. - /// - /// The . - /// - public override Image Save(Stream stream, Image image) - { - if (!FormatUtilities.IsAnimated(image)) - { - image = this.Quantizer.Quantize(image); - } - - return base.Save(stream, image); - } - - /// - /// Saves the current image to the specified file path. - /// - /// The path to save the image to. - /// The - /// to save. - /// - /// The . - /// - public override Image Save(string path, Image image) - { - if (!FormatUtilities.IsAnimated(image)) - { - image = this.Quantizer.Quantize(image); - } - - return base.Save(path, image); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/GifFrame.cs b/old/src/ImageProcessor/Imaging/Formats/GifFrame.cs deleted file mode 100644 index 92eae3c80..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/GifFrame.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// A single gif frame. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Drawing; - - /// - /// A single gif frame. - /// - public class GifFrame - { - /// - /// Gets or sets the image. - /// - public Image Image { get; set; } - - /// - /// Gets or sets the delay in milliseconds. - /// - public TimeSpan Delay { get; set; } - - /// - /// Gets or sets the x position of the frame. - /// - public int X { get; set; } - - /// - /// Gets or sets the Y position of the frame. - /// - public int Y { get; set; } - } -} diff --git a/old/src/ImageProcessor/Imaging/Formats/IQuantizableImageFormat.cs b/old/src/ImageProcessor/Imaging/Formats/IQuantizableImageFormat.cs deleted file mode 100644 index 575f5c83a..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/IQuantizableImageFormat.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The IndexedImageFormat interface for identifying quantizable image formats. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using ImageProcessor.Imaging.Quantizers; - - /// - /// The IndexedImageFormat interface for identifying quantizable image formats. - /// - public interface IQuantizableImageFormat - { - /// - /// Gets or sets the quantizer for reducing the image palette. - /// - IQuantizer Quantizer { get; set; } - - /// - /// Gets or sets the color count. - /// - int ColorCount { get; set; } - } -} diff --git a/old/src/ImageProcessor/Imaging/Formats/ISupportedImageFormat.cs b/old/src/ImageProcessor/Imaging/Formats/ISupportedImageFormat.cs deleted file mode 100644 index 05e69260a..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/ISupportedImageFormat.cs +++ /dev/null @@ -1,108 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The SupportedImageFormat interface providing information about image formats to ImageProcessor. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - - /// - /// The SupportedImageFormat interface providing information about image formats to ImageProcessor. - /// - public interface ISupportedImageFormat - { - /// - /// Gets the file headers. - /// - byte[][] FileHeaders { get; } - - /// - /// Gets the list of file extensions. - /// - string[] FileExtensions { get; } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - string MimeType { get; } - - /// - /// Gets the default file extension. - /// - string DefaultExtension { get; } - - /// - /// Gets the file format of the image. - /// - ImageFormat ImageFormat { get; } - - /// - /// Gets or sets a value indicating whether the image format is indexed. - /// - bool IsIndexed { get; set; } - - /// - /// Gets or sets the quality of output for images. - /// - int Quality { get; set; } - - #region Methods - /// - /// Applies the given processor the current image. - /// - /// - /// The processor delegate. - /// - /// - /// The . - /// - void ApplyProcessor(Func processor, ImageFactory factory); - - /// - /// Loads the image to process. - /// - /// - /// The containing the image information. - /// - /// - /// The . - /// - Image Load(Stream stream); - - /// - /// Saves the current image to the specified output stream. - /// - /// - /// The to save the image information to. - /// - /// - /// The to save. - /// - /// - /// The . - /// - Image Save(Stream stream, Image image); - - /// - /// Saves the current image to the specified file path. - /// - /// The path to save the image to. - /// - /// The to save. - /// - /// - /// The . - /// - Image Save(string path, Image image); - #endregion - } -} diff --git a/old/src/ImageProcessor/Imaging/Formats/JpegFormat.cs b/old/src/ImageProcessor/Imaging/Formats/JpegFormat.cs deleted file mode 100644 index ae5fd05c3..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/JpegFormat.cs +++ /dev/null @@ -1,146 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides the necessary information to support jpeg images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - using System.Linq; - - /// - /// Provides the necessary information to support jpeg images. - /// - public sealed class JpegFormat : FormatBase - { - /// - /// Gets the file headers. - /// - public override byte[][] FileHeaders - { - get - { - return new[] { new byte[] { 255, 216, 255 } }; - } - } - - /// - /// Gets the list of file extensions. - /// - public override string[] FileExtensions - { - get - { - return new[] { "jpeg", "jpg" }; - } - } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public override string MimeType - { - get - { - return "image/jpeg"; - } - } - - /// - /// Gets the . - /// - public override ImageFormat ImageFormat - { - get - { - return ImageFormat.Jpeg; - } - } - - /// - /// Applies the given processor the current image. - /// - /// The processor delegate. - /// The . - public override void ApplyProcessor(Func processor, ImageFactory factory) - { - base.ApplyProcessor(processor, factory); - - // Set the property item information from any Exif metadata. - // We do this here so that they can be changed between processor methods. - if (factory.PreserveExifData) - { - foreach (KeyValuePair propertItem in factory.ExifPropertyItems) - { - factory.Image.SetPropertyItem(propertItem.Value); - } - } - } - - /// - /// Saves the current image to the specified output stream. - /// - /// - /// The to save the image information to. - /// - /// The to save. - /// - /// The . - /// - public override Image Save(Stream stream, Image image) - { - // Jpegs can be saved with different settings to include a quality setting for the JPEG compression. - // This improves output compression and quality. - using (EncoderParameters encoderParameters = FormatUtilities.GetEncodingParameters(this.Quality)) - { - ImageCodecInfo imageCodecInfo = - ImageCodecInfo.GetImageEncoders() - .FirstOrDefault(ici => ici.MimeType.Equals(this.MimeType, StringComparison.OrdinalIgnoreCase)); - - if (imageCodecInfo != null) - { - image.Save(stream, imageCodecInfo, encoderParameters); - } - } - - return image; - } - - /// - /// Saves the current image to the specified file path. - /// - /// The path to save the image to. - /// The - /// to save. - /// - /// The . - /// - public override Image Save(string path, Image image) - { - // Jpegs can be saved with different settings to include a quality setting for the JPEG compression. - // This improves output compression and quality. - using (EncoderParameters encoderParameters = FormatUtilities.GetEncodingParameters(this.Quality)) - { - ImageCodecInfo imageCodecInfo = - ImageCodecInfo.GetImageEncoders() - .FirstOrDefault(ici => ici.MimeType.Equals(this.MimeType, StringComparison.OrdinalIgnoreCase)); - - if (imageCodecInfo != null) - { - image.Save(path, imageCodecInfo, encoderParameters); - } - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/PngFormat.cs b/old/src/ImageProcessor/Imaging/Formats/PngFormat.cs deleted file mode 100644 index 38cfab429..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/PngFormat.cs +++ /dev/null @@ -1,132 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides the necessary information to support png images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - - using ImageProcessor.Imaging.Quantizers; - using ImageProcessor.Imaging.Quantizers.WuQuantizer; - - /// - /// Provides the necessary information to support png images. - /// - public class PngFormat : FormatBase, IQuantizableImageFormat - { - /// - /// The quantizer for reducing the image palette. - /// - private IQuantizer quantizer = new WuQuantizer(); - - /// - /// Gets the file headers. - /// - public override byte[][] FileHeaders - { - get - { - return new[] { new byte[] { 137, 80, 78, 71 } }; - } - } - - /// - /// Gets the list of file extensions. - /// - public override string[] FileExtensions - { - get - { - return new[] { "png" }; - } - } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public override string MimeType - { - get - { - return "image/png"; - } - } - - /// - /// Gets the . - /// - public override ImageFormat ImageFormat - { - get - { - return ImageFormat.Png; - } - } - - /// - /// Gets or sets the quantizer for reducing the image palette. - /// - public IQuantizer Quantizer - { - get - { - return this.quantizer; - } - - set - { - this.quantizer = value; - } - } - - /// - /// Gets or sets the color count. - /// - public int ColorCount { get; set; } - - /// - /// Saves the current image to the specified output stream. - /// - /// The to save the image information to. - /// The to save. - /// - /// The . - /// - public override Image Save(Stream stream, Image image) - { - if (this.IsIndexed) - { - image = this.Quantizer.Quantize(image); - } - - return base.Save(stream, image); - } - - /// - /// Saves the current image to the specified file path. - /// - /// The path to save the image to. - /// The - /// to save. - /// - /// The . - /// - public override Image Save(string path, Image image) - { - if (this.IsIndexed) - { - image = this.Quantizer.Quantize(image); - } - - return base.Save(path, image); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Formats/TiffFormat.cs b/old/src/ImageProcessor/Imaging/Formats/TiffFormat.cs deleted file mode 100644 index 59229dd88..000000000 --- a/old/src/ImageProcessor/Imaging/Formats/TiffFormat.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides the necessary information to support tiff images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Formats -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - - /// - /// Provides the necessary information to support tiff images. - /// - public class TiffFormat : FormatBase - { - /// - /// Gets the file headers. - /// - public override byte[][] FileHeaders - { - get - { - return new[] - { - new byte[] { 73, 73, 42, 0 }, - new byte[] { 77, 77, 0, 42 } - }; - } - } - - /// - /// Gets the list of file extensions. - /// - public override string[] FileExtensions - { - get - { - return new[] { "tiff", "tif" }; - } - } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public override string MimeType - { - get - { - return "image/tiff"; - } - } - - /// - /// Gets the . - /// - public override ImageFormat ImageFormat - { - get - { - return ImageFormat.Tiff; - } - } - - /// - /// Applies the given processor the current image. - /// - /// The processor delegate. - /// The . - public override void ApplyProcessor(Func processor, ImageFactory factory) - { - base.ApplyProcessor(processor, factory); - - // Set the property item information from any Exif metadata. - // We do this here so that they can be changed between processor methods. - if (factory.PreserveExifData) - { - foreach (KeyValuePair propertItem in factory.ExifPropertyItems) - { - factory.Image.SetPropertyItem(propertItem.Value); - } - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/GaussianLayer.cs b/old/src/ImageProcessor/Imaging/GaussianLayer.cs deleted file mode 100644 index 20d6a059a..000000000 --- a/old/src/ImageProcessor/Imaging/GaussianLayer.cs +++ /dev/null @@ -1,185 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// A Gaussian layer for applying sharpening and blurring methods to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System; - - /// - /// A Gaussian layer for applying sharpening and blurring methods to an image. - /// - public class GaussianLayer - { - /// - /// The size. - /// - private int size; - - /// - /// The sigma. - /// - private double sigma; - - /// - /// The threshold. - /// - private int threshold; - - /// - /// Initializes a new instance of the class. - /// - public GaussianLayer() - { - this.Size = 3; - this.Sigma = 1.4; - this.Threshold = 0; - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The size to set the Gaussian kernel to. - /// - /// - /// The Sigma value (standard deviation) for Gaussian function used to calculate the kernel. - /// - /// - /// The threshold value, which is added to each weighted sum of pixels. - /// - public GaussianLayer(int size, double sigma = 1.4, int threshold = 0) - { - this.Size = size; - this.Sigma = sigma; - this.Threshold = threshold; - } - - /// - /// Gets or sets the size of the Gaussian kernel. - /// - /// - /// If set to a value below 0, the property will be set to 0. - /// - /// - /// - public int Size - { - get - { - return this.size; - } - - set - { - if (value < 0) - { - value = 0; - } - - this.size = value; - } - } - - /// - /// Gets or sets the sigma value (standard deviation) for Gaussian function used to calculate the kernel. - /// - /// - /// If set to a value below 0, the property will be set to 0. - /// - /// - /// - public double Sigma - { - get - { - return this.sigma; - } - - set - { - if (value < 0) - { - value = 0; - } - - this.sigma = value; - } - } - - /// - /// Gets or sets the threshold value, which is added to each weighted sum of pixels. - /// - /// - /// If set to a value below 0, the property will be set to 0. - /// - /// - /// - public int Threshold - { - get - { - return this.threshold; - } - - set - { - if (value < 0) - { - value = 0; - } - - this.threshold = value; - } - } - - /// - /// Returns a value that indicates whether the specified object is an - /// object that is equivalent to - /// this object. - /// - /// - /// The object to test. - /// - /// - /// True if the given object is an object that is equivalent to - /// this object; otherwise, false. - /// - public override bool Equals(object obj) - { - GaussianLayer gaussianLayer = obj as GaussianLayer; - - if (gaussianLayer == null) - { - return false; - } - - return this.Size == gaussianLayer.Size - && Math.Abs(this.Sigma - gaussianLayer.Sigma) < 0.0001 - && this.Threshold == gaussianLayer.Threshold; - } - - /// - /// Serves as a hash function for a particular type. - /// - /// - /// A hash code for the current . - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.Size; - hashCode = (hashCode * 397) ^ this.Size.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Threshold; - return hashCode; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Helpers/Adjustments.cs b/old/src/ImageProcessor/Imaging/Helpers/Adjustments.cs deleted file mode 100644 index 641537399..000000000 --- a/old/src/ImageProcessor/Imaging/Helpers/Adjustments.cs +++ /dev/null @@ -1,221 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides reusable adjustment methods to apply to images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Helpers -{ - using System; - using System.Drawing; - using System.Drawing.Imaging; - using System.Threading.Tasks; - - using ImageProcessor.Common.Extensions; - - /// - /// Provides reusable adjustment methods to apply to images. - /// - public static class Adjustments - { - /// - /// Adjusts the alpha component of the given image. - /// - /// - /// The source to adjust. - /// - /// - /// The percentage value between 0 and 100 for adjusting the opacity. - /// - /// The rectangle to define the bounds of the area to adjust the opacity. - /// If null then the effect is applied to the entire image. - /// - /// The with the alpha component adjusted. - /// - /// - /// Thrown if the percentage value falls outside the acceptable range. - /// - public static Bitmap Alpha(Image source, int percentage, Rectangle? rectangle = null) - { - if (percentage > 100 || percentage < 0) - { - throw new ArgumentOutOfRangeException("percentage", "Percentage should be between 0 and 100."); - } - - float factor = (float)percentage / 100; - int width = source.Width; - int height = source.Height; - - // Traditional examples using a color matrix alter the rgb values also. - using (FastBitmap bitmap = new FastBitmap(source)) - { - // Loop through the pixels. - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - // ReSharper disable AccessToDisposedClosure - Color color = bitmap.GetPixel(x, y); - bitmap.SetPixel(x, y, Color.FromArgb(Convert.ToInt32(color.A * factor), color.R, color.G, color.B)); - // ReSharper restore AccessToDisposedClosure - } - }); - } - - return (Bitmap)source; - } - - /// - /// Adjusts the brightness component of the given image. - /// - /// - /// The source to adjust. - /// - /// - /// The threshold value between -100 and 100 for adjusting the brightness. - /// - /// The rectangle to define the bounds of the area to adjust the brightness. - /// If null then the effect is applied to the entire image. - /// - /// The with the brightness adjusted. - /// - /// - /// Thrown if the threshold value falls outside the acceptable range. - /// - public static Bitmap Brightness(Image source, int threshold, Rectangle? rectangle = null) - { - if (threshold > 100 || threshold < -100) - { - throw new ArgumentOutOfRangeException("threshold", "Threshold should be between -100 and 100."); - } - - float brightnessFactor = (float)threshold / 100; - Rectangle bounds = rectangle ?? new Rectangle(0, 0, source.Width, source.Height); - - ColorMatrix colorMatrix = - new ColorMatrix( - new[] - { - new float[] { 1, 0, 0, 0, 0 }, - new float[] { 0, 1, 0, 0, 0 }, - new float[] { 0, 0, 1, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new[] { brightnessFactor, brightnessFactor, brightnessFactor, 0, 1 } - }); - - using (Graphics graphics = Graphics.FromImage(source)) - { - using (ImageAttributes imageAttributes = new ImageAttributes()) - { - imageAttributes.SetColorMatrix(colorMatrix); - graphics.DrawImage(source, bounds, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, imageAttributes); - } - } - - return (Bitmap)source; - } - - /// - /// Adjusts the contrast component of the given image. - /// - /// - /// The source to adjust. - /// - /// - /// The threshold value between -100 and 100 for adjusting the contrast. - /// - /// The rectangle to define the bounds of the area to adjust the contrast. - /// If null then the effect is applied to the entire image. - /// - /// The with the contrast adjusted. - /// - /// - /// Thrown if the threshold value falls outside the acceptable range. - /// - public static Bitmap Contrast(Image source, int threshold, Rectangle? rectangle = null) - { - if (threshold > 100 || threshold < -100) - { - throw new ArgumentOutOfRangeException("threshold", "Threshold should be between -100 and 100."); - } - - Rectangle bounds = rectangle ?? new Rectangle(0, 0, source.Width, source.Height); - - float contrastFactor = (float)threshold / 100; - - // Stop at -1 to prevent inversion. - contrastFactor++; - float factorTransform = 0.5f * (1.0f - contrastFactor); - - ColorMatrix colorMatrix = - new ColorMatrix( - new[] - { - new[] { contrastFactor, 0, 0, 0, 0 }, - new[] { 0, contrastFactor, 0, 0, 0 }, - new[] { 0, 0, contrastFactor, 0, 0 }, - new float[] { 0, 0, 0, 1, 0 }, - new[] { factorTransform, factorTransform, factorTransform, 0, 1 } - }); - - using (Graphics graphics = Graphics.FromImage(source)) - { - using (ImageAttributes imageAttributes = new ImageAttributes()) - { - imageAttributes.SetColorMatrix(colorMatrix); - graphics.DrawImage(source, bounds, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, imageAttributes); - } - } - - return (Bitmap)source; - } - - /// - /// Adjust the gamma (intensity of the light) component of the given image. - /// - /// - /// The source to adjust. - /// - /// - /// The value to adjust the gamma by (typically between .2 and 5). - /// - /// - /// The with the gamma adjusted. - /// - /// - /// Thrown if the value falls outside the acceptable range. - /// - public static Bitmap Gamma(Image source, float value) - { - if (value > 5 || value < .1) - { - throw new ArgumentOutOfRangeException("value", "Value should be between .1 and 5."); - } - - int width = source.Width; - int height = source.Height; - Bitmap destination = new Bitmap(width, height); - destination.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - Rectangle rectangle = new Rectangle(0, 0, width, height); - using (Graphics graphics = Graphics.FromImage(destination)) - { - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetGamma(value); - graphics.DrawImage(source, rectangle, 0, 0, width, height, GraphicsUnit.Pixel, attributes); - } - } - - source.Dispose(); - return destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Helpers/Effects.cs b/old/src/ImageProcessor/Imaging/Helpers/Effects.cs deleted file mode 100644 index a328e19a6..000000000 --- a/old/src/ImageProcessor/Imaging/Helpers/Effects.cs +++ /dev/null @@ -1,242 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides reusable effect methods to apply to images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Helpers -{ - using System; - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Threading.Tasks; - - using ImageProcessor.Imaging.Filters.EdgeDetection; - using ImageProcessor.Imaging.Filters.Photo; - - /// - /// Provides reusable effect methods to apply to images. - /// - public static class Effects - { - /// - /// Adds a vignette effect to the source image based on the given color. - /// - /// - /// The source. - /// - /// - /// to base the vignette on. - /// - /// - /// The rectangle to define the bounds of the area to vignette. If null then the effect is applied - /// to the entire image. - /// - /// - /// Whether to invert the vignette. - /// - /// - /// The with the vignette applied. - /// - public static Bitmap Vignette(Image source, Color baseColor, Rectangle? rectangle = null, bool invert = false) - { - using (Graphics graphics = Graphics.FromImage(source)) - { - Rectangle bounds = rectangle ?? new Rectangle(0, 0, source.Width, source.Height); - Rectangle ellipsebounds = bounds; - - // Increase the rectangle size by the difference between the rectangle dimensions and sqrt(2)/2 * the rectangle dimensions. - // Why sqrt(2)/2? Because the point (sqrt(2)/2, sqrt(2)/2) is the 45 degree angle point on a unit circle. Scaling by the width - // and height gives the distance needed to inflate the rectangle to make sure it's fully covered. - ellipsebounds.Offset(-ellipsebounds.X, -ellipsebounds.Y); - int x = ellipsebounds.Width - (int)Math.Floor(.70712 * ellipsebounds.Width); - int y = ellipsebounds.Height - (int)Math.Floor(.70712 * ellipsebounds.Height); - ellipsebounds.Inflate(x, y); - - using (GraphicsPath path = new GraphicsPath()) - { - path.AddEllipse(ellipsebounds); - using (PathGradientBrush brush = new PathGradientBrush(path)) - { - // Fill a rectangle with an elliptical gradient brush that goes from transparent to opaque. - // This has the effect of painting the far corners with the given color and shade less on the way in to the centre. - Color centerColor; - Color edgeColor; - if (invert) - { - centerColor = Color.FromArgb(50, baseColor.R, baseColor.G, baseColor.B); - edgeColor = Color.FromArgb(0, baseColor.R, baseColor.G, baseColor.B); - } - else - { - centerColor = Color.FromArgb(0, baseColor.R, baseColor.G, baseColor.B); - edgeColor = Color.FromArgb(255, baseColor.R, baseColor.G, baseColor.B); - } - - brush.WrapMode = WrapMode.Tile; - brush.CenterColor = centerColor; - brush.SurroundColors = new[] { edgeColor }; - - Blend blend = new Blend - { - Positions = new[] { 0.0f, 0.2f, 0.4f, 0.6f, 0.8f, 1.0F }, - Factors = new[] { 0.0f, 0.5f, 1f, 1f, 1.0f, 1.0f } - }; - - brush.Blend = blend; - - Region oldClip = graphics.Clip; - graphics.Clip = new Region(bounds); - graphics.FillRectangle(brush, ellipsebounds); - graphics.Clip = oldClip; - } - } - } - - return (Bitmap)source; - } - - /// - /// Adds a diffused glow (inverted vignette) effect to the source image based on the given color. - /// - /// The source. - /// to base the vignette on. - /// The rectangle to define the bounds of the area to vignette. If null then the effect is applied - /// to the entire image. - /// The with the vignette applied. - public static Bitmap Glow(Image source, Color baseColor, Rectangle? rectangle = null) - { - return Vignette(source, baseColor, rectangle, true); - } - - /// - /// Applies the given image mask to the source. - /// - /// - /// The source . - /// - /// - /// The mask . - /// - /// - /// Thrown if the two images are of different size. - /// - /// - /// The masked . - /// - public static Bitmap ApplyMask(Image source, Image mask) - { - if (mask.Size != source.Size) - { - throw new ArgumentException(); - } - - int width = mask.Width; - int height = mask.Height; - - Bitmap toMask = new Bitmap(source); - - // Loop through and replace the alpha channel - using (FastBitmap maskBitmap = new FastBitmap(mask)) - { - using (FastBitmap sourceBitmap = new FastBitmap(toMask)) - { - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - // ReSharper disable AccessToDisposedClosure - Color maskColor = maskBitmap.GetPixel(x, y); - Color sourceColor = sourceBitmap.GetPixel(x, y); - - if (sourceColor.A != 0) - { - sourceBitmap.SetPixel(x, y, Color.FromArgb(maskColor.A, sourceColor.R, sourceColor.G, sourceColor.B)); - } - - // ReSharper restore AccessToDisposedClosure - } - }); - } - } - - // Ensure the background is cleared out on non alpha supporting formats. - Bitmap clear = new Bitmap(width, height); - clear.SetResolution(source.HorizontalResolution, source.VerticalResolution); - using (Graphics graphics = Graphics.FromImage(clear)) - { - graphics.Clear(Color.Transparent); - graphics.DrawImage(toMask, 0, 0, width, height); - } - - toMask.Dispose(); - return clear; - } - - /// - /// Traces the edges of a given . - /// - /// - /// The source . - /// - /// - /// The destination . - /// - /// - /// The threshold (between 0 and 255). - /// - /// - /// The a new instance of traced. - /// - public static Bitmap Trace(Image source, Image destination, byte threshold = 0) - { - int width = source.Width; - int height = source.Height; - - // Grab the edges converting to greyscale, and invert the colors. - ConvolutionFilter filter = new ConvolutionFilter(new SobelEdgeFilter(), true); - - using (Bitmap temp = filter.Process2DFilter(source)) - { - destination = new InvertMatrixFilter().TransformImage(temp, destination); - - // Darken it slightly to aid detection - destination = Adjustments.Brightness(destination, -5); - } - - // Loop through and replace any colors more white than the threshold - // with a transparent one. - using (FastBitmap destinationBitmap = new FastBitmap(destination)) - { - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - // ReSharper disable AccessToDisposedClosure - Color color = destinationBitmap.GetPixel(x, y); - if (color.B >= threshold) - { - destinationBitmap.SetPixel(x, y, Color.Transparent); - } - // ReSharper restore AccessToDisposedClosure - } - }); - } - - // Darken it again to average out the color. - destination = Adjustments.Brightness(destination, -5); - - return (Bitmap)destination; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Helpers/ImageMaths.cs b/old/src/ImageProcessor/Imaging/Helpers/ImageMaths.cs deleted file mode 100644 index 97338bfa3..000000000 --- a/old/src/ImageProcessor/Imaging/Helpers/ImageMaths.cs +++ /dev/null @@ -1,359 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides reusable mathematical methods to apply to images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Helpers -{ - using System; - using System.Drawing; - - using ImageProcessor.Imaging.Colors; - - /// - /// Provides reusable mathematical methods to apply to images. - /// - public static class ImageMaths - { - /// - /// Gets a representing the child centered relative to the parent. - /// - /// - /// The parent . - /// - /// - /// The child . - /// - /// - /// The centered . - /// - public static RectangleF CenteredRectangle(Rectangle parent, Rectangle child) - { - float x = (parent.Width - child.Width) / 2.0F; - float y = (parent.Height - child.Height) / 2.0F; - int width = child.Width; - int height = child.Height; - return new RectangleF(x, y, width, height); - } - - /// - /// Restricts a value to be within a specified range. - /// - /// - /// The The value to clamp. - /// - /// - /// The minimum value. If value is less than min, min will be returned. - /// - /// - /// The maximum value. If value is greater than max, max will be returned. - /// - /// - /// The to clamp. - /// - /// - /// The representing the clamped value. - /// - public static T Clamp(T value, T min, T max) where T : IComparable - { - if (value.CompareTo(min) < 0) - { - return min; - } - - if (value.CompareTo(max) > 0) - { - return max; - } - - return value; - } - - /// - /// Returns value indicating whether the given number is with in the minimum and maximum - /// given range. - /// - /// - /// The The value to clamp. - /// - /// - /// If - /// The minimum range value. - /// - /// - /// The maximum range value. - /// - /// - /// Whether to include the minimum and maximum values. - /// Defaults to true. - /// - /// - /// The to test. - /// - /// - /// True if the value falls within the maximum and minimum; otherwise, false. - /// - public static bool InRange(T value, T min, T max, bool include = true) where T : IComparable - { - if (include) - { - return (value.CompareTo(min) >= 0) && (value.CompareTo(max) <= 0); - } - - return (value.CompareTo(min) > 0) && (value.CompareTo(max) < 0); - } - - /// - /// Returns the given degrees converted to radians. - /// - /// - /// The angle in degrees. - /// - /// - /// The representing the degree as radians. - /// - public static double DegreesToRadians(double angleInDegrees) - { - return angleInDegrees * (Math.PI / 180); - } - - /// - /// Gets the bounding from the given points. - /// - /// - /// The designating the top left position. - /// - /// - /// The designating the bottom right position. - /// - /// - /// The bounding . - /// - public static Rectangle GetBoundingRectangle(Point topLeft, Point bottomRight) - { - return new Rectangle(topLeft.X, topLeft.Y, bottomRight.X - topLeft.X, bottomRight.Y - topLeft.Y); - } - - /// - /// Calculates the new size after rotation. - /// - /// The width of the image. - /// The height of the image. - /// The angle of rotation. - /// The new size of the image - public static Rectangle GetBoundingRotatedRectangle(int width, int height, float angleInDegrees) - { - // Check first clockwise. - double radians = DegreesToRadians(angleInDegrees); - double radiansSin = Math.Sin(radians); - double radiansCos = Math.Cos(radians); - double width1 = (height * radiansSin) + (width * radiansCos); - double height1 = (width * radiansSin) + (height * radiansCos); - - // Find dimensions in the other direction - radiansSin = Math.Sin(-radians); - radiansCos = Math.Cos(-radians); - double width2 = (height * radiansSin) + (width * radiansCos); - double height2 = (width * radiansSin) + (height * radiansCos); - - // Get the external vertex for the rotation - Rectangle result = new Rectangle( - 0, - 0, - Convert.ToInt32(Math.Max(Math.Abs(width1), Math.Abs(width2))), - Convert.ToInt32(Math.Max(Math.Abs(height1), Math.Abs(height2)))); - - return result; - } - - /// - /// Finds the bounding rectangle based on the first instance of any color component other - /// than the given one. - /// - /// - /// The to search within. - /// - /// - /// The color component value to remove. - /// - /// - /// The channel to test against. - /// - /// - /// The . - /// - public static Rectangle GetFilteredBoundingRectangle(Image bitmap, byte componentValue, RgbaComponent channel = RgbaComponent.B) - { - int width = bitmap.Width; - int height = bitmap.Height; - Point topLeft = new Point(); - Point bottomRight = new Point(); - - Func delegateFunc; - - // Determine which channel to check against - switch (channel) - { - case RgbaComponent.R: - delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).R != b; - break; - - case RgbaComponent.G: - delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).G != b; - break; - - case RgbaComponent.A: - delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).A != b; - break; - - default: - delegateFunc = (fastBitmap, x, y, b) => fastBitmap.GetPixel(x, y).B != b; - break; - } - - Func getMinY = fastBitmap => - { - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - if (delegateFunc(fastBitmap, x, y, componentValue)) - { - return y; - } - } - } - - return 0; - }; - - Func getMaxY = fastBitmap => - { - for (int y = height - 1; y > -1; y--) - { - for (int x = 0; x < width; x++) - { - if (delegateFunc(fastBitmap, x, y, componentValue)) - { - return y; - } - } - } - - return height; - }; - - Func getMinX = fastBitmap => - { - for (int x = 0; x < width; x++) - { - for (int y = 0; y < height; y++) - { - if (delegateFunc(fastBitmap, x, y, componentValue)) - { - return x; - } - } - } - - return 0; - }; - - Func getMaxX = fastBitmap => - { - for (int x = width - 1; x > -1; x--) - { - for (int y = 0; y < height; y++) - { - if (delegateFunc(fastBitmap, x, y, componentValue)) - { - return x; - } - } - } - - return height; - }; - - using (FastBitmap fastBitmap = new FastBitmap(bitmap)) - { - topLeft.Y = getMinY(fastBitmap); - topLeft.X = getMinX(fastBitmap); - bottomRight.Y = getMaxY(fastBitmap) + 1; - bottomRight.X = getMaxX(fastBitmap) + 1; - } - - return GetBoundingRectangle(topLeft, bottomRight); - } - - /// - /// Rotates one point around another - /// - /// - /// The point to rotate. - /// The rotation angle in degrees. - /// The centre point of rotation. If not set the point will equal - /// - /// - /// Rotated point - public static Point RotatePoint(Point pointToRotate, double angleInDegrees, Point? centerPoint = null) - { - Point center = centerPoint ?? Point.Empty; - - double angleInRadians = DegreesToRadians(angleInDegrees); - double cosTheta = Math.Cos(angleInRadians); - double sinTheta = Math.Sin(angleInRadians); - return new Point - { - X = - (int)((cosTheta * (pointToRotate.X - center.X)) - - ((sinTheta * (pointToRotate.Y - center.Y)) + center.X)), - Y = - (int)((sinTheta * (pointToRotate.X - center.X)) + - ((cosTheta * (pointToRotate.Y - center.Y)) + center.Y)) - }; - } - - /// - /// Returns the array of matching the bounds of the given rectangle. - /// - /// - /// The to return the points from. - /// - /// - /// The array. - /// - public static Point[] ToPoints(Rectangle rectangle) - { - return new[] - { - new Point(rectangle.Left, rectangle.Top), - new Point(rectangle.Right, rectangle.Top), - new Point(rectangle.Right, rectangle.Bottom), - new Point(rectangle.Left, rectangle.Bottom) - }; - } - - /// - /// Calculates the zoom needed after the rotation to ensure the canvas is covered - /// by the rotated image. - /// - /// Width of the image. - /// Height of the image. - /// The angle in degrees. - /// - /// Based on - /// - /// The zoom needed - public static float ZoomAfterRotation(int imageWidth, int imageHeight, float angleInDegrees) - { - Rectangle rectangle = GetBoundingRotatedRectangle(imageWidth, imageHeight, angleInDegrees); - return Math.Max((float)rectangle.Width / imageWidth, (float)rectangle.Height / imageHeight); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Helpers/PixelOperations.cs b/old/src/ImageProcessor/Imaging/Helpers/PixelOperations.cs deleted file mode 100644 index 2393fcace..000000000 --- a/old/src/ImageProcessor/Imaging/Helpers/PixelOperations.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Performs per-pixel operations. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Helpers -{ - using System; - using System.Drawing; - using ImageProcessor.Common.Extensions; - - /// - /// Performs per-pixel operations. - /// - public static class PixelOperations - { - /// - /// Returns the given color adjusted by the given gamma value. - /// - /// - /// The to adjust. - /// - /// - /// The gamma value - Between .1 and 5. - /// - /// - /// The adjusted . - /// - /// - /// Thrown if the given gamma value is out with the acceptable range. - /// - public static Color Gamma(Color color, float value) - { - if (value > 5 || value < .1) - { - throw new ArgumentOutOfRangeException("value", "Value should be between .1 and 5."); - } - - byte[] ramp = new byte[256]; - for (int x = 0; x < 256; ++x) - { - byte val = ((255.0 * Math.Pow(x / 255.0, value)) + 0.5).ToByte(); - ramp[x] = val; - } - - byte r = ramp[color.R]; - byte g = ramp[color.G]; - byte b = ramp[color.B]; - - return Color.FromArgb(color.A, r, g, b); - } - } -} diff --git a/old/src/ImageProcessor/Imaging/ImageLayer.cs b/old/src/ImageProcessor/Imaging/ImageLayer.cs deleted file mode 100644 index 23bd4a75f..000000000 --- a/old/src/ImageProcessor/Imaging/ImageLayer.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the properties required to add an image layer to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System.Drawing; - - /// - /// Encapsulates the properties required to add an image layer to an image. - /// - public class ImageLayer - { - /// - /// The opacity at which to render the text. - /// - private int opacity = 100; - - /// - /// Gets or sets the image. - /// - public Image Image { get; set; } - - /// - /// Gets or sets the size. - /// - public Size Size { get; set; } - - /// - /// Gets or sets the Opacity of the text layer. - /// - public int Opacity - { - get { return this.opacity; } - set { this.opacity = value; } - } - - /// - /// Gets or sets the Position of the text layer. - /// - public Point? Position { get; set; } - - /// - /// Returns a value that indicates whether the specified object is an - /// object that is equivalent to - /// this object. - /// - /// - /// The object to test. - /// - /// - /// True if the given object is an object that is equivalent to - /// this object; otherwise, false. - /// - public override bool Equals(object obj) - { - ImageLayer imageLayer = obj as ImageLayer; - - if (imageLayer == null) - { - return false; - } - - return this.Image == imageLayer.Image - && this.Size == imageLayer.Size - && this.Opacity == imageLayer.Opacity - && this.Position == imageLayer.Position; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.Image.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Size.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Opacity; - hashCode = (hashCode * 397) ^ this.Position.GetHashCode(); - return hashCode; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/MetaData/ExifPropertyTag.cs b/old/src/ImageProcessor/Imaging/MetaData/ExifPropertyTag.cs deleted file mode 100644 index 29bdd1745..000000000 --- a/old/src/ImageProcessor/Imaging/MetaData/ExifPropertyTag.cs +++ /dev/null @@ -1,1192 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The following enum gives descriptions of the property items supported by Windows GDI+. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.MetaData -{ - /// - /// The following enum gives descriptions of the property items supported by Windows GDI+. - /// - /// - public enum ExifPropertyTag - { - /// - /// Null-terminated character string that specifies the name of the person who created the image. - /// - Artist = 0x013B, - - /// - /// Number of bits per color component. See also - /// - BitsPerSample = 0x0102, - - /// - /// Height of the dithering or halftoning matrix. - /// - CellHeight = 0x0109, - - /// - /// Width of the dithering or halftoning matrix. - /// - CellWidth = 0x0108, - - /// - /// Chrominance table. The luminance table and the chrominance table are used to control JPEG quality. - /// A valid luminance or chrominance table has 64 entries. - /// If an image has either a luminance table or a chrominance table, then it must have both tables. - /// - ChrominanceTable = 0x5091, - - /// - /// Color palette (lookup table) for a palette-indexed image. - /// - ColorMap = 0x0140, - - /// - /// Table of values that specify color transfer functions. - /// - ColorTransferFunction = 0x501A, - - /// - /// Compression scheme used for the image data. - /// - Compression = 0x0103, - - /// - /// Null-terminated character string that contains copyright information. - /// - Copyright = 0x8298, - - /// - /// Date and time the image was created. - /// - DateTime = 0x0132, - - /// - /// Null-terminated character string that specifies the name of the document from - /// which the image was scanned. - /// - DocumentName = 0x010D, - - /// - /// Color component values that correspond to a 0 percent dot and a 100 percent dot. - /// - DotRange = 0x0150, - - /// - /// Null-terminated character string that specifies the manufacturer of the - /// equipment used to record the image. - /// - EquipMake = 0x010F, - - /// - /// Null-terminated character string that specifies the model name or model number - /// of the equipment used to record the image. - /// - EquipModel = 0x0110, - - /// - /// Lens aperture. The unit is the APEX value. - /// - ExifAperture = 0x9202, - - /// - /// Brightness value. The unit is the APEX value. Ordinarily it is given - /// in the range of -99.99 to 99.99. - /// - ExifBrightness = 0x9203, - - /// - /// The color filter array (CFA) geometric pattern of the image sensor when a one-chip color - /// area sensor is used. It does not apply to all sensing methods. - /// - ExifCfaPattern = 0xA302, - - /// - /// Color space specifier. Normally sRGB (=1) is used to define the color space - /// based on the PC monitor conditions and environment. If a color space other - /// than sRGB is used, Uncalibrated (=0xFFFF) is set. Image data recorded as - /// Uncalibrated can be treated as sRGB when it is converted to FlashPix. - /// - ExifColorSpace = 0xA001, - - /// - /// Information specific to compressed data. The compression mode used for a - /// compressed image is indicated in unit BPP. - /// - ExifCompBPP = 0x9102, - - /// - /// Information specific to compressed data. The channels of each component are - /// arranged in order from the first component to the fourth. For - /// uncompressed data, the data arrangement is given in the - /// PhotometricInterp tag. - /// - /// However, because PhotometricInterp can only express the order of Y, Cb, and Cr, - /// this tag is provided for cases when compressed data uses components other than - /// Y, Cb, and Cr and to support other sequences. - /// - /// - ExifCompConfig = 0x9101, - - /// - /// Date and time when the image was stored as digital data. If, for example, an image - /// was captured by DSC and at the same time the file was recorded, then DateTimeOriginal - /// and DateTimeDigitized will have the same contents. - /// - /// The format is YYYY:MM:DD HH:MM:SS with time shown in 24-hour format and the date and - /// time separated by one blank character (0x2000). The character string length is 20 bytes - /// including the NULL terminator. When the field is empty, it is treated as unknown. - /// - /// - ExifDTDigitized = 0x9004, - - /// - /// Null-terminated character string that specifies a fraction of a second for the ExifDTDigitized tag. - /// - ExifDTDigSS = 0x9292, - - /// - /// Date and time when the original image data was generated. For a DSC, the date and time when the picture was taken. The format is YYYY:MM:DD HH:MM:SS with time shown in 24-hour format and the date and time separated by one blank character (0x2000). The character string length is 20 bytes including the NULL terminator. When the field is empty, it is treated as unknown. - /// - ExifDTOrig = 0x9003, - - /// - /// Null-terminated character string that specifies a fraction of a second for the tag. - /// - ExifDTOrigSS = 0x9291, - - /// - /// Null-terminated character string that specifies a fraction of a second for the tag. - /// - ExifDTSubsec = 0x9290, - - /// - /// Exposure bias. The unit is the APEX value. Ordinarily it is given in the range -99.99 to 99.99. - /// - ExifExposureBias = 0x9204, - - /// - /// Exposure index selected on the camera or input device at the time the image was captured. - /// - ExifExposureIndex = 0xA215, - - /// - /// Class of the program used by the camera to set exposure when the picture is taken. - /// - ExifExposureProg = 0x8822, - - /// - /// Exposure time, measured in seconds. - /// - ExifExposureTime = 0x829A, - - /// - /// The image source. If a DSC recorded the image, the value of this tag is 3. - /// - ExifFileSource = 0xA300, - - /// - /// Flash status. This tag is recorded when an image is taken using a strobe light (flash). Bit 0 indicates the flash firing status, and bits 1 and 2 indicate the flash return status. - /// - ExifFlash = 0x9209, - - /// - /// Strobe energy, in Beam Candle Power Seconds (BCPS), at the time the image was captured. - /// - ExifFlashEnergy = 0xA20B, - - /// - /// F number. - /// - ExifFNumber = 0x829D, - - /// - /// Actual focal length, in millimeters, of the lens. Conversion is not made to the focal length of a 35 millimeter film camera. - /// - ExifFocalLength = 0x920A, - - /// - /// Unit of measure for and . - /// - ExifFocalResUnit = 0xA210, - - /// - /// Number of pixels in the image width (x) direction per unit on the camera focal plane. The unit is specified - /// in . - /// - ExifFocalXRes = 0xA20E, - - /// - /// Number of pixels in the image height (y) direction per unit on the camera focal plane. The unit is specified - /// in . - /// - ExifFocalYRes = 0xA20F, - - /// - /// FlashPix format version supported by an FPXR file. If the FPXR function supports FlashPix format version 1.0, - /// this is indicated similarly to by recording 0100 as a 4-byte ASCII string. - /// Because the type is , there is no NULL terminator. - /// - ExifFPXVer = 0xA000, - - /// - /// Private tag used by GDI+. Not for public use. GDI+ uses this tag to locate Exif specific information. - /// - ExifIFD = 0x8769, - - /// - /// Offset to a block of property items that contain interoperability information. - /// - ExifInterop = 0xA005, - - /// - /// ISO speed and ISO latitude of the camera or input device as specified in ISO 12232. - /// - ExifISOSpeed = 0x8827, - - /// - /// Type of light source. - /// - ExifLightSource = 0x9208, - - /// - /// Note tag. A tag used by manufacturers of EXIF writers to record information. The contents are up to the manufacturer. - /// - ExifMakerNote = 0x927C, - - /// - /// Smallest F number of the lens. The unit is the APEX value. Ordinarily it is given in the range of 00.00 to 99.99, but it is not limited to this range. - /// - ExifMaxAperture = 0x9205, - - /// - /// Metering mode. - /// - ExifMeteringMode = 0x9207, - - /// - /// Optoelectronic conversion function (OECF) specified in ISO 14524. The OECF is the relationship between the camera optical input and the image values. - /// - ExifOECF = 0x8828, - - /// - /// Information specific to compressed data. When a compressed file is recorded, the valid width of the meaningful image must be recorded in this tag, whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. - /// - ExifPixXDim = 0xA002, - - /// - /// Information specific to compressed data. When a compressed file is recorded, the valid height of the meaningful image must be recorded in this tag whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. Because data padding is unnecessary in the vertical direction, the number of lines recorded in this valid image height tag will be the same as that recorded in the SOF. - /// - ExifPixYDim = 0xA003, - - /// - /// The name of an audio file related to the image data. The only relational information recorded is the EXIF audio file name and extension (an ASCII string that consists of 8 characters plus a period (.), plus 3 characters). The path is not recorded. When you use this tag, audio files must be recorded in conformance with the EXIF audio format. Writers can also store audio data within APP2 as FlashPix extension stream data. - /// - ExifRelatedWav = 0xA004, - - /// - /// The type of scene. If a DSC recorded the image, the value of this tag must be set to 1, indicating that the image was directly photographed. - /// - ExifSceneType = 0xA301, - - /// - /// Image sensor type on the camera or input device. - /// - ExifSensingMethod = 0xA217, - - /// - /// Shutter speed. The unit is the Additive System of Photographic Exposure (APEX) value. - /// - ExifShutterSpeed = 0x9201, - - /// - /// Camera or input device spatial frequency table and SFR values in the image width, image height, and diagonal direction, as specified in ISO 12233. - /// - ExifSpatialFR = 0xA20C, - - /// - /// Null-terminated character string that specifies the spectral sensitivity of each channel of the camera used. The string is compatible with the standard developed by the ASTM Technical Committee. - /// - ExifSpectralSense = 0x8824, - - /// - /// Distance to the subject, measured in meters. - /// - ExifSubjectDist = 0x9206, - - /// - /// Location of the main subject in the scene. The value of this tag represents the pixel at the center - /// of the main subject relative to the left edge. The first value indicates the column number, and - /// the second value indicates the row number. - /// - ExifSubjectLoc = 0xA214, - - /// - /// Comment tag. A tag used by EXIF users to write keywords or comments about the image besides those - /// in and without the character-code limitations of - /// the tag. - /// - ExifUserComment = 0x9286, - - /// - /// Version of the EXIF standard supported. Nonexistence of this field is taken to mean non-conformance to the - /// standard. Conformance to the standard is indicated by recording 0210 as a 4-byte ASCII string. - /// Because the type is , there is no NULL terminator. - /// - ExifVer = 0x9000, - - /// - /// Number of extra color components. For example, one extra component might hold an alpha value. - /// - ExtraSamples = 0x0152, - - /// - /// Logical order of bits in a byte. - /// - FillOrder = 0x010A, - - /// - /// Time delay, in hundredths of a second, between two frames in an animated GIF image. - /// - FrameDelay = 0x5100, - - /// - /// For each string of contiguous unused bytes, the number of bytes in that string. - /// - FreeByteCounts = 0x0121, - - /// - /// For each string of contiguous unused bytes, the byte offset of that string. - /// - FreeOffset = 0x0120, - - /// - /// Gamma value attached to the image. The gamma value is stored as a rational number (pair of long) with a numerator of 100000. For example, a gamma value of 2.2 is stored as the pair (100000, 45455). - /// - Gamma = 0x0301, - - /// - /// Color palette for an indexed bitmap in a GIF image. - /// - GlobalPalette = 0x5102, - - /// - /// Altitude, in meters, based on the reference altitude specified by . - /// - GpsAltitude = 0x0006, - - /// - /// Reference altitude, in meters. - /// - GpsAltitudeRef = 0x0005, - - /// - /// Bearing to the destination point. The range of values is from 0.00 to 359.99. - /// - GpsDestBear = 0x0018, - - /// - /// Null-terminated character string that specifies the reference used for giving the bearing to the destination point. T specifies true direction, and M specifies magnetic direction. - /// - GpsDestBearRef = 0x0017, - - /// - /// Distance to the destination point. - /// - GpsDestDist = 0x001A, - - /// - /// Null-terminated character string that specifies the unit used to express the distance to the destination point. - /// K, M, and N represent kilometers, miles, and knots respectively. - /// - GpsDestDistRef = 0x0019, - - /// - /// Latitude of the destination point. The latitude is expressed as three rational values giving the degrees, - /// minutes, and seconds respectively. When degrees, minutes, and seconds are expressed, the format is - /// dd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to - /// two decimal places, the format is dd/1, mmmm/100, 0/1. - /// - GpsDestLat = 0x0014, - - /// - /// Null-terminated character string that specifies whether the latitude of the destination point is north or south - /// latitude. N specifies north latitude, and S specifies south latitude. - /// - GpsDestLatRef = 0x0013, - - /// - /// Longitude of the destination point. The longitude is expressed as three rational values giving the degrees, minutes, and seconds respectively. When degrees, minutes, and seconds are expressed, the format is ddd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to two decimal places, the format is ddd/1, mmmm/100, 0/1. - /// - GpsDestLong = 0x0016, - - /// - /// Null-terminated character string that specifies whether the longitude of the destination point is east or west longitude. E specifies east longitude, and W specifies west longitude. - /// - GpsDestLongRef = 0x0015, - - /// - /// GPS DOP (data degree of precision). An HDOP value is written during 2-D measurement, and a PDOP value is written during 3-D measurement. - /// - GpsGpsDop = 0x000B, - - /// - /// Null-terminated character string that specifies the GPS measurement mode. 2 specifies 2-D measurement, and 3 specifies 3-D measurement. - /// - GpsGpsMeasureMode = 0x000A, - - /// - /// Null-terminated character string that specifies the GPS satellites used for measurements. This tag can be used to specify the ID number, angle of elevation, azimuth, SNR, and other information about each satellite. The format is not specified. If the GPS receiver is incapable of taking measurements, the value of the tag must be set to NULL. - /// - GpsGpsSatellites = 0x0008, - - /// - /// Null-terminated character string that specifies the status of the GPS receiver when the image is recorded. A means measurement is in progress, and V means the measurement is Interoperability. - /// - GpsGpsStatus = 0x0009, - - /// - /// Time as coordinated universal time (UTC). The value is expressed as three rational numbers that give the hour, minute, and second. - /// - GpsGpsTime = 0x0007, - - /// - /// Offset to a block of GPS property items. Property items whose tags have the prefix Gps are stored in the GPS block. - /// The GPS property items are defined in the EXIF specification. GDI+ uses this tag to locate GPS information, - /// but GDI+ does not expose this tag for public use. - /// - GpsIFD = 0x8825, - - /// - /// Direction of the image when it was captured. The range of values is from 0.00 to 359.99. - /// - GpsImgDir = 0x0011, - - /// - /// Null-terminated character string that specifies the reference for the direction of the image when it is captured. T specifies true direction, and M specifies magnetic direction. - /// - GpsImgDirRef = 0x0010, - - /// - /// Latitude. Latitude is expressed as three rational values giving the degrees, minutes, and seconds respectively. When degrees, minutes, and seconds are expressed, the format is dd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to two decimal places, the format is dd/1, mmmm/100, 0/1. - /// - GpsLatitude = 0x0002, - - /// - /// Null-terminated character string that specifies whether the longitude is east or west longitude. - /// E specifies east longitude, and W specifies west longitude. - /// - GpsLatitudeRef = 0x0001, - - /// - /// Longitude. Longitude is expressed as three rational values giving the degrees, minutes, and seconds - /// respectively. When degrees, minutes and seconds are expressed, the format is ddd/1, mm/1, ss/1. - /// When degrees and minutes are used and, for example, fractions of minutes are given up to two - /// decimal places, the format is ddd/1, mmmm/100, 0/1. - /// - GpsLongitude = 0x0004, - - /// - /// Null-terminated character string that specifies whether the longitude is east or west longitude. - /// E specifies east longitude, and W specifies west longitude. - /// - GpsLongitudeRef = 0x0003, - - /// - /// Null-terminated character string that specifies geodetic survey data used by the GPS receiver. - /// If the survey data is restricted to Japan, the value of this tag is TOKYO or WGS-84. - /// - GpsMapDatum = 0x0012, - - /// - /// Speed of the GPS receiver movement. - /// - GpsSpeed = 0x000D, - - /// - /// Null-terminated character string that specifies the unit used to express the GPS receiver speed of movement. - /// K, M, and N represent kilometers per hour, miles per hour, and knots respectively. - /// - GpsSpeedRef = 0x000C, - - /// - /// Direction of GPS receiver movement. The range of values is from 0.00 to 359.99. - /// - GpsTrack = 0x000F, - - /// - /// Null-terminated character string that specifies the reference for giving the direction of - /// GPS receiver movement. T specifies true direction, and M specifies magnetic direction. - /// - GpsTrackRef = 0x000E, - - /// - /// Version of the Global Positioning Systems (GPS) IFD, given as 2.0.0.0. This tag is mandatory when - /// the tag is present. When the version is 2.0.0.0, the tag value is 0x02000000. - /// - GpsVer = 0x0000, - - /// - /// For each possible pixel value in a grayscale image, the optical density of that pixel value. - /// - GrayResponseCurve = 0x0123, - - /// - /// Precision of the number specified by . 1 specifies tenths, - /// 2 specifies hundredths, 3 specifies thousandths, and so on. - /// - GrayResponseUnit = 0x0122, - - /// - /// Block of information about grids and guides. - /// - GridSize = 0x5011, - - /// - /// Angle for screen. - /// - HalftoneDegree = 0x500C, - - /// - /// Information used by the halftone function. - /// - HalftoneHints = 0x0141, - - /// - /// Ink's screen frequency, in lines per inch. - /// - HalftoneLPI = 0x500A, - - /// - /// Units for the screen frequency. - /// - HalftoneLPIUnit = 0x500B, - - /// - /// Miscellaneous halftone information. - /// - HalftoneMisc = 0x500E, - - /// - /// Boolean value that specifies whether to use the printer's default screens. - /// - HalftoneScreen = 0x500F, - - /// - /// Shape of the halftone dots. - /// - HalftoneShape = 0x500D, - - /// - /// Null-terminated character string that specifies the computer and/or operating system used to create the image. - /// - HostComputer = 0x013C, - - /// - /// ICC profile embedded in the image. - /// - ICCProfile = 0x8773, - - /// - /// Null-terminated character string that identifies an ICC profile. - /// - ICCProfileDescriptor = 0x0302, - - /// - /// Null-terminated character string that specifies the title of the image. - /// - ImageDescription = 0x010E, - - /// - /// Number of pixel rows. - /// - ImageHeight = 0x0101, - - /// - /// Null-terminated character string that specifies the title of the image. - /// - ImageTitle = 0x0320, - - /// - /// Number of pixels per row. - /// - ImageWidth = 0x0100, - - /// - /// Index of the background color in the palette of a GIF image. - /// - IndexBackground = 0x5103, - - /// - /// Index of the transparent color in the palette of a GIF image. - /// - IndexTransparent = 0x5104, - - /// - /// Sequence of concatenated, null-terminated, character strings that specify the names of the - /// inks used in a separated image. - /// - InkNames = 0x014D, - - /// - /// Set of inks used in a separated image. - /// - InkSet = 0x014C, - - /// - /// For each color component, the offset to the AC Huffman table for that component. - /// See also . - /// - JPEGACTables = 0x0209, - - /// - /// For each color component, the offset to the DC Huffman table (or lossless Huffman table) for that - /// component. See also . - /// - JPEGDCTables = 0x0208, - - /// - /// Offset to the start of a JPEG bitstream. - /// - JPEGInterFormat = 0x0201, - - /// - /// Length, in bytes, of the JPEG bitstream. - /// - JPEGInterLength = 0x0202, - - /// - /// For each color component, a lossless predictor-selection value for that component. - /// See also . - /// - JPEGLosslessPredictors = 0x0205, - - /// - /// For each color component, a point transformation value for that component. - /// See also . - /// - JPEGPointTransforms = 0x0206, - - /// - /// JPEG compression process. - /// - JPEGProc = 0x0200, - - /// - /// For each color component, the offset to the quantization table for that - /// component. See also . - /// - JPEGQTables = 0x0207, - - /// - /// Private tag used by the Adobe Photoshop format. Not for public use. - /// - JPEGQuality = 0x5010, - - /// - /// Length of the restart interval. - /// - JPEGRestartInterval = 0x0203, - - /// - /// For an animated GIF image, the number of times to display the animation. - /// A value of 0 specifies that the animation should be displayed infinitely. - /// - LoopCount = 0x5101, - - /// - /// Luminance table. The luminance table and the chrominance table are used to control JPEG quality. - /// A valid luminance or chrominance table has 64 entries of type . - /// If an image has either a luminance table or a chrominance table, then it must have both tables. - /// - LuminanceTable = 0x5090, - - /// - /// For each color component, the maximum value assigned to that component. - /// See also . - /// - MaxSampleValue = 0x0119, - - /// - /// For each color component, the minimum value assigned to that component. - /// See also . - /// - MinSampleValue = 0x0118, - - /// - /// Type of data in a subfile. - /// - NewSubfileType = 0x00FE, - - /// - /// The number of inks. - /// - NumberOfInks = 0x014E, - - /// - /// Image orientation viewed in terms of rows and columns. - /// - Orientation = 0x0112, - - /// - /// Null-terminated character string that specifies the name of the page from which the image was scanned. - /// - PageName = 0x011D, - - /// - /// Page number of the page from which the image was scanned. - /// - PageNumber = 0x0129, - - /// - /// The palette histogram. - /// - PaletteHistogram = 0x5113, - - /// - /// How pixel data will be interpreted. - /// - PhotometricInterp = 0x0106, - - /// - /// Pixels per unit in the x direction. - /// - PixelPerUnitX = 0x5111, - - /// - /// Pixels per unit in the y direction. - /// - PixelPerUnitY = 0x5112, - - /// - /// Unit for and . - /// - PixelUnit = 0x5110, - - /// - /// Whether pixel components are recorded in chunky or planar format. - /// - PlanarConfig = 0x011C, - - /// - /// TType of prediction scheme that was applied to the image data before the encoding scheme was applied. - /// - Predictor = 0x013D, - - /// - /// For each of the three primary colors in the image, the chromaticity of that color. - /// - PrimaryChromaticities = 0x013F, - - /// - /// Sequence of one-byte Boolean values that specify printing options. - /// - PrintFlags = 0x5005, - - /// - /// The print flags bleed width. - /// - PrintFlagsBleedWidth = 0x5008, - - /// - /// The print flags bleed width scale. - /// - PrintFlagsBleedWidthScale = 0x5009, - - /// - /// The print flags crop marks. - /// - PrintFlagsCrop = 0x5007, - - /// - /// The print flags version. - /// - PrintFlagsVersion = 0x5006, - - /// - /// Reference black point value and reference white point value. - /// - REFBlackWhite = 0x0214, - - /// - /// Unit of measure for the horizontal resolution and the vertical resolution. - /// - ResolutionUnit = 0x0128, - - /// - /// Units in which to display the image width. - /// - ResolutionXLengthUnit = 0x5003, - - /// - /// Units in which to display horizontal resolution. - /// - ResolutionXUnit = 0x5001, - - /// - /// Units in which to display the image height. - /// - ResolutionYLengthUnit = 0x5004, - - /// - /// Units in which to display vertical resolution. - /// - ResolutionYUnit = 0x5002, - - /// - /// Number of rows per strip. See also and . - /// - RowsPerStrip = 0x0116, - - /// - /// For each color component, the numerical format (unsigned, signed, floating point) of that component. - /// See also . - /// - SampleFormat = 0x0153, - - /// - /// Number of color components per pixel. - /// - SamplesPerPixel = 0x0115, - - /// - /// For each color component, the maximum value of that component. See also . - /// - SMaxSampleValue = 0x0155, - - /// - /// For each color component, the minimum value of that component. See also . - /// - SMinSampleValue = 0x0154, - - /// - /// Null-terminated character string that specifies the name and version of the software or - /// firmware of the device used to generate the image. - /// - SoftwareUsed = 0x0131, - - /// - /// How the image should be displayed as defined by the International Color Consortium (ICC). If a GDI+ Image object - /// is constructed with the useEmbeddedColorManagement parameter set to TRUE, then GDI+ renders the image - /// according to the specified rendering intent. The intent can be set to perceptual, relative colorimetric, - /// saturation, or absolute colorimetric. - /// - SRGBRenderingIntent = 0x0303, - - /// - /// For each strip, the total number of bytes in that strip. - /// - StripBytesCount = 0x0117, - - /// - /// For each strip, the byte offset of that strip. See also - /// and . - /// - StripOffsets = 0x0111, - - /// - /// The type of data in a subfile. - /// - SubfileType = 0x00FF, - - /// - /// Set of flags that relate to T4 encoding. - /// - T4Option = 0x0124, - - /// - /// Set of flags that relate to T6 encoding. - /// - T6Option = 0x0125, - - /// - /// Null-terminated character string that describes the intended printing environment. - /// - TargetPrinter = 0x0151, - - /// - /// Technique used to convert from gray pixels to black and white pixels. - /// - ThreshHolding = 0x0107, - - /// - /// Null-terminated character string that specifies the name of the person who created the thumbnail image. - /// - ThumbnailArtist = 0x5034, - - /// - /// Number of bits per color component in the thumbnail image. See also . - /// - ThumbnailBitsPerSample = 0x5022, - - /// - /// Bits per pixel (BPP) for the thumbnail image. - /// - ThumbnailColorDepth = 0x5015, - - /// - /// Compressed size, in bytes, of the thumbnail image. - /// - ThumbnailCompressedSize = 0x5019, - - /// - /// Compression scheme used for thumbnail image data. - /// - ThumbnailCompression = 0x5023, - - /// - /// Null-terminated character string that contains copyright information for the thumbnail image. - /// - ThumbnailCopyRight = 0x503B, - - /// - /// Raw thumbnail bits in JPEG or RGB format. Depends on . - /// - ThumbnailData = 0x501B, - - /// - /// Date and time the thumbnail image was created. See also . - /// - ThumbnailDateTime = 0x5033, - - /// - /// Null-terminated character string that specifies the manufacturer of the equipment used to - /// record the thumbnail image. - /// - ThumbnailEquipMake = 0x5026, - - /// - /// Null-terminated character string that specifies the model name or model number of the - /// equipment used to record the thumbnail image. - /// - ThumbnailEquipModel = 0x5027, - - /// - /// Format of the thumbnail image. - /// - ThumbnailFormat = 0x5012, - - /// - /// Height, in pixels, of the thumbnail image. - /// - ThumbnailHeight = 0x5014, - - /// - /// Null-terminated character string that specifies the title of the image. - /// - ThumbnailImageDescription = 0x5025, - - /// - /// Number of pixel rows in the thumbnail image. - /// - ThumbnailImageHeight = 0x5021, - - /// - /// Number of pixels per row in the thumbnail image. - /// - ThumbnailImageWidth = 0x5020, - - /// - /// Thumbnail image orientation in terms of rows and columns. See also . - /// - ThumbnailOrientation = 0x5029, - - /// - /// How thumbnail pixel data will be interpreted. - /// - ThumbnailPhotometricInterp = 0x5024, - - /// - /// Whether pixel components in the thumbnail image are recorded in chunky or planar format. - /// See also . - /// - ThumbnailPlanarConfig = 0x502F, - - /// - /// Number of color planes for the thumbnail image. - /// - ThumbnailPlanes = 0x5016, - - /// - /// For each of the three primary colors in the thumbnail image, the chromaticity - /// of that color. See also . - /// - ThumbnailPrimaryChromaticities = 0x5036, - - /// - /// Byte offset between rows of pixel data. - /// - ThumbnailRawBytes = 0x5017, - - /// - /// Reference black point value and reference white point value - /// for the thumbnail image. See also . - /// - ThumbnailRefBlackWhite = 0x503A, - - /// - /// Unit of measure for the horizontal resolution and the vertical resolution of - /// the thumbnail image. See also . - /// - ThumbnailResolutionUnit = 0x5030, - - /// - /// Thumbnail resolution in the width direction. - /// The resolution unit is given in . - /// - ThumbnailResolutionX = 0x502D, - - /// - /// Thumbnail resolution in the height direction. The resolution unit is given - /// in . - /// - ThumbnailResolutionY = 0x502E, - - /// - /// Number of rows per strip in the thumbnail image. See also - /// and . - /// - ThumbnailRowsPerStrip = 0x502B, - - /// - /// Number of color components per pixel in the thumbnail image. - /// - ThumbnailSamplesPerPixel = 0x502A, - - /// - /// Total size, in bytes, of the thumbnail image. - /// - ThumbnailSize = 0x5018, - - /// - /// Null-terminated character string that specifies the name and version of the software - /// or firmware of the device used to generate the thumbnail image. - /// - ThumbnailSoftwareUsed = 0x5032, - - /// - /// For each thumbnail image strip, the total number of bytes in that strip. - /// - ThumbnailStripBytesCount = 0x502C, - - /// - /// For each strip in the thumbnail image, the byte offset of that strip. See also - /// and . - /// - ThumbnailStripOffsets = 0x5028, - - /// - /// Tables that specify transfer functions for the thumbnail image. See also . - /// - ThumbnailTransferFunction = 0x5031, - - /// - /// Chromaticity of the white point of the thumbnail image. See also . - /// - ThumbnailWhitePoint = 0x5035, - - /// - /// Width, in pixels, of the thumbnail image. - /// - ThumbnailWidth = 0x5013, - - /// - /// Coefficients for transformation from RGB to YCbCr data for the thumbnail image. - /// See also . - /// - ThumbnailYCbCrCoefficients = 0x5037, - - /// - /// Position of chrominance components in relation to the luminance component for - /// the thumbnail image. See also . - /// - ThumbnailYCbCrPositioning = 0x5039, - - /// - /// Sampling ratio of chrominance components in relation to the luminance component for - /// the thumbnail image. See also . - /// - ThumbnailYCbCrSubsampling = 0x5038, - - /// - /// For each tile, the number of bytes in that tile. - /// - TileByteCounts = 0x0145, - - /// - /// Number of pixel rows in each tile. - /// - TileLength = 0x0143, - - /// - /// For each tile, the byte offset of that tile. - /// - TileOffset = 0x0144, - - /// - /// Number of pixel columns in each tile. - /// - TileWidth = 0x0142, - - /// - /// Tables that specify transfer functions for the image. - /// - TransferFunction = 0x012D, - - /// - /// Table of values that extends the range of the transfer function. - /// - TransferRange = 0x0156, - - /// - /// Chromaticity of the white point of the image. - /// - WhitePoint = 0x013E, - - /// - /// Offset from the left side of the page to the left side of the image. - /// The unit of measure is specified by . - /// - XPosition = 0x011E, - - /// - /// Number of pixels per unit in the image width (x) direction. - /// The unit is specified by . - /// - XResolution = 0x011A, - - /// - /// Coefficients for transformation from RGB to YCbCr image data. - /// - YCbCrCoefficients = 0x0211, - - /// - /// Position of chrominance components in relation to the luminance component. - /// - YCbCrPositioning = 0x0213, - - /// - /// Sampling ratio of chrominance components in relation to the luminance component. - /// - YCbCrSubsampling = 0x0212, - - /// - /// Offset from the top of the page to the top of the image. The unit of measure - /// is specified by . - /// - YPosition = 0x011F, - - /// - /// Number of pixels per unit in the image height (y) direction. The unit is specified - /// by . - /// - YResolution = 0x011B - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagType.cs b/old/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagType.cs deleted file mode 100644 index 02fa21362..000000000 --- a/old/src/ImageProcessor/Imaging/MetaData/ExifPropertyTagType.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Specifies the data type of the values stored in the value data member of that same PropertyItem object. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.MetaData -{ - /// - /// Specifies the data type of the values stored in the value data member of that same PropertyItem object. - /// - /// - public enum ExifPropertyTagType : short - { - /// Specifies that the value data member is an array of bytes. - Byte = 1, - - /// - /// Specifies that the value data member is a null-terminated ASCII string. If you set the type data member of a - /// PropertyItem object to ExifPropertyTagTypeASCII, you should set the length data member to the length of the string - /// including the NULL terminator. For example, the string HELLO would have a length of 6. - /// - ASCII = 2, - - /// Specifies that the value data member is an array of unsigned short (16-bit) integers. - Int16 = 3, - - /// Specifies that the value data member is an array of unsigned long (32-bit) integers. - Int32 = 4, - - /// - /// Specifies that the value data member is an array of pairs of unsigned long integers. Each pair represents a - /// fraction; the first integer is the numerator and the second integer is the denominator. - /// - Rational = 5, - - /// - /// Specifies that the value data member is an array of bytes that can hold values of any data type. - /// - Undefined = 7, - - /// - /// Specifies that the value data member is an array of signed long (32-bit) integers. - /// - SLONG = 9, - - /// - /// Specifies that the value data member is an array of pairs of signed long integers. Each pair represents a - /// fraction; the first integer is the numerator and the second integer is the denominator. - /// - SRational = 10 - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/IQuantizer.cs b/old/src/ImageProcessor/Imaging/Quantizers/IQuantizer.cs deleted file mode 100644 index 48feff2d1..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/IQuantizer.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to calculate the color palette of an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers -{ - using System.Drawing; - - /// - /// Encapsulates methods to calculate the color palette of an image. - /// - public interface IQuantizer - { - /// - /// Quantize an image and return the resulting output bitmap. - /// - /// - /// The image to quantize. - /// - /// - /// A quantized version of the image. - /// - Bitmap Quantize(Image source); - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/OctreeQuantizer.cs b/old/src/ImageProcessor/Imaging/Quantizers/OctreeQuantizer.cs deleted file mode 100644 index 2f62e82ba..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/OctreeQuantizer.cs +++ /dev/null @@ -1,582 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to calculate the colour palette if an image using an Octree pattern. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers -{ - using System; - using System.Collections; - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging.Colors; - - /// - /// Encapsulates methods to calculate the colour palette if an image using an Octree pattern. - /// - /// - public unsafe class OctreeQuantizer : Quantizer - { - /// - /// Stores the tree - /// - private readonly Octree octree; - - /// - /// Maximum allowed color depth - /// - private readonly int maxColors; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The Octree quantizer is a two pass algorithm. The initial pass sets up the Octree, - /// the second pass quantizes a color based on the nodes in the tree. - /// - /// Defaults to return a maximum of 255 colors plus transparency with 8 significant bits. - /// - /// - public OctreeQuantizer() - : this(255, 8) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The Octree quantizer is a two pass algorithm. The initial pass sets up the Octree, - /// the second pass quantizes a color based on the nodes in the tree - /// - /// - /// The maximum number of colors to return - /// - /// - /// The number of significant bits - /// - public OctreeQuantizer(int maxColors, int maxColorBits) - : base(false) - { - if (maxColors > 255) - { - throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256"); - } - - if ((maxColorBits < 1) | (maxColorBits > 8)) - { - throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8"); - } - - // Construct the Octree - this.octree = new Octree(maxColorBits); - - this.maxColors = maxColors; - } - - /// - /// Process the pixel in the first pass of the algorithm - /// - /// - /// The pixel to quantize - /// - /// - /// This function need only be overridden if your quantize algorithm needs two passes, - /// such as an Octree quantizer. - /// - protected override void InitialQuantizePixel(Color32* pixel) - { - // Add the color to the Octree - this.octree.AddColor(pixel); - } - - /// - /// Override this to process the pixel in the second pass of the algorithm - /// - /// - /// The pixel to quantize - /// - /// - /// The quantized value - /// - protected override byte QuantizePixel(Color32* pixel) - { - // The color at [maxColors] is set to transparent - byte paletteIndex = (byte)this.maxColors; - - // Get the palette index if this non-transparent - if (pixel->A > 0) - { - paletteIndex = (byte)this.octree.GetPaletteIndex(pixel); - } - - return paletteIndex; - } - - /// - /// Retrieve the palette for the quantized image - /// - /// - /// Any old palette, this is overwritten - /// - /// - /// The new color palette - /// - protected override ColorPalette GetPalette(ColorPalette original) - { - // First off convert the Octree to maxColors colors - ArrayList palette = this.octree.Palletize(this.maxColors - 1); - - // Then convert the palette based on those colors - for (int index = 0; index < palette.Count; index++) - { - original.Entries[index] = (Color)palette[index]; - } - - // Add the transparent color - original.Entries[this.maxColors] = Color.FromArgb(0, 0, 0, 0); - - return original; - } - - /// - /// Class which does the actual quantization - /// - private class Octree - { - /// - /// Mask used when getting the appropriate pixels for a given node - /// - private static readonly int[] Mask = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; - - /// - /// The root of the Octree - /// - private readonly OctreeNode root; - - /// - /// Array of reducible nodes - /// - private readonly OctreeNode[] reducibleNodes; - - /// - /// Maximum number of significant bits in the image - /// - private readonly int maxColorBits; - - /// - /// Number of leaves in the tree - /// - private int leafCount; - - /// - /// Store the last node quantized - /// - private OctreeNode previousNode; - - /// - /// Cache the previous color quantized - /// - private int previousColor; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The maximum number of significant bits in the image - /// - public Octree(int maxColorBits) - { - this.maxColorBits = maxColorBits; - this.leafCount = 0; - this.reducibleNodes = new OctreeNode[9]; - this.root = new OctreeNode(0, this.maxColorBits, this); - this.previousColor = 0; - this.previousNode = null; - } - - /// - /// Gets or sets the number of leaves in the tree - /// - private int Leaves - { - get { return this.leafCount; } - set { this.leafCount = value; } - } - - /// - /// Gets the array of reducible nodes - /// - private OctreeNode[] ReducibleNodes - { - get { return this.reducibleNodes; } - } - - /// - /// Add a given color value to the Octree - /// - /// - /// The containing color information to add. - /// - public void AddColor(Color32* pixel) - { - // Check if this request is for the same color as the last - if (this.previousColor == pixel->Argb) - { - // If so, check if I have a previous node setup. This will only occur if the first color in the image - // happens to be black, with an alpha component of zero. - if (null == this.previousNode) - { - this.previousColor = pixel->Argb; - this.root.AddColor(pixel, this.maxColorBits, 0, this); - } - else - { - // Just update the previous node - this.previousNode.Increment(pixel); - } - } - else - { - this.previousColor = pixel->Argb; - this.root.AddColor(pixel, this.maxColorBits, 0, this); - } - } - - /// - /// Convert the nodes in the Octree to a palette with a maximum of colorCount colors - /// - /// - /// The maximum number of colors - /// - /// - /// An with the palletized colors - /// - public ArrayList Palletize(int colorCount) - { - while (this.Leaves > colorCount) - { - this.Reduce(); - } - - // Now palletize the nodes - ArrayList palette = new ArrayList(this.Leaves); - int paletteIndex = 0; - this.root.ConstructPalette(palette, ref paletteIndex); - - // And return the palette - return palette; - } - - /// - /// Get the palette index for the passed color - /// - /// - /// The containing the pixel data. - /// - /// - /// The index of the given structure. - /// - public int GetPaletteIndex(Color32* pixel) - { - return this.root.GetPaletteIndex(pixel, 0); - } - - /// - /// Keep track of the previous node that was quantized - /// - /// - /// The node last quantized - /// - protected void TrackPrevious(OctreeNode node) - { - this.previousNode = node; - } - - /// - /// Reduce the depth of the tree - /// - private void Reduce() - { - // Find the deepest level containing at least one reducible node - int index = this.maxColorBits - 1; - while ((index > 0) && (null == this.reducibleNodes[index])) - { - index--; - } - - // Reduce the node most recently added to the list at level 'index' - OctreeNode node = this.reducibleNodes[index]; - this.reducibleNodes[index] = node.NextReducible; - - // Decrement the leaf count after reducing the node - this.leafCount -= node.Reduce(); - - // And just in case I've reduced the last color to be added, and the next color to - // be added is the same, invalidate the previousNode... - this.previousNode = null; - } - - /// - /// Class which encapsulates each node in the tree - /// - protected class OctreeNode - { - /// - /// Pointers to any child nodes - /// - private readonly OctreeNode[] children; - - /// - /// Pointer to next reducible node - /// - private readonly OctreeNode nextReducible; - - /// - /// Flag indicating that this is a leaf node - /// - private bool leaf; - - /// - /// Number of pixels in this node - /// - private int pixelCount; - - /// - /// Red component - /// - private int red; - - /// - /// Green Component - /// - private int green; - - /// - /// Blue component - /// - private int blue; - - /// - /// The index of this node in the palette - /// - private int paletteIndex; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The level in the tree = 0 - 7 - /// - /// - /// The number of significant color bits in the image - /// - /// - /// The tree to which this node belongs - /// - public OctreeNode(int level, int colorBits, Octree octree) - { - // Construct the new node - this.leaf = level == colorBits; - - this.red = this.green = this.blue = 0; - this.pixelCount = 0; - - // If a leaf, increment the leaf count - if (this.leaf) - { - octree.Leaves++; - this.nextReducible = null; - this.children = null; - } - else - { - // Otherwise add this to the reducible nodes - this.nextReducible = octree.ReducibleNodes[level]; - octree.ReducibleNodes[level] = this; - this.children = new OctreeNode[8]; - } - } - - /// - /// Gets the next reducible node - /// - public OctreeNode NextReducible - { - get { return this.nextReducible; } - } - - /// - /// Add a color into the tree - /// - /// - /// The color - /// - /// - /// The number of significant color bits - /// - /// - /// The level in the tree - /// - /// - /// The tree to which this node belongs - /// - public void AddColor(Color32* pixel, int colorBits, int level, Octree octree) - { - // Update the color information if this is a leaf - if (this.leaf) - { - this.Increment(pixel); - - // Setup the previous node - octree.TrackPrevious(this); - } - else - { - // Go to the next level down in the tree - int shift = 7 - level; - int index = ((pixel->R & Mask[level]) >> (shift - 2)) | - ((pixel->G & Mask[level]) >> (shift - 1)) | - ((pixel->B & Mask[level]) >> shift); - - OctreeNode child = this.children[index]; - - if (null == child) - { - // Create a new child node & store in the array - child = new OctreeNode(level + 1, colorBits, octree); - this.children[index] = child; - } - - // Add the color to the child node - child.AddColor(pixel, colorBits, level + 1, octree); - } - } - - /// - /// Reduce this node by removing all of its children - /// - /// The number of leaves removed - public int Reduce() - { - this.red = this.green = this.blue = 0; - int childNodes = 0; - - // Loop through all children and add their information to this node - for (int index = 0; index < 8; index++) - { - if (null != this.children[index]) - { - this.red += this.children[index].red; - this.green += this.children[index].green; - this.blue += this.children[index].blue; - this.pixelCount += this.children[index].pixelCount; - ++childNodes; - this.children[index] = null; - } - } - - // Now change this to a leaf node - this.leaf = true; - - // Return the number of nodes to decrement the leaf count by - return childNodes - 1; - } - - /// - /// Traverse the tree, building up the color palette - /// - /// - /// The palette - /// - /// - /// The current palette index - /// - public void ConstructPalette(ArrayList palette, ref int index) - { - if (this.leaf) - { - // Consume the next palette index - this.paletteIndex = index++; - - byte r = (this.red / this.pixelCount).ToByte(); - byte g = (this.green / this.pixelCount).ToByte(); - byte b = (this.blue / this.pixelCount).ToByte(); - - // And set the color of the palette entry - palette.Add(Color.FromArgb(r, g, b)); - } - else - { - // Loop through children looking for leaves - for (int i = 0; i < 8; i++) - { - if (null != this.children[i]) - { - this.children[i].ConstructPalette(palette, ref index); - } - } - } - } - - /// - /// Return the palette index for the passed color - /// - /// - /// The representing the pixel. - /// - /// - /// The level. - /// - /// - /// The representing the index of the pixel in the palette. - /// - public int GetPaletteIndex(Color32* pixel, int level) - { - int index = this.paletteIndex; - - if (!this.leaf) - { - int shift = 7 - level; - int pixelIndex = ((pixel->R & Mask[level]) >> (shift - 2)) | - ((pixel->G & Mask[level]) >> (shift - 1)) | - ((pixel->B & Mask[level]) >> shift); - - if (null != this.children[pixelIndex]) - { - index = this.children[pixelIndex].GetPaletteIndex(pixel, level + 1); - } - else - { - throw new Exception("Didn't expect this!"); - } - } - - return index; - } - - /// - /// Increment the pixel count and add to the color information - /// - /// - /// The pixel to add. - /// - public void Increment(Color32* pixel) - { - this.pixelCount++; - this.red += pixel->R; - this.green += pixel->G; - this.blue += pixel->B; - } - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Quantizers/Quantizer.cs b/old/src/ImageProcessor/Imaging/Quantizers/Quantizer.cs deleted file mode 100644 index f1eaae663..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/Quantizer.cs +++ /dev/null @@ -1,271 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to calculate the color palette of an image. -// -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers -{ - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.Colors; - - /// - /// Encapsulates methods to calculate the color palette of an image. - /// - /// - public unsafe abstract class Quantizer : IQuantizer - { - /// - /// Flag used to indicate whether a single pass or two passes are needed for quantization. - /// - private readonly bool singlePass; - - /// - /// Initializes a new instance of the class. - /// - /// - /// If true, the quantization only needs to loop through the source pixels once - /// - /// - /// If you construct this class with a true value for singlePass, then the code will, when quantizing your image, - /// only call the 'QuantizeImage' function. If two passes are required, the code will call 'InitialQuantizeImage' - /// and then 'QuantizeImage'. - /// - protected Quantizer(bool singlePass) - { - this.singlePass = singlePass; - } - - /// - /// Quantize an image and return the resulting output bitmap. - /// - /// - /// The image to quantize. - /// - /// - /// A quantized version of the image. - /// - public Bitmap Quantize(Image source) - { - // Get the size of the source image - int height = source.Height; - int width = source.Width; - - // And construct a rectangle from these dimensions - Rectangle bounds = new Rectangle(0, 0, width, height); - - // First off take a 32bpp copy of the image - Bitmap copy = new Bitmap(width, height, PixelFormat.Format32bppPArgb); - copy.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - // And construct an 8bpp version - Bitmap output = new Bitmap(width, height, PixelFormat.Format8bppIndexed); - output.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - // Now lock the bitmap into memory - using (Graphics g = Graphics.FromImage(copy)) - { - g.PageUnit = GraphicsUnit.Pixel; - - // Draw the source image onto the copy bitmap, - // which will effect a widening as appropriate. - g.DrawImageUnscaled(source, bounds); - } - - // Define a pointer to the bitmap data - BitmapData sourceData = null; - - try - { - // Get the source image bits and lock into memory - sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb); - - // Call the FirstPass function if not a single pass algorithm. - // For something like an Octree quantizer, this will run through - // all image pixels, build a data structure, and create a palette. - if (!this.singlePass) - { - this.FirstPass(sourceData, width, height); - } - - // Then set the color palette on the output bitmap. I'm passing in the current palette - // as there's no way to construct a new, empty palette. - output.Palette = this.GetPalette(output.Palette); - - // Then call the second pass which actually does the conversion - this.SecondPass(sourceData, output, width, height, bounds); - } - finally - { - // Ensure that the bits are unlocked - copy.UnlockBits(sourceData); - } - - // Last but not least, return the output bitmap - return output; - } - - /// - /// Execute the first pass through the pixels in the image - /// - /// - /// The source data - /// - /// - /// The width in pixels of the image - /// - /// - /// The height in pixels of the image - /// - protected virtual void FirstPass(BitmapData sourceData, int width, int height) - { - // Define the source data pointers. The source row is a byte to - // keep addition of the stride value easier (as this is in bytes) - byte* sourceRow = (byte*)sourceData.Scan0.ToPointer(); - - // Loop through each row - for (int row = 0; row < height; row++) - { - // Set the source pixel to the first pixel in this row - int* sourcePixel = (int*)sourceRow; - - // And loop through each column - for (int col = 0; col < width; col++, sourcePixel++) - { - // Now I have the pixel, call the FirstPassQuantize function... - this.InitialQuantizePixel((Color32*)sourcePixel); - } - - // Add the stride to the source row - sourceRow += sourceData.Stride; - } - } - - /// - /// Execute a second pass through the bitmap - /// - /// - /// The source bitmap, locked into memory - /// - /// - /// The output bitmap - /// - /// - /// The width in pixels of the image - /// - /// - /// The height in pixels of the image - /// - /// - /// The bounding rectangle - /// - protected virtual void SecondPass(BitmapData sourceData, Bitmap output, int width, int height, Rectangle bounds) - { - BitmapData outputData = null; - - try - { - // Lock the output bitmap into memory - outputData = output.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); - - // Define the source data pointers. The source row is a byte to - // keep addition of the stride value easier (as this is in bytes) - byte* sourceRow = (byte*)sourceData.Scan0.ToPointer(); - int* sourcePixel = (int*)sourceRow; - int* previousPixel = sourcePixel; - - // Now define the destination data pointers - byte* destinationRow = (byte*)outputData.Scan0.ToPointer(); - byte* destinationPixel = destinationRow; - - // And convert the first pixel, so that I have values going into the loop - byte pixelValue = this.QuantizePixel((Color32*)sourcePixel); - - // Assign the value of the first pixel - *destinationPixel = pixelValue; - - // Loop through each row - for (int row = 0; row < height; row++) - { - // Set the source pixel to the first pixel in this row - sourcePixel = (int*)sourceRow; - - // And set the destination pixel pointer to the first pixel in the row - destinationPixel = destinationRow; - - // Loop through each pixel on this scan line - for (int col = 0; col < width; col++, sourcePixel++, destinationPixel++) - { - // Check if this is the same as the last pixel. If so use that value - // rather than calculating it again. This is an inexpensive optimization. - if (*previousPixel != *sourcePixel) - { - // Quantize the pixel - pixelValue = this.QuantizePixel((Color32*)sourcePixel); - - // And setup the previous pointer - previousPixel = sourcePixel; - } - - // And set the pixel in the output - *destinationPixel = pixelValue; - } - - // Add the stride to the source row - sourceRow += sourceData.Stride; - - // And to the destination row - destinationRow += outputData.Stride; - } - } - finally - { - // Ensure that I unlock the output bits - output.UnlockBits(outputData); - } - } - - /// - /// Override this to process the pixel in the first pass of the algorithm - /// - /// - /// The pixel to quantize - /// - /// - /// This function need only be overridden if your quantize algorithm needs two passes, - /// such as an Octree quantizer. - /// - protected virtual void InitialQuantizePixel(Color32* pixel) - { - } - - /// - /// Override this to process the pixel in the second pass of the algorithm - /// - /// - /// The pixel to quantize - /// - /// - /// The quantized value - /// - protected abstract byte QuantizePixel(Color32* pixel); - - /// - /// Retrieve the palette for the quantized image - /// - /// - /// Any old palette, this is overwritten - /// - /// - /// The new color palette - /// - protected abstract ColorPalette GetPalette(ColorPalette original); - } -} diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/Box.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/Box.cs deleted file mode 100644 index 23e159c22..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/Box.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The box for storing color attributes. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - /// - /// The box for storing color attributes. - /// Adapted from - /// - public struct Box - { - /// - /// The alpha maximum. - /// - public byte AlphaMaximum; - - /// - /// The alpha minimum. - /// - public byte AlphaMinimum; - - /// - /// The blue maximum. - /// - public byte BlueMaximum; - - /// - /// The blue minimum. - /// - public byte BlueMinimum; - - /// - /// The green maximum. - /// - public byte GreenMaximum; - - /// - /// The green minimum. - /// - public byte GreenMinimum; - - /// - /// The red maximum. - /// - public byte RedMaximum; - - /// - /// The red minimum. - /// - public byte RedMinimum; - - /// - /// The size. - /// - public int Size; - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/ColorMoment.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/ColorMoment.cs deleted file mode 100644 index 6d6aa05b8..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/ColorMoment.cs +++ /dev/null @@ -1,188 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The cumulative color moment for holding pixel information. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using ImageProcessor.Imaging.Colors; - - /// - /// The cumulative color moment for holding pixel information. - /// Adapted from - /// - internal struct ColorMoment - { - /// - /// The alpha component. - /// - public long Alpha; - - /// - /// The blue component. - /// - public long Blue; - - /// - /// The green component. - /// - public long Green; - - /// - /// The moment. - /// - public float Moment; - - /// - /// The red. - /// - public long Red; - - /// - /// The weight. - /// - public int Weight; - - /// - /// Adds one to another. - /// - /// - /// The first . - /// - /// - /// The second . - /// - /// - /// The representing the sum of the addition. - /// - public static ColorMoment operator +(ColorMoment firstAddend, ColorMoment secondAddend) - { - firstAddend.Alpha += secondAddend.Alpha; - firstAddend.Red += secondAddend.Red; - firstAddend.Green += secondAddend.Green; - firstAddend.Blue += secondAddend.Blue; - firstAddend.Weight += secondAddend.Weight; - firstAddend.Moment += secondAddend.Moment; - return firstAddend; - } - - /// - /// Subtracts one from another. - /// - /// - /// The from which the other will be subtracted - /// - /// - /// The that is to be subtracted. - /// - /// - /// The representing the difference of the subtraction. - /// - public static ColorMoment operator -(ColorMoment minuend, ColorMoment subtrahend) - { - minuend.Alpha -= subtrahend.Alpha; - minuend.Red -= subtrahend.Red; - minuend.Green -= subtrahend.Green; - minuend.Blue -= subtrahend.Blue; - minuend.Weight -= subtrahend.Weight; - minuend.Moment -= subtrahend.Moment; - return minuend; - } - - /// - /// Negates the given . - /// - /// - /// The to negate. - /// - /// - /// The negated result - /// - public static ColorMoment operator -(ColorMoment moment) - { - moment.Alpha = -moment.Alpha; - moment.Red = -moment.Red; - moment.Green = -moment.Green; - moment.Blue = -moment.Blue; - moment.Weight = -moment.Weight; - moment.Moment = -moment.Moment; - return moment; - } - - /// - /// Adds a pixel to the current instance. - /// - /// - /// The pixel to add. - /// - public void Add(Color32 pixel) - { - byte alpha = pixel.A; - byte red = pixel.R; - byte green = pixel.G; - byte blue = pixel.B; - this.Alpha += alpha; - this.Red += red; - this.Green += green; - this.Blue += blue; - this.Weight++; - this.Moment += (alpha * alpha) + (red * red) + (green * green) + (blue * blue); - } - - /// - /// Adds a color moment to the current instance more quickly. - /// - /// - /// The to add. - /// - public void AddFast(ref ColorMoment moment) - { - this.Alpha += moment.Alpha; - this.Red += moment.Red; - this.Green += moment.Green; - this.Blue += moment.Blue; - this.Weight += moment.Weight; - this.Moment += moment.Moment; - } - - /// - /// The amplitude. - /// - /// - /// The representing the amplitude. - /// - public long Amplitude() - { - return (this.Alpha * this.Alpha) + (this.Red * this.Red) + (this.Green * this.Green) + (this.Blue * this.Blue); - } - - /// - /// The variance. - /// - /// - /// The representing the variance. - /// - public float Variance() - { - float result = this.Moment - ((float)this.Amplitude() / this.Weight); - return float.IsNaN(result) ? 0.0f : result; - } - - /// - /// The weighted distance. - /// - /// - /// The . - /// - public long WeightedDistance() - { - return this.Amplitude() / this.Weight; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/CubeCut.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/CubeCut.cs deleted file mode 100644 index 1d5412f6e..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/CubeCut.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Represents a cube cut. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - /// - /// Represents a cube cut. - /// Adapted from - /// - internal struct CubeCut - { - /// - /// The position. - /// - public readonly byte? Position; - - /// - /// The value. - /// - public readonly float Value; - - /// - /// Initializes a new instance of the struct. - /// - /// - /// The cut point. - /// - /// - /// The result. - /// - public CubeCut(byte? cutPoint, float result) - { - this.Position = cutPoint; - this.Value = result; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/Histogram.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/Histogram.cs deleted file mode 100644 index 5a6369678..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/Histogram.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The histogram representing the distribution of color data. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System; - - /// - /// The histogram representing the distribution of color data. - /// Adapted from - /// - public class Histogram - { - /// - /// The moments. - /// - internal readonly ColorMoment[,,,] Moments; - - /// - /// The side size. - /// - private const int SideSize = 33; - - /// - /// Initializes a new instance of the class. - /// - public Histogram() - { - // 47,436,840 bytes - this.Moments = new ColorMoment[SideSize, SideSize, SideSize, SideSize]; - } - - /// - /// The clear. - /// - internal void Clear() - { - Array.Clear(this.Moments, 0, SideSize * SideSize * SideSize * SideSize); - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/IWuQuantizer.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/IWuQuantizer.cs deleted file mode 100644 index 90ffb15b4..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/IWuQuantizer.cs +++ /dev/null @@ -1,42 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to calculate the color palette of an image using -// a Wu color quantizer . -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System.Drawing; - - /// - /// Encapsulates methods to calculate the color palette of an image using - /// a Wu color quantizer . - /// Adapted from - /// - public interface IWuQuantizer : IQuantizer - { - /// - /// Quantizes the given image. - /// - /// - /// The 32 bit per pixel . - /// - /// - /// The alpha threshold. All colors with an alpha value less than this will be - /// considered fully transparent - /// - /// - /// The alpha fader. Alpha values will be normalized to the nearest multiple of this value. - /// - /// - /// The quantized . - /// - Bitmap Quantize(Image image, int alphaThreshold, int alphaFader); - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/ImageBuffer.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/ImageBuffer.cs deleted file mode 100644 index 19fee034c..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/ImageBuffer.cs +++ /dev/null @@ -1,109 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The image buffer for storing and manipulating pixel information. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - using System.Runtime.InteropServices; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Colors; - - /// - /// The image buffer for storing and manipulating pixel information. - /// Adapted from - /// - internal class ImageBuffer - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The image to store. - /// - public ImageBuffer(Bitmap image) - { - this.Image = image; - } - - /// - /// Gets the image. - /// - public Bitmap Image { get; private set; } - - /// - /// Gets the enumerable pixel array representing each row of pixels. - /// - /// - /// Thrown if the given image is not a 32 bit per pixel image. - /// - public IEnumerable PixelLines - { - get - { - int width = this.Image.Width; - int height = this.Image.Height; - Color32[] pixels = new Color32[width]; - - using (FastBitmap bitmap = new FastBitmap(this.Image)) - { - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - Color color = bitmap.GetPixel(x, y); - pixels[x] = new Color32(color.A, color.R, color.G, color.B); - } - - yield return pixels; - } - } - } - } - - /// - /// Updates the pixel indexes. - /// - /// - /// The enumerable byte array representing each row of pixels. - /// - public void UpdatePixelIndexes(IEnumerable lineIndexes) - { - int width = this.Image.Width; - int height = this.Image.Height; - int rowIndex = 0; - - BitmapData data = this.Image.LockBits(Rectangle.FromLTRB(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); - try - { - IntPtr pixelBase = data.Scan0; - int scanWidth = data.Stride; - foreach (byte[] scanLine in lineIndexes) - { - // TODO: Use unsafe code - Marshal.Copy(scanLine, 0, IntPtr.Add(pixelBase, scanWidth * rowIndex), width); - - if (++rowIndex >= height) - { - break; - } - } - } - finally - { - this.Image.UnlockBits(data); - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/PaletteColorHistory.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/PaletteColorHistory.cs deleted file mode 100644 index ee155b7de..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/PaletteColorHistory.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The palette color history containing the sum of all pixel data. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System.Drawing; - - using ImageProcessor.Imaging.Colors; - - /// - /// The palette color history containing the sum of all pixel data. - /// Adapted from - /// - internal struct PaletteColorHistory - { - /// - /// The alpha component. - /// - public int Alpha; - - /// - /// The red component. - /// - public int Red; - - /// - /// The green component. - /// - public int Green; - - /// - /// The blue component. - /// - public int Blue; - - /// - /// The sum of the color components. - /// - public int Sum; - - /// - /// Normalizes the color. - /// - /// - /// The normalized . - /// - public Color ToNormalizedColor() - { - return (this.Sum != 0) ? Color.FromArgb(this.Alpha /= this.Sum, this.Red /= this.Sum, this.Green /= this.Sum, this.Blue /= this.Sum) : Color.Empty; - } - - /// - /// Adds a pixel to the color history. - /// - /// - /// The pixel to add. - /// - public void AddPixel(Color32 pixel) - { - this.Alpha += pixel.A; - this.Red += pixel.R; - this.Green += pixel.G; - this.Blue += pixel.B; - this.Sum++; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/PaletteLookup.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/PaletteLookup.cs deleted file mode 100644 index f00438bf1..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/PaletteLookup.cs +++ /dev/null @@ -1,269 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Stores the indexed color palette of an image for fast access. -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System; - using System.Collections.Generic; - using System.Linq; - - using ImageProcessor.Imaging.Colors; - - /// - /// Stores the indexed color palette of an image for fast access. - /// Adapted from - /// - internal class PaletteLookup - { - /// - /// The dictionary for caching lookup nodes. - /// - private Dictionary lookupNodes; - - /// - /// The palette mask. - /// - private int paletteMask; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The palette. - /// - public PaletteLookup(Color32[] palette) - { - this.Palette = new LookupNode[palette.Length]; - for (int paletteIndex = 0; paletteIndex < palette.Length; paletteIndex++) - { - this.Palette[paletteIndex] = new LookupNode - { - Color32 = palette[paletteIndex], - PaletteIndex = (byte)paletteIndex - }; - } - - this.BuildLookup(palette); - } - - /// - /// Gets or sets the palette. - /// - private LookupNode[] Palette { get; set; } - - /// - /// Gets palette index for the given pixel. - /// - /// - /// The pixel to return the index for. - /// - /// - /// The representing the index. - /// - public byte GetPaletteIndex(Color32 pixel) - { - int pixelKey = pixel.Argb & this.paletteMask; - LookupNode[] bucket; - if (!this.lookupNodes.TryGetValue(pixelKey, out bucket)) - { - bucket = this.Palette; - } - - if (bucket.Length == 1) - { - return bucket[0].PaletteIndex; - } - - int bestDistance = int.MaxValue; - byte bestMatch = 0; - foreach (LookupNode lookup in bucket) - { - Color32 lookupPixel = lookup.Color32; - - int deltaAlpha = pixel.A - lookupPixel.A; - int distance = deltaAlpha * deltaAlpha; - - int deltaRed = pixel.R - lookupPixel.R; - distance += deltaRed * deltaRed; - - int deltaGreen = pixel.G - lookupPixel.G; - distance += deltaGreen * deltaGreen; - - int deltaBlue = pixel.B - lookupPixel.B; - distance += deltaBlue * deltaBlue; - - if (distance >= bestDistance) - { - continue; - } - - bestDistance = distance; - bestMatch = lookup.PaletteIndex; - } - - if ((bucket == this.Palette) && (pixelKey != 0)) - { - this.lookupNodes[pixelKey] = new[] { bucket[bestMatch] }; - } - - return bestMatch; - } - - /// - /// Computes the bit mask. - /// - /// - /// The maximum byte value. - /// - /// - /// The number of bits. - /// - /// - /// The . - /// - private static byte ComputeBitMask(byte max, int bits) - { - byte mask = 0; - - if (bits != 0) - { - byte highestSetBitIndex = HighestSetBitIndex(max); - - for (int i = 0; i < bits; i++) - { - mask <<= 1; - mask++; - } - - for (int i = 0; i <= highestSetBitIndex - bits; i++) - { - mask <<= 1; - } - } - - return mask; - } - - /// - /// Gets the mask value from the palette. - /// - /// - /// The palette. - /// - /// - /// The representing the component value of the mask. - /// - private static int GetMask(Color32[] palette) - { - IEnumerable alphas = palette.Select(p => p.A).ToArray(); - byte maxAlpha = alphas.Max(); - int uniqueAlphas = alphas.Distinct().Count(); - - IEnumerable reds = palette.Select(p => p.R).ToArray(); - byte maxRed = reds.Max(); - int uniqueReds = reds.Distinct().Count(); - - IEnumerable greens = palette.Select(p => p.G).ToArray(); - byte maxGreen = greens.Max(); - int uniqueGreens = greens.Distinct().Count(); - - IEnumerable blues = palette.Select(p => p.B).ToArray(); - byte maxBlue = blues.Max(); - int uniqueBlues = blues.Distinct().Count(); - - double totalUniques = uniqueAlphas + uniqueReds + uniqueGreens + uniqueBlues; - - double availableBits = 1.0 + Math.Log(uniqueAlphas * uniqueReds * uniqueGreens * uniqueBlues); - - byte alphaMask = ComputeBitMask(maxAlpha, Convert.ToInt32(Math.Round(uniqueAlphas / totalUniques * availableBits))); - byte redMask = ComputeBitMask(maxRed, Convert.ToInt32(Math.Round(uniqueReds / totalUniques * availableBits))); - byte greenMask = ComputeBitMask(maxGreen, Convert.ToInt32(Math.Round(uniqueGreens / totalUniques * availableBits))); - byte blueMask = ComputeBitMask(maxBlue, Convert.ToInt32(Math.Round(uniqueBlues / totalUniques * availableBits))); - - Color32 maskedPixel = new Color32(alphaMask, redMask, greenMask, blueMask); - return maskedPixel.Argb; - } - - /// - /// Gets the highest set bit index. - /// - /// - /// The value. - /// - /// - /// The . - /// - private static byte HighestSetBitIndex(byte value) - { - byte index = 0; - for (int i = 0; i < 8; i++) - { - if (0 != (value & 1)) - { - index = (byte)i; - } - - value >>= 1; - } - - return index; - } - - /// - /// The build lookup. - /// - /// - /// The palette. - /// - private void BuildLookup(Color32[] palette) - { - int mask = GetMask(palette); - Dictionary> tempLookup = new Dictionary>(); - foreach (LookupNode lookup in this.Palette) - { - int pixelKey = lookup.Color32.Argb & mask; - - List bucket; - if (!tempLookup.TryGetValue(pixelKey, out bucket)) - { - bucket = new List(); - tempLookup[pixelKey] = bucket; - } - - bucket.Add(lookup); - } - - this.lookupNodes = new Dictionary(tempLookup.Count); - foreach (int key in tempLookup.Keys) - { - this.lookupNodes[key] = tempLookup[key].ToArray(); - } - - this.paletteMask = mask; - } - - /// - /// Represents a single node containing the index and pixel. - /// - private struct LookupNode - { - /// - /// The palette index. - /// - public byte PaletteIndex; - - /// - /// The pixel. - /// - public Color32 Color32; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/WuQuantizer.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/WuQuantizer.cs deleted file mode 100644 index 40f82caee..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/WuQuantizer.cs +++ /dev/null @@ -1,125 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to calculate the color palette of an image using -// a Wu color quantizer . -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Imaging.Colors; - - /// - /// Encapsulates methods to calculate the color palette of an image using - /// a Wu color quantizer . - /// Adapted from - /// - public class WuQuantizer : WuQuantizerBase - { - /// - /// Quantizes the image contained within the returning the result. - /// - /// - /// The for storing and manipulating pixel information.. - /// - /// - /// The maximum number of colors apply to the image. - /// - /// - /// The array of containing indexed versions of the images colors. - /// - /// - /// All colors with an alpha value less than this will be considered fully transparent. - /// - /// - /// The quantized . - /// - internal override Bitmap GetQuantizedImage(ImageBuffer imageBuffer, int colorCount, Color32[] lookups, int alphaThreshold) - { - Bitmap result = new Bitmap(imageBuffer.Image.Width, imageBuffer.Image.Height, PixelFormat.Format8bppIndexed); - result.SetResolution(imageBuffer.Image.HorizontalResolution, imageBuffer.Image.VerticalResolution); - ImageBuffer resultBuffer = new ImageBuffer(result); - PaletteColorHistory[] paletteHistogram = new PaletteColorHistory[colorCount + 1]; - resultBuffer.UpdatePixelIndexes(IndexedPixels(imageBuffer, lookups, alphaThreshold, paletteHistogram)); - result.Palette = BuildPalette(result.Palette, paletteHistogram); - return result; - } - - /// - /// Builds a color palette from the given . - /// - /// - /// The to fill. - /// - /// - /// The containing the sum of all pixel data. - /// - /// - /// The . - /// - private static ColorPalette BuildPalette(ColorPalette palette, PaletteColorHistory[] paletteHistory) - { - int length = paletteHistory.Length; - for (int i = 0; i < length; i++) - { - palette.Entries[i] = paletteHistory[i].ToNormalizedColor(); - } - - return palette; - } - - /// - /// Gets an enumerable array of bytes representing each row of the image. - /// - /// - /// The for storing and manipulating pixel information. - /// - /// - /// The array of containing indexed versions of the images colors. - /// - /// - /// The alpha threshold. - /// - /// - /// The palette histogram. - /// - /// - /// The enumerable list of representing each pixel. - /// - private static IEnumerable IndexedPixels(ImageBuffer image, Color32[] lookups, int alphaThreshold, PaletteColorHistory[] paletteHistogram) - { - byte[] lineIndexes = new byte[image.Image.Width]; - PaletteLookup lookup = new PaletteLookup(lookups); - - // Determine the correct fallback color. - byte fallback = lookups.Length < AlphaMax ? AlphaMin : AlphaMax; - foreach (Color32[] pixelLine in image.PixelLines) - { - int length = pixelLine.Length; - for (int i = 0; i < length; i++) - { - Color32 pixel = pixelLine[i]; - byte bestMatch = fallback; - if (pixel.A > alphaThreshold) - { - bestMatch = lookup.GetPaletteIndex(pixel); - paletteHistogram[bestMatch].AddPixel(pixel); - } - - lineIndexes[i] = bestMatch; - } - - yield return lineIndexes; - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/WuQuantizerBase.cs b/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/WuQuantizerBase.cs deleted file mode 100644 index ee212abcc..000000000 --- a/old/src/ImageProcessor/Imaging/Quantizers/WuQuantizer/WuQuantizerBase.cs +++ /dev/null @@ -1,735 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to calculate the color palette of an image using -// a Wu color quantizer . -// Adapted from -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging.Quantizers.WuQuantizer -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Drawing; - using System.Drawing.Imaging; - using System.Linq; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Colors; - - /// - /// Encapsulates methods to calculate the color palette of an image using - /// a Wu color quantizer . - /// Adapted from - /// - public abstract class WuQuantizerBase : IWuQuantizer - { - /// - /// The maximum value for an alpha color component. - /// - protected const byte AlphaMax = 255; - - /// - /// The minimum value for an alpha color component. - /// - protected const byte AlphaMin = 0; - - /// - /// The position of the alpha component within a byte array. - /// - protected const int Alpha = 3; - - /// - /// The position of the red component within a byte array. - /// - protected const int Red = 2; - - /// - /// The position of the green component within a byte array. - /// - protected const int Green = 1; - - /// - /// The position of the blue component within a byte array. - /// - protected const int Blue = 0; - - /// - /// The size of a color cube side. - /// - private const int SideSize = 33; - - /// - /// The maximum index within a color cube side - /// - private const int MaxSideIndex = 32; - - /// - /// Quantize an image and return the resulting output bitmap - /// - /// - /// The 32 bit per pixel image to quantize. - /// - /// - /// A quantized version of the image. - /// - public Bitmap Quantize(Image source) - { - return this.Quantize(source, 0, 1); - } - - /// - /// Quantize an image and return the resulting output bitmap - /// - /// - /// The 32 bit per pixel image to quantize. - /// - /// - /// All colors with an alpha value less than this will be considered fully transparent. - /// - /// - /// Alpha values will be normalized to the nearest multiple of this value. - /// - /// - /// A quantized version of the image. - /// - public Bitmap Quantize(Image source, int alphaThreshold, int alphaFader) - { - return this.Quantize(source, alphaThreshold, alphaFader, null, 256); - } - - /// - /// Quantize an image and return the resulting output bitmap - /// - /// - /// The 32 bit per pixel image to quantize. - /// - /// - /// All colors with an alpha value less than this will be considered fully transparent. - /// - /// - /// Alpha values will be normalized to the nearest multiple of this value. - /// - /// - /// The representing the distribution of color data. - /// - /// - /// The maximum number of colors apply to the image. - /// - /// - /// A quantized version of the image. - /// - public Bitmap Quantize(Image source, int alphaThreshold, int alphaFader, Histogram histogram, int maxColors) - { - try - { - ImageBuffer buffer; - - // The image has to be a 32 bit per pixel Argb image. - if (Image.GetPixelFormatSize(source.PixelFormat) != 32) - { - Bitmap clone = new Bitmap(source.Width, source.Height, PixelFormat.Format32bppPArgb); - clone.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - using (Graphics graphics = Graphics.FromImage(clone)) - { - graphics.Clear(Color.Transparent); - graphics.DrawImage(source, new Rectangle(0, 0, clone.Width, clone.Height)); - } - - source.Dispose(); - buffer = new ImageBuffer(clone); - } - else - { - buffer = new ImageBuffer((Bitmap)source); - } - - if (histogram == null) - { - histogram = new Histogram(); - } - else - { - histogram.Clear(); - } - - BuildHistogram(histogram, buffer, alphaThreshold, alphaFader); - CalculateMoments(histogram.Moments); - Box[] cubes = SplitData(ref maxColors, histogram.Moments); - Color32[] lookups = BuildLookups(cubes, histogram.Moments); - return this.GetQuantizedImage(buffer, maxColors, lookups, alphaThreshold); - } - catch (Exception ex) - { - throw new QuantizationException(ex.Message, ex); - } - } - - /// - /// Quantizes the image contained within the returning the result. - /// - /// - /// The for storing and manipulating pixel information.. - /// - /// - /// The maximum number of colors apply to the image. - /// - /// - /// The array of containing indexed versions of the images colors. - /// - /// - /// All colors with an alpha value less than this will be considered fully transparent. - /// - /// - /// The quantized . - /// - internal abstract Bitmap GetQuantizedImage(ImageBuffer imageBuffer, int colorCount, Color32[] lookups, int alphaThreshold); - - /// - /// Builds a histogram from the current image. - /// - /// - /// The representing the distribution of color data. - /// - /// - /// The for storing pixel information. - /// - /// - /// All colors with an alpha value less than this will be considered fully transparent. - /// - /// - /// Alpha values will be normalized to the nearest multiple of this value. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static void BuildHistogram(Histogram histogram, ImageBuffer imageBuffer, int alphaThreshold, int alphaFader) - { - ColorMoment[, , ,] moments = histogram.Moments; - - foreach (Color32[] pixelLine in imageBuffer.PixelLines) - { - foreach (Color32 pixel in pixelLine) - { - byte pixelAlpha = pixel.A; - if (pixelAlpha > alphaThreshold) - { - if (pixelAlpha < 255) - { - int alpha = pixel.A + (pixel.A % alphaFader); - pixelAlpha = (byte)(alpha > 255 ? 255 : alpha); - } - - byte pixelRed = pixel.R; - byte pixelGreen = pixel.G; - byte pixelBlue = pixel.B; - - pixelAlpha = (byte)((pixelAlpha >> 3) + 1); - pixelRed = (byte)((pixelRed >> 3) + 1); - pixelGreen = (byte)((pixelGreen >> 3) + 1); - pixelBlue = (byte)((pixelBlue >> 3) + 1); - moments[pixelAlpha, pixelRed, pixelGreen, pixelBlue].Add(pixel); - } - } - } - - // Set a default pixel for images with less than 256 colors. - moments[0, 0, 0, 0].Add(new Color32(0, 0, 0, 0)); - } - - /// - /// Calculates the color moments from the histogram of moments. - /// - /// - /// The three dimensional array of to process. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static void CalculateMoments(ColorMoment[, , ,] moments) - { - ColorMoment[,] areaSquared = new ColorMoment[SideSize, SideSize]; - ColorMoment[] area = new ColorMoment[SideSize]; - for (int alphaIndex = 1; alphaIndex < SideSize; alphaIndex++) - { - for (int redIndex = 1; redIndex < SideSize; redIndex++) - { - Array.Clear(area, 0, area.Length); - for (int greenIndex = 1; greenIndex < SideSize; greenIndex++) - { - ColorMoment line = new ColorMoment(); - for (int blueIndex = 1; blueIndex < SideSize; blueIndex++) - { - line.AddFast(ref moments[alphaIndex, redIndex, greenIndex, blueIndex]); - area[blueIndex].AddFast(ref line); - areaSquared[greenIndex, blueIndex].AddFast(ref area[blueIndex]); - - ColorMoment moment = moments[alphaIndex - 1, redIndex, greenIndex, blueIndex]; - moment.AddFast(ref areaSquared[greenIndex, blueIndex]); - moments[alphaIndex, redIndex, greenIndex, blueIndex] = moment; - } - } - } - } - } - - /// - /// Calculates the volume of the top of the cube. - /// - /// - /// The cube to calculate the volume from. - /// - /// - /// The direction to calculate. - /// - /// - /// The position at which to begin. - /// - /// - /// The three dimensional moment. - /// - /// - /// The representing the top of the cube. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static ColorMoment Top(Box cube, int direction, int position, ColorMoment[, , ,] moment) - { - switch (direction) - { - case Alpha: - return (moment[position, cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - - moment[position, cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] - - moment[position, cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + - moment[position, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum]) - - (moment[position, cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - - moment[position, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - - moment[position, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + - moment[position, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]); - - case Red: - return (moment[cube.AlphaMaximum, position, cube.GreenMaximum, cube.BlueMaximum] - - moment[cube.AlphaMaximum, position, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.AlphaMinimum, position, cube.GreenMaximum, cube.BlueMaximum] + - moment[cube.AlphaMinimum, position, cube.GreenMinimum, cube.BlueMaximum]) - - (moment[cube.AlphaMaximum, position, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.AlphaMaximum, position, cube.GreenMinimum, cube.BlueMinimum] - - moment[cube.AlphaMinimum, position, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, position, cube.GreenMinimum, cube.BlueMinimum]); - - case Green: - return (moment[cube.AlphaMaximum, cube.RedMaximum, position, cube.BlueMaximum] - - moment[cube.AlphaMaximum, cube.RedMinimum, position, cube.BlueMaximum] - - moment[cube.AlphaMinimum, cube.RedMaximum, position, cube.BlueMaximum] + - moment[cube.AlphaMinimum, cube.RedMinimum, position, cube.BlueMaximum]) - - (moment[cube.AlphaMaximum, cube.RedMaximum, position, cube.BlueMinimum] - - moment[cube.AlphaMaximum, cube.RedMinimum, position, cube.BlueMinimum] - - moment[cube.AlphaMinimum, cube.RedMaximum, position, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMinimum, position, cube.BlueMinimum]); - - case Blue: - return (moment[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMaximum, position] - - moment[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMinimum, position] - - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMaximum, position] + - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, position]) - - (moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMaximum, position] - - moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, position] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, position] + - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, position]); - - default: - return new ColorMoment(); - } - } - - /// - /// Calculates the volume of the bottom of the cube. - /// - /// - /// The cube to calculate the volume from. - /// - /// - /// The direction to calculate. - /// - /// - /// The three dimensional moment. - /// - /// - /// The representing the bottom of the cube. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static ColorMoment Bottom(Box cube, int direction, ColorMoment[, , ,] moment) - { - switch (direction) - { - case Alpha: - return (-moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] + - moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum]) - - (-moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]); - - case Red: - return (-moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] + - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum]) - - (-moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]); - - case Green: - return (-moment[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] + - moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum]) - - (-moment[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]); - - case Blue: - return (-moment[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]) - - (-moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]); - - default: - return new ColorMoment(); - } - } - - /// - /// Maximizes the sum of the two boxes. - /// - /// - /// The . - /// - /// - /// The cube. - /// - /// - /// The direction. - /// - /// - /// The first byte. - /// - /// - /// The last byte. - /// - /// - /// The whole . - /// - /// - /// The representing the sum. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static CubeCut Maximize(ColorMoment[, , ,] moments, Box cube, int direction, byte first, byte last, ColorMoment whole) - { - ColorMoment bottom = Bottom(cube, direction, moments); - float result = 0.0f; - byte? cutPoint = null; - - for (byte position = first; position < last; ++position) - { - ColorMoment half = bottom + Top(cube, direction, position, moments); - if (half.Weight == 0) - { - continue; - } - - long temp = half.WeightedDistance(); - - half = whole - half; - if (half.Weight != 0) - { - temp += half.WeightedDistance(); - - if (temp > result) - { - result = temp; - cutPoint = position; - } - } - } - - return new CubeCut(cutPoint, result); - } - - /// - /// Returns a value indicating whether a cube can be cut. - /// - /// - /// The three dimensional array of . - /// - /// - /// The first . - /// - /// - /// The second . - /// - /// - /// The indicating the result. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static bool Cut(ColorMoment[, , ,] moments, ref Box first, ref Box second) - { - int direction; - ColorMoment whole = Volume(moments, first); - CubeCut maxAlpha = Maximize(moments, first, Alpha, (byte)(first.AlphaMinimum + 1), first.AlphaMaximum, whole); - CubeCut maxRed = Maximize(moments, first, Red, (byte)(first.RedMinimum + 1), first.RedMaximum, whole); - CubeCut maxGreen = Maximize(moments, first, Green, (byte)(first.GreenMinimum + 1), first.GreenMaximum, whole); - CubeCut maxBlue = Maximize(moments, first, Blue, (byte)(first.BlueMinimum + 1), first.BlueMaximum, whole); - - if ((maxAlpha.Value >= maxRed.Value) && (maxAlpha.Value >= maxGreen.Value) && (maxAlpha.Value >= maxBlue.Value)) - { - direction = Alpha; - if (maxAlpha.Position == null) - { - return false; - } - } - else if ((maxRed.Value >= maxAlpha.Value) && (maxRed.Value >= maxGreen.Value) - && (maxRed.Value >= maxBlue.Value)) - { - direction = Red; - } - else - { - if ((maxGreen.Value >= maxAlpha.Value) && (maxGreen.Value >= maxRed.Value) - && (maxGreen.Value >= maxBlue.Value)) - { - direction = Green; - } - else - { - direction = Blue; - } - } - - second.AlphaMaximum = first.AlphaMaximum; - second.RedMaximum = first.RedMaximum; - second.GreenMaximum = first.GreenMaximum; - second.BlueMaximum = first.BlueMaximum; - - switch (direction) - { - case Alpha: - if (maxAlpha.Position == null) - { - return false; - } - - second.AlphaMinimum = first.AlphaMaximum = (byte)maxAlpha.Position; - second.RedMinimum = first.RedMinimum; - second.GreenMinimum = first.GreenMinimum; - second.BlueMinimum = first.BlueMinimum; - break; - - case Red: - if (maxRed.Position == null) - { - return false; - } - - second.RedMinimum = first.RedMaximum = (byte)maxRed.Position; - second.AlphaMinimum = first.AlphaMinimum; - second.GreenMinimum = first.GreenMinimum; - second.BlueMinimum = first.BlueMinimum; - break; - - case Green: - if (maxGreen.Position == null) - { - return false; - } - - second.GreenMinimum = first.GreenMaximum = (byte)maxGreen.Position; - second.AlphaMinimum = first.AlphaMinimum; - second.RedMinimum = first.RedMinimum; - second.BlueMinimum = first.BlueMinimum; - break; - - case Blue: - if (maxBlue.Position == null) - { - return false; - } - - second.BlueMinimum = first.BlueMaximum = (byte)maxBlue.Position; - second.AlphaMinimum = first.AlphaMinimum; - second.RedMinimum = first.RedMinimum; - second.GreenMinimum = first.GreenMinimum; - break; - } - - first.Size = (first.AlphaMaximum - first.AlphaMinimum) * (first.RedMaximum - first.RedMinimum) * (first.GreenMaximum - first.GreenMinimum) * (first.BlueMaximum - first.BlueMinimum); - second.Size = (second.AlphaMaximum - second.AlphaMinimum) * (second.RedMaximum - second.RedMinimum) * (second.GreenMaximum - second.GreenMinimum) * (second.BlueMaximum - second.BlueMinimum); - - return true; - } - - /// - /// Calculates the variance of the volume of the cube. - /// - /// - /// The three dimensional array of . - /// - /// - /// The cube. - /// - /// - /// The representing the variance. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static float CalculateVariance(ColorMoment[, , ,] moments, Box cube) - { - ColorMoment volume = Volume(moments, cube); - return volume.Variance(); - } - - /// - /// Calculates the volume of the colors. - /// - /// - /// The three dimensional array of . - /// - /// - /// The cube. - /// - /// - /// The representing the volume. - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static ColorMoment Volume(ColorMoment[, , ,] moments, Box cube) - { - return (moments[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - - moments[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] - - moments[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + - moments[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moments[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] + - moments[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + - moments[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] - - moments[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum]) - - - (moments[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - - moments[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - - moments[cube.AlphaMaximum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moments[cube.AlphaMinimum, cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - - moments[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + - moments[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + - moments[cube.AlphaMaximum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum] - - moments[cube.AlphaMinimum, cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]); - } - - /// - /// Splits the data. - /// - /// - /// The color count. - /// - /// - /// The three dimensional array of . - /// - /// - /// The array . - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static Box[] SplitData(ref int colorCount, ColorMoment[, , ,] moments) - { - --colorCount; - int next = 0; - float[] volumeVariance = new float[colorCount]; - Box[] cubes = new Box[colorCount]; - cubes[0].AlphaMaximum = MaxSideIndex; - cubes[0].RedMaximum = MaxSideIndex; - cubes[0].GreenMaximum = MaxSideIndex; - cubes[0].BlueMaximum = MaxSideIndex; - for (int cubeIndex = 1; cubeIndex < colorCount; ++cubeIndex) - { - if (Cut(moments, ref cubes[next], ref cubes[cubeIndex])) - { - volumeVariance[next] = cubes[next].Size > 1 ? CalculateVariance(moments, cubes[next]) : 0.0f; - volumeVariance[cubeIndex] = cubes[cubeIndex].Size > 1 ? CalculateVariance(moments, cubes[cubeIndex]) : 0.0f; - } - else - { - volumeVariance[next] = 0.0f; - cubeIndex--; - } - - next = 0; - float temp = volumeVariance[0]; - - for (int index = 1; index <= cubeIndex; ++index) - { - if (volumeVariance[index] <= temp) - { - continue; - } - - temp = volumeVariance[index]; - next = index; - } - - if (temp > 0.0) - { - continue; - } - - colorCount = cubeIndex + 1; - break; - } - - return cubes.Take(colorCount).ToArray(); - } - - /// - /// Builds an array of pixel data to look within. - /// - /// - /// The array of cubes. - /// - /// - /// The three dimensional array of . - /// - /// - /// The array of . - /// - [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1001:CommasMustBeSpacedCorrectly", Justification = "Reviewed. Suppression is OK here.")] - private static Color32[] BuildLookups(Box[] cubes, ColorMoment[, , ,] moments) - { - Color32[] lookups = new Color32[cubes.Length]; - - for (int cubeIndex = 0; cubeIndex < cubes.Length; cubeIndex++) - { - ColorMoment volume = Volume(moments, cubes[cubeIndex]); - - if (volume.Weight <= 0) - { - continue; - } - - Color32 lookup = new Color32 - { - A = (byte)(volume.Alpha / volume.Weight), - R = (byte)(volume.Red / volume.Weight), - G = (byte)(volume.Green / volume.Weight), - B = (byte)(volume.Blue / volume.Weight) - }; - - lookups[cubeIndex] = lookup; - } - - return lookups; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/ResizeLayer.cs b/old/src/ImageProcessor/Imaging/ResizeLayer.cs deleted file mode 100644 index ac6202f83..000000000 --- a/old/src/ImageProcessor/Imaging/ResizeLayer.cs +++ /dev/null @@ -1,167 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the properties required to resize an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - #region Using - - using System.Collections.Generic; - using System.Drawing; - using System.Linq; - - #endregion - - /// - /// Encapsulates the properties required to resize an image. - /// - public class ResizeLayer - { - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The containing the width and height to set the image to. - /// - /// - /// The resize mode to apply to resized image. (Default ResizeMode.Pad) - /// - /// - /// The to apply to resized image. (Default AnchorPosition.Center) - /// - /// - /// Whether to allow up-scaling of images. (Default true) - /// - /// - /// The center coordinates (Default null) - /// - /// - /// The maximum size to resize an image to. - /// Used to restrict resizing based on calculated resizing - /// - /// - /// The range of sizes to restrict resizing an image to. - /// Used to restrict resizing based on calculated resizing - /// - public ResizeLayer( - Size size, - ResizeMode resizeMode = ResizeMode.Pad, - AnchorPosition anchorPosition = AnchorPosition.Center, - bool upscale = true, - float[] centerCoordinates = null, - Size? maxSize = null, - List restrictedSizes = null) - { - this.Size = size; - this.Upscale = upscale; - this.ResizeMode = resizeMode; - this.AnchorPosition = anchorPosition; - this.CenterCoordinates = centerCoordinates ?? new float[] { }; - this.MaxSize = maxSize; - this.RestrictedSizes = restrictedSizes ?? new List(); - } - #endregion - - #region Properties - /// - /// Gets or sets the size. - /// - public Size Size { get; set; } - - /// - /// Gets or sets the max size. - /// - public Size? MaxSize { get; set; } - - /// - /// Gets or sets the restricted range of sizes. to restrict resizing methods to. - /// - public List RestrictedSizes { get; set; } - - /// - /// Gets or sets the resize mode. - /// - public ResizeMode ResizeMode { get; set; } - - /// - /// Gets or sets the anchor position. - /// - public AnchorPosition AnchorPosition { get; set; } - - /// - /// Gets or sets a value indicating whether to allow up-scaling of images. - /// - public bool Upscale { get; set; } - - /// - /// Gets or sets the center coordinates. - /// - public float[] CenterCoordinates { get; set; } - #endregion - - /// - /// Returns a value that indicates whether the specified object is an - /// object that is equivalent to - /// this object. - /// - /// - /// The object to test. - /// - /// - /// True if the given object is an object that is equivalent to - /// this object; otherwise, false. - /// - public override bool Equals(object obj) - { - ResizeLayer resizeLayer = obj as ResizeLayer; - - if (resizeLayer == null) - { - return false; - } - - return this.Size == resizeLayer.Size - && this.ResizeMode == resizeLayer.ResizeMode - && this.AnchorPosition == resizeLayer.AnchorPosition - && this.Upscale == resizeLayer.Upscale - && ((this.CenterCoordinates != null - && resizeLayer.CenterCoordinates != null - && this.CenterCoordinates.SequenceEqual(resizeLayer.CenterCoordinates)) - || (this.CenterCoordinates == resizeLayer.CenterCoordinates)) - && this.MaxSize == resizeLayer.MaxSize - && ((this.RestrictedSizes != null - && resizeLayer.RestrictedSizes != null - && this.RestrictedSizes.SequenceEqual(resizeLayer.RestrictedSizes)) - || (this.RestrictedSizes == resizeLayer.RestrictedSizes)); - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.Size.GetHashCode(); - hashCode = (hashCode * 397) ^ this.MaxSize.GetHashCode(); - hashCode = (hashCode * 397) ^ (this.RestrictedSizes != null ? this.RestrictedSizes.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (int)this.ResizeMode; - hashCode = (hashCode * 397) ^ (int)this.AnchorPosition; - hashCode = (hashCode * 397) ^ this.Upscale.GetHashCode(); - hashCode = (hashCode * 397) ^ (this.CenterCoordinates != null ? this.CenterCoordinates.GetHashCode() : 0); - return hashCode; - } - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Imaging/ResizeMode.cs b/old/src/ImageProcessor/Imaging/ResizeMode.cs deleted file mode 100644 index 5ad648088..000000000 --- a/old/src/ImageProcessor/Imaging/ResizeMode.cs +++ /dev/null @@ -1,38 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Enumerated resize modes to apply to resized images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - /// - /// Enumerated resize modes to apply to resized images. - /// - public enum ResizeMode - { - /// - /// Pads the resized image to fit the bounds of its container. - /// - Pad, - - /// - /// Stretches the resized image to fit the bounds of its container. - /// - Stretch, - - /// - /// Crops the resized image to fit the bounds of its container. - /// - Crop, - - /// - /// Constrains the resized image to fit the bounds of its container. - /// - Max - } -} diff --git a/old/src/ImageProcessor/Imaging/Resizer.cs b/old/src/ImageProcessor/Imaging/Resizer.cs deleted file mode 100644 index 7fd24c674..000000000 --- a/old/src/ImageProcessor/Imaging/Resizer.cs +++ /dev/null @@ -1,390 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides methods to resize images. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Drawing.Imaging; - using System.Linq; - - using ImageProcessor.Common.Exceptions; - - /// - /// Provides methods to resize images. - /// - public class Resizer - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The to resize the image to. - /// - public Resizer(Size size) - { - this.ResizeLayer = new ResizeLayer(size); - } - - /// - /// Initializes a new instance of the class. - /// - /// - /// The . - /// - public Resizer(ResizeLayer resizeLayer) - { - this.ResizeLayer = resizeLayer; - } - - /// - /// Gets or sets the . - /// - public ResizeLayer ResizeLayer { get; set; } - - /// - /// Resizes the given image. - /// - /// - /// The source to resize - /// - /// - /// The resized . - /// - public Bitmap ResizeImage(Image source) - { - int width = this.ResizeLayer.Size.Width; - int height = this.ResizeLayer.Size.Height; - ResizeMode mode = this.ResizeLayer.ResizeMode; - AnchorPosition anchor = this.ResizeLayer.AnchorPosition; - bool upscale = this.ResizeLayer.Upscale; - float[] centerCoordinates = this.ResizeLayer.CenterCoordinates; - int maxWidth = this.ResizeLayer.MaxSize.HasValue ? this.ResizeLayer.MaxSize.Value.Width : int.MaxValue; - int maxHeight = this.ResizeLayer.MaxSize.HasValue ? this.ResizeLayer.MaxSize.Value.Height : int.MaxValue; - List restrictedSizes = this.ResizeLayer.RestrictedSizes; - - return this.ResizeImage(source, width, height, maxWidth, maxHeight, restrictedSizes, mode, anchor, upscale, centerCoordinates); - } - - /// - /// Resizes the given image. - /// - /// - /// The source to resize - /// - /// - /// The width to resize the image to. - /// - /// - /// The height to resize the image to. - /// - /// - /// The default max width to resize the image to. - /// - /// - /// The default max height to resize the image to. - /// - /// - /// A containing image resizing restrictions. - /// - /// - /// The mode with which to resize the image. - /// - /// - /// The anchor position to place the image at. - /// - /// - /// Whether to allow up-scaling of images. (Default true) - /// - /// - /// If the resize mode is crop, you can set a specific center coordinate, use as alternative to anchorPosition - /// - /// - /// The resized . - /// - private Bitmap ResizeImage( - Image source, - int width, - int height, - int maxWidth, - int maxHeight, - List restrictedSizes, - ResizeMode resizeMode = ResizeMode.Pad, - AnchorPosition anchorPosition = AnchorPosition.Center, - bool upscale = true, - float[] centerCoordinates = null) - { - Bitmap newImage = null; - - try - { - int sourceWidth = source.Width; - int sourceHeight = source.Height; - - int destinationWidth = width; - int destinationHeight = height; - - maxWidth = maxWidth > 0 ? maxWidth : int.MaxValue; - maxHeight = maxHeight > 0 ? maxHeight : int.MaxValue; - - // Fractional variants for preserving aspect ratio. - double percentHeight = Math.Abs(height / (double)sourceHeight); - double percentWidth = Math.Abs(width / (double)sourceWidth); - - int destinationX = 0; - int destinationY = 0; - - // Change the destination rectangle coordinates if padding and - // there has been a set width and height. - if (resizeMode == ResizeMode.Pad && width > 0 && height > 0) - { - double ratio; - - if (percentHeight < percentWidth) - { - ratio = percentHeight; - destinationWidth = Convert.ToInt32(sourceWidth * percentHeight); - - switch (anchorPosition) - { - case AnchorPosition.Left: - destinationX = 0; - break; - case AnchorPosition.Right: - destinationX = (int)(width - (sourceWidth * ratio)); - break; - default: - destinationX = Convert.ToInt32((width - (sourceWidth * ratio)) / 2); - break; - } - } - else - { - ratio = percentWidth; - destinationHeight = Convert.ToInt32(sourceHeight * percentWidth); - - switch (anchorPosition) - { - case AnchorPosition.Top: - destinationY = 0; - break; - case AnchorPosition.Bottom: - destinationY = (int)(height - (sourceHeight * ratio)); - break; - default: - destinationY = (int)((height - (sourceHeight * ratio)) / 2); - break; - } - } - } - - // Change the destination rectangle coordinates if cropping and - // there has been a set width and height. - if (resizeMode == ResizeMode.Crop && width > 0 && height > 0) - { - double ratio; - - if (percentHeight < percentWidth) - { - ratio = percentWidth; - - if (centerCoordinates != null && centerCoordinates.Any()) - { - double center = -(ratio * sourceHeight) * centerCoordinates[0]; - destinationY = (int)center + (height / 2); - - if (destinationY > 0) - { - destinationY = 0; - } - - if (destinationY < (int)(height - (sourceHeight * ratio))) - { - destinationY = (int)(height - (sourceHeight * ratio)); - } - } - else - { - switch (anchorPosition) - { - case AnchorPosition.Top: - destinationY = 0; - break; - case AnchorPosition.Bottom: - destinationY = (int)(height - (sourceHeight * ratio)); - break; - default: - destinationY = (int)((height - (sourceHeight * ratio)) / 2); - break; - } - } - - destinationHeight = (int)Math.Ceiling(sourceHeight * percentWidth); - } - else - { - ratio = percentHeight; - - if (centerCoordinates != null && centerCoordinates.Any()) - { - double center = -(ratio * sourceWidth) * centerCoordinates[1]; - destinationX = (int)center + (width / 2); - - if (destinationX > 0) - { - destinationX = 0; - } - - if (destinationX < (int)(width - (sourceWidth * ratio))) - { - destinationX = (int)(width - (sourceWidth * ratio)); - } - } - else - { - switch (anchorPosition) - { - case AnchorPosition.Left: - destinationX = 0; - break; - case AnchorPosition.Right: - destinationX = (int)(width - (sourceWidth * ratio)); - break; - default: - destinationX = (int)((width - (sourceWidth * ratio)) / 2); - break; - } - } - - destinationWidth = (int)Math.Ceiling(sourceWidth * percentHeight); - } - } - - // Constrain the image to fit the maximum possible height or width. - if (resizeMode == ResizeMode.Max) - { - // If either is 0, we don't need to figure out orientation - if (width > 0 && height > 0) - { - // Integers must be cast to doubles to get needed precision - double ratio = (double)height / width; - double sourceRatio = (double)sourceHeight / sourceWidth; - - if (sourceRatio < ratio) - { - height = 0; - } - else - { - width = 0; - } - } - } - - // If height or width is not passed we assume that the standard ratio is to be kept. - if (height == 0) - { - destinationHeight = Convert.ToInt32(sourceHeight * percentWidth); - height = destinationHeight; - } - - if (width == 0) - { - destinationWidth = Convert.ToInt32(sourceWidth * percentHeight); - width = destinationWidth; - } - - // Restrict sizes - if (restrictedSizes != null && restrictedSizes.Any()) - { - bool reject = true; - foreach (Size restrictedSize in restrictedSizes) - { - if (restrictedSize.Height == 0 || restrictedSize.Width == 0) - { - if (restrictedSize.Width == width || restrictedSize.Height == height) - { - reject = false; - } - } - else if (restrictedSize.Width == width && restrictedSize.Height == height) - { - reject = false; - } - } - - if (reject) - { - return (Bitmap)source; - } - } - - if (width > 0 && height > 0 && width <= maxWidth && height <= maxHeight) - { - // Exit if upscaling is not allowed. - if ((width > sourceWidth || height > sourceHeight) && upscale == false && resizeMode != ResizeMode.Stretch) - { - return (Bitmap)source; - } - - newImage = new Bitmap(width, height); - newImage.SetResolution(source.HorizontalResolution, source.VerticalResolution); - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - // We want to use two different blending algorithms for enlargement/shrinking. - if (source.Width < destinationWidth && source.Height < destinationHeight) - { - // We are making it larger. - graphics.SmoothingMode = SmoothingMode.AntiAlias; - } - else - { - // We are making it smaller. - graphics.SmoothingMode = SmoothingMode.None; - } - - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image - // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge - // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror - // images of the pixels within solves this problem. - using (ImageAttributes wrapMode = new ImageAttributes()) - { - wrapMode.SetWrapMode(WrapMode.TileFlipXY); - Rectangle destinationRectangle = new Rectangle(destinationX, destinationY, destinationWidth, destinationHeight); - graphics.DrawImage(source, destinationRectangle, 0, 0, sourceWidth, sourceHeight, GraphicsUnit.Pixel, wrapMode); - } - - // Reassign the image. - source.Dispose(); - source = newImage; - } - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return (Bitmap)source; - } - } -} diff --git a/old/src/ImageProcessor/Imaging/RoundedCornerLayer.cs b/old/src/ImageProcessor/Imaging/RoundedCornerLayer.cs deleted file mode 100644 index efa3deacc..000000000 --- a/old/src/ImageProcessor/Imaging/RoundedCornerLayer.cs +++ /dev/null @@ -1,117 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the properties required to add rounded corners to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - /// - /// Encapsulates the properties required to add rounded corners to an image. - /// - public class RoundedCornerLayer - { - /// - /// Initializes a new instance of the class. - /// - /// - /// The radius at which the corner will be rounded. - /// - /// - /// Set if top left is rounded - /// - /// - /// Set if top right is rounded - /// - /// - /// Set if bottom left is rounded - /// - /// - /// Set if bottom right is rounded - /// - public RoundedCornerLayer(int radius, bool topLeft = true, bool topRight = true, bool bottomLeft = true, bool bottomRight = true) - { - this.Radius = radius; - this.TopLeft = topLeft; - this.TopRight = topRight; - this.BottomLeft = bottomLeft; - this.BottomRight = bottomRight; - } - - #region Properties - /// - /// Gets or sets the radius of the corners. - /// - public int Radius { get; set; } - - /// - /// Gets or sets a value indicating whether top left corners are to be added. - /// - public bool TopLeft { get; set; } - - /// - /// Gets or sets a value indicating whether top right corners are to be added. - /// - public bool TopRight { get; set; } - - /// - /// Gets or sets a value indicating whether bottom left corners are to be added. - /// - public bool BottomLeft { get; set; } - - /// - /// Gets or sets a value indicating whether bottom right corners are to be added. - /// - public bool BottomRight { get; set; } - #endregion - - /// - /// Returns a value that indicates whether the specified object is an - /// object that is equivalent to - /// this object. - /// - /// - /// The object to test. - /// - /// - /// True if the given object is an object that is equivalent to - /// this object; otherwise, false. - /// - public override bool Equals(object obj) - { - RoundedCornerLayer rounded = obj as RoundedCornerLayer; - - if (rounded == null) - { - return false; - } - - return this.Radius == rounded.Radius - && this.TopLeft == rounded.TopLeft && this.TopRight == rounded.TopRight - && this.BottomLeft == rounded.BottomLeft && this.BottomRight == rounded.BottomRight; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.Radius; - hashCode = (hashCode * 397) ^ this.TopLeft.GetHashCode(); - hashCode = (hashCode * 397) ^ this.TopRight.GetHashCode(); - hashCode = (hashCode * 397) ^ this.BottomLeft.GetHashCode(); - hashCode = (hashCode * 397) ^ this.BottomRight.GetHashCode(); - return hashCode; - } - } - } -} diff --git a/old/src/ImageProcessor/Imaging/TextLayer.cs b/old/src/ImageProcessor/Imaging/TextLayer.cs deleted file mode 100644 index 12b049e42..000000000 --- a/old/src/ImageProcessor/Imaging/TextLayer.cs +++ /dev/null @@ -1,189 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the properties required to add a layer of text to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Imaging -{ - using System.Drawing; - using System.Drawing.Text; - - /// - /// Encapsulates the properties required to add a layer of text to an image. - /// - public class TextLayer - { - #region Fields - /// - /// The color to render the text. - /// - private Color textColor = Color.Black; - - /// - /// The opacity at which to render the text. - /// - private int opacity = 100; - - /// - /// The font style to render the text. - /// - private FontStyle fontStyle = FontStyle.Regular; - - /// - /// The font family to render the text. - /// - private FontFamily fontFamily = new FontFamily(GenericFontFamilies.SansSerif); - - /// - /// The font size to render the text. - /// - private int fontSize = 48; - #endregion - - #region Properties - /// - /// Gets or sets Text. - /// - public string Text { get; set; } - - /// - /// Gets or sets the to render the font. - /// - /// Defaults to black. - /// - /// - public Color FontColor - { - get { return this.textColor; } - set { this.textColor = value; } - } - - /// - /// Gets or sets the name of the font family. - /// - /// Defaults to generic sans-serif font family. - /// - /// - public FontFamily FontFamily - { - get { return this.fontFamily; } - set { this.fontFamily = value; } - } - - /// - /// Gets or sets the size of the font in pixels. - /// - /// Defaults to 48 pixels. - /// - /// - public int FontSize - { - get { return this.fontSize; } - set { this.fontSize = value; } - } - - /// - /// Gets or sets the FontStyle of the text layer. - /// - /// Defaults to regular. - /// - /// - public FontStyle Style - { - get { return this.fontStyle; } - set { this.fontStyle = value; } - } - - /// - /// Gets or sets the Opacity of the text layer. - /// - public int Opacity - { - get { return this.opacity; } - set { this.opacity = value; } - } - - /// - /// Gets or sets the Position of the text layer. - /// - public Point? Position { get; set; } - - /// - /// Gets or sets a value indicating whether a DropShadow should be drawn. - /// - public bool DropShadow { get; set; } - - /// - /// Gets or sets a value indicating whether the text should be rendered vertically. - /// - public bool Vertical { get; set; } - - /// - /// Gets or sets a value indicating whether the text should be rendered right to left. - /// - public bool RightToLeft { get; set; } - #endregion - - /// - /// Returns a value that indicates whether the specified object is an - /// object that is equivalent to - /// this object. - /// - /// - /// The object to test. - /// - /// - /// True if the given object is an object that is equivalent to - /// this object; otherwise, false. - /// - public override bool Equals(object obj) - { - TextLayer textLayer = obj as TextLayer; - - if (textLayer == null) - { - return false; - } - - return this.Text == textLayer.Text - && this.FontColor == textLayer.FontColor - && this.FontFamily.Equals(textLayer.FontFamily) - && this.FontSize == textLayer.FontSize - && this.Style == textLayer.Style - && this.DropShadow == textLayer.DropShadow - && this.Opacity == textLayer.Opacity - && this.Position == textLayer.Position - && this.Vertical == textLayer.Vertical - && this.RightToLeft == textLayer.RightToLeft; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = this.Text != null ? this.Text.GetHashCode() : 0; - hashCode = (hashCode * 397) ^ this.DropShadow.GetHashCode(); - hashCode = (hashCode * 397) ^ (this.FontFamily != null ? this.FontFamily.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (int)this.Style; - hashCode = (hashCode * 397) ^ this.FontColor.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Opacity; - hashCode = (hashCode * 397) ^ this.FontSize; - hashCode = (hashCode * 397) ^ this.Position.GetHashCode(); - hashCode = (hashCode * 397) ^ this.Vertical.GetHashCode(); - hashCode = (hashCode * 397) ^ this.RightToLeft.GetHashCode(); - return hashCode; - } - } - } -} diff --git a/old/src/ImageProcessor/Processors/Alpha.cs b/old/src/ImageProcessor/Processors/Alpha.cs deleted file mode 100644 index 621f4f8cb..000000000 --- a/old/src/ImageProcessor/Processors/Alpha.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the alpha component of the image to effect its transparency. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods to change the alpha component of the image to effect its transparency. - /// - public class Alpha : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Alpha() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - int percentage = this.DynamicParameter; - - newImage = new Bitmap(image); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - newImage = Adjustments.Alpha(newImage, percentage); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/AutoRotate.cs b/old/src/ImageProcessor/Processors/AutoRotate.cs deleted file mode 100644 index 67b91f81d..000000000 --- a/old/src/ImageProcessor/Processors/AutoRotate.cs +++ /dev/null @@ -1,112 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Performs auto-rotation to ensure that EXIF defined rotation is reflected in -// the final image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.MetaData; - - /// - /// Performs auto-rotation to ensure that EXIF defined rotation is reflected in - /// the final image. - /// - public class AutoRotate : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public AutoRotate() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// The current instance of the - /// class containing - /// the image to process. - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - const int Orientation = (int)ExifPropertyTag.Orientation; - if (!factory.PreserveExifData && factory.ExifPropertyItems.ContainsKey(Orientation)) - { - newImage = new Bitmap(image); - - int rotationValue = factory.ExifPropertyItems[Orientation].Value[0]; - switch (rotationValue) - { - case 1: // Landscape, do nothing - break; - - case 8: // Rotated 90 right - // De-rotate: - newImage.RotateFlip(RotateFlipType.Rotate270FlipNone); - break; - - case 3: // Bottoms up - newImage.RotateFlip(RotateFlipType.Rotate180FlipNone); - break; - - case 6: // Rotated 90 left - newImage.RotateFlip(RotateFlipType.Rotate90FlipNone); - break; - } - - // Reassign the image. - image.Dispose(); - image = newImage; - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/BackgroundColor.cs b/old/src/ImageProcessor/Processors/BackgroundColor.cs deleted file mode 100644 index 9d446f094..000000000 --- a/old/src/ImageProcessor/Processors/BackgroundColor.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Changes the background color of an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - - /// - /// Changes the background color of an image. - /// - public class BackgroundColor : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public BackgroundColor() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the DynamicParameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// The current instance of the - /// class containing - /// the image to process. - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - int width = image.Width; - int height = image.Height; - - Color backgroundColor = this.DynamicParameter; - newImage = new Bitmap(width, height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Make a graphics object from the empty bitmap. - using (Graphics graphics = Graphics.FromImage(newImage)) - { - // Fill the background. - graphics.Clear(backgroundColor); - - // Draw passed in image onto graphics object. - graphics.DrawImage(image, 0, 0, width, height); - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/Brightness.cs b/old/src/ImageProcessor/Processors/Brightness.cs deleted file mode 100644 index 8e4b92e6d..000000000 --- a/old/src/ImageProcessor/Processors/Brightness.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the brightness component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods to change the brightness component of the image. - /// - public class Brightness : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Brightness() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - int threshold = (int)this.DynamicParameter; - newImage = new Bitmap(image); - newImage = Adjustments.Brightness(newImage, threshold); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Contrast.cs b/old/src/ImageProcessor/Processors/Contrast.cs deleted file mode 100644 index 8a6491257..000000000 --- a/old/src/ImageProcessor/Processors/Contrast.cs +++ /dev/null @@ -1,88 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the contrast component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods to change the contrast component of the image. - /// - public class Contrast : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Contrast() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - int threshold = (int)this.DynamicParameter; - newImage = new Bitmap(image); - newImage = Adjustments.Contrast(newImage, threshold); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Crop.cs b/old/src/ImageProcessor/Processors/Crop.cs deleted file mode 100644 index dda79132b..000000000 --- a/old/src/ImageProcessor/Processors/Crop.cs +++ /dev/null @@ -1,156 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Crops an image to the given directions. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Drawing.Imaging; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - - /// - /// Crops an image to the given directions. - /// - public class Crop : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Crop() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - try - { - int sourceWidth = image.Width; - int sourceHeight = image.Height; - RectangleF rectangleF; - CropLayer cropLayer = this.DynamicParameter; - - if (cropLayer.CropMode == CropMode.Percentage) - { - // Fix for whole numbers. - cropLayer.Left = cropLayer.Left > 1 ? cropLayer.Left / 100 : cropLayer.Left; - cropLayer.Right = cropLayer.Right > 1 ? cropLayer.Right / 100 : cropLayer.Right; - cropLayer.Top = cropLayer.Top > 1 ? cropLayer.Top / 100 : cropLayer.Top; - cropLayer.Bottom = cropLayer.Bottom > 1 ? cropLayer.Bottom / 100 : cropLayer.Bottom; - - // Work out the percentages. - float left = cropLayer.Left * sourceWidth; - float top = cropLayer.Top * sourceHeight; - float width = (1 - cropLayer.Left - cropLayer.Right) * sourceWidth; - float height = (1 - cropLayer.Top - cropLayer.Bottom) * sourceHeight; - - rectangleF = new RectangleF(left, top, width, height); - } - else - { - rectangleF = new RectangleF(cropLayer.Left, cropLayer.Top, cropLayer.Right, cropLayer.Bottom); - } - - Rectangle rectangle = Rectangle.Round(rectangleF); - - if (rectangle.X < sourceWidth && rectangle.Y < sourceHeight) - { - if (rectangle.Width > (sourceWidth - rectangle.X)) - { - rectangle.Width = sourceWidth - rectangle.X; - } - - if (rectangle.Height > (sourceHeight - rectangle.Y)) - { - rectangle.Height = sourceHeight - rectangle.Y; - } - - newImage = new Bitmap(rectangle.Width, rectangle.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image - // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge - // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror - // images of the pixels within solves this problem. - using (ImageAttributes wrapMode = new ImageAttributes()) - { - wrapMode.SetWrapMode(WrapMode.TileFlipXY); - graphics.DrawImage( - image, - new Rectangle(0, 0, rectangle.Width, rectangle.Height), - rectangle.X, - rectangle.Y, - rectangle.Width, - rectangle.Height, - GraphicsUnit.Pixel, - wrapMode); - } - } - - // Reassign the image. - image.Dispose(); - image = newImage; - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/DetectEdges.cs b/old/src/ImageProcessor/Processors/DetectEdges.cs deleted file mode 100644 index 1f0d480e8..000000000 --- a/old/src/ImageProcessor/Processors/DetectEdges.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Produces an image with the detected edges highlighted. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Filters.EdgeDetection; - - /// - /// Produces an image with the detected edges highlighted. - /// - public class DetectEdges : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public DetectEdges() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - Tuple parameters = this.DynamicParameter; - IEdgeFilter filter = parameters.Item1; - bool greyscale = parameters.Item2; - - try - { - ConvolutionFilter convolutionFilter = new ConvolutionFilter(filter, greyscale); - - // Check and assign the correct method. Don't use reflection for speed. - newImage = filter is I2DEdgeFilter - ? convolutionFilter.Process2DFilter((Bitmap)image) - : convolutionFilter.ProcessFilter((Bitmap)image); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/DetectObjects.cs b/old/src/ImageProcessor/Processors/DetectObjects.cs deleted file mode 100644 index 417c55a3a..000000000 --- a/old/src/ImageProcessor/Processors/DetectObjects.cs +++ /dev/null @@ -1,119 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the DetectObjects component of the image to effect its transparency. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Filters.ObjectDetection; - using ImageProcessor.Imaging.Filters.Photo; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods to change the DetectObjects component of the image to effect its transparency. - /// - public class DetectObjects : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public DetectObjects() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Bitmap grey = null; - Image image = factory.Image; - - try - { - HaarCascade cascade = this.DynamicParameter; - grey = new Bitmap(image.Width, image.Height); - grey.SetResolution(image.HorizontalResolution, image.VerticalResolution); - grey = MatrixFilters.GreyScale.TransformImage(image, grey); - - HaarObjectDetector detector = new HaarObjectDetector(cascade) - { - SearchMode = ObjectDetectorSearchMode.NoOverlap, - ScalingMode = ObjectDetectorScalingMode.GreaterToSmaller, - ScalingFactor = 1.5f - }; - - // Process frame to detect objects - Rectangle[] rectangles = detector.ProcessFrame(grey); - grey.Dispose(); - - newImage = new Bitmap(image); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - using (Graphics graphics = Graphics.FromImage(newImage)) - { - using (Pen blackPen = new Pen(Color.White)) - { - blackPen.Width = 4; - graphics.DrawRectangles(blackPen, rectangles); - } - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (grey != null) - { - grey.Dispose(); - } - - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/EntropyCrop.cs b/old/src/ImageProcessor/Processors/EntropyCrop.cs deleted file mode 100644 index ad6812643..000000000 --- a/old/src/ImageProcessor/Processors/EntropyCrop.cs +++ /dev/null @@ -1,105 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Filters.Binarization; - using ImageProcessor.Imaging.Filters.EdgeDetection; - using ImageProcessor.Imaging.Helpers; - - /// - /// Performs a crop on an image to the area of greatest entropy. - /// - public class EntropyCrop : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public EntropyCrop() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Bitmap grey = null; - Image image = factory.Image; - byte threshold = this.DynamicParameter; - - try - { - // Detect the edges then strip out middle shades. - grey = new ConvolutionFilter(new SobelEdgeFilter(), true).Process2DFilter(image); - grey = new BinaryThreshold(threshold).ProcessFilter(grey); - - // Search for the first white pixels - Rectangle rectangle = ImageMaths.GetFilteredBoundingRectangle(grey, 0); - grey.Dispose(); - - newImage = new Bitmap(rectangle.Width, rectangle.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - using (Graphics graphics = Graphics.FromImage(newImage)) - { - graphics.DrawImage( - image, - new Rectangle(0, 0, rectangle.Width, rectangle.Height), - rectangle.X, - rectangle.Y, - rectangle.Width, - rectangle.Height, - GraphicsUnit.Pixel); - } - - // Reassign the image. - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (grey != null) - { - grey.Dispose(); - } - - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/Filter.cs b/old/src/ImageProcessor/Processors/Filter.cs deleted file mode 100644 index 25b3f2132..000000000 --- a/old/src/ImageProcessor/Processors/Filter.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add filters to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Filters.Photo; - - /// - /// Encapsulates methods with which to add filters to an image. - /// - public class Filter : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Filter() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - newImage = new Bitmap(image.Width, image.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - IMatrixFilter matrix = this.DynamicParameter; - newImage = matrix.TransformImage(image, newImage); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Flip.cs b/old/src/ImageProcessor/Processors/Flip.cs deleted file mode 100644 index 21c4496e6..000000000 --- a/old/src/ImageProcessor/Processors/Flip.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Flips an image horizontally or vertically. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - - /// - /// Flips an image horizontally or vertically. - /// - public class Flip : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Flip() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - RotateFlipType rotateFlipType = this.DynamicParameter; - - newImage = new Bitmap(image); - - // Flip - newImage.RotateFlip(rotateFlipType); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Format.cs b/old/src/ImageProcessor/Processors/Format.cs deleted file mode 100644 index 2695180af..000000000 --- a/old/src/ImageProcessor/Processors/Format.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Sets the output of the image to a specific format. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Formats; - - /// - /// Sets the output of the image to a specific format. - /// - public class Format : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Format() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - try - { - ISupportedImageFormat format = this.DynamicParameter; - factory.Format(format); - } - catch (Exception ex) - { - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return factory.Image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Gamma.cs b/old/src/ImageProcessor/Processors/Gamma.cs deleted file mode 100644 index 09ce69548..000000000 --- a/old/src/ImageProcessor/Processors/Gamma.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the alpha component of the image to effect its luminance. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods to change the gamma component of the image to effect its luminance. - /// - public class Gamma : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Gamma() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - float value = this.DynamicParameter; - - newImage = new Bitmap(image); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - newImage = Adjustments.Gamma(newImage, value); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/GaussianBlur.cs b/old/src/ImageProcessor/Processors/GaussianBlur.cs deleted file mode 100644 index 1ddf9e787..000000000 --- a/old/src/ImageProcessor/Processors/GaussianBlur.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Applies a Gaussian blur to the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - - /// - /// Applies a Gaussian blur to the image. - /// - public class GaussianBlur : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public GaussianBlur() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the DynamicParameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// The current instance of the class containing - /// the image to process. - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Bitmap image = (Bitmap)factory.Image; - - try - { - newImage = new Bitmap(image); - GaussianLayer gaussianLayer = this.DynamicParameter; - - Convolution convolution = new Convolution(gaussianLayer.Sigma) { Threshold = gaussianLayer.Threshold }; - double[,] kernel = convolution.CreateGuassianBlurFilter(gaussianLayer.Size); - newImage = convolution.ProcessKernel(newImage, kernel); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/GaussianSharpen.cs b/old/src/ImageProcessor/Processors/GaussianSharpen.cs deleted file mode 100644 index 8aaf84e5d..000000000 --- a/old/src/ImageProcessor/Processors/GaussianSharpen.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Applies a Gaussian sharpen to the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - - /// - /// Applies a Gaussian sharpen to the image. - /// - public class GaussianSharpen : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public GaussianSharpen() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the DynamicParameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// The current instance of the class containing - /// the image to process. - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Bitmap image = (Bitmap)factory.Image; - - try - { - newImage = new Bitmap(image); - GaussianLayer gaussianLayer = this.DynamicParameter; - - Convolution convolution = new Convolution(gaussianLayer.Sigma) { Threshold = gaussianLayer.Threshold }; - double[,] kernel = convolution.CreateGuassianSharpenFilter(gaussianLayer.Size); - newImage = convolution.ProcessKernel(newImage, kernel); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Halftone.cs b/old/src/ImageProcessor/Processors/Halftone.cs deleted file mode 100644 index 081776610..000000000 --- a/old/src/ImageProcessor/Processors/Halftone.cs +++ /dev/null @@ -1,122 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The halftone processor applies a classical CMYK halftone to the given image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Filters.Artistic; - using ImageProcessor.Imaging.Helpers; - - /// - /// The halftone processor applies a classical CMYK halftone to the given image. - /// - public class Halftone : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Halftone() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Image image = factory.Image; - int width = image.Width; - int height = image.Height; - Bitmap newImage = null; - Bitmap edgeBitmap = null; - try - { - HalftoneFilter filter = new HalftoneFilter(5); - newImage = new Bitmap(image); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - newImage = filter.ApplyFilter(newImage); - bool comicMode = this.DynamicParameter; - - if (comicMode) - { - // Draw the edges. - edgeBitmap = new Bitmap(width, height); - edgeBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); - edgeBitmap = Effects.Trace(image, edgeBitmap, 120); - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - // Overlay the image. - graphics.DrawImage(edgeBitmap, 0, 0); - Rectangle rectangle = new Rectangle(0, 0, width, height); - - // Draw an edge around the image. - using (Pen blackPen = new Pen(Color.Black)) - { - blackPen.Width = 4; - graphics.DrawRectangle(blackPen, rectangle); - } - } - - edgeBitmap.Dispose(); - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (edgeBitmap != null) - { - edgeBitmap.Dispose(); - } - - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Hue.cs b/old/src/ImageProcessor/Processors/Hue.cs deleted file mode 100644 index a3ccc4c5e..000000000 --- a/old/src/ImageProcessor/Processors/Hue.cs +++ /dev/null @@ -1,112 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to rotate the hue component of an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Colors; - - /// - /// Encapsulates methods to adjust the hue component of an image. - /// - public class Hue : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Hue() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - Tuple parameters = this.DynamicParameter; - int degrees = parameters.Item1; - bool rotate = parameters.Item2; - int width = image.Width; - int height = image.Height; - - newImage = new Bitmap(image); - - using (FastBitmap fastBitmap = new FastBitmap(newImage)) - { - if (!rotate) - { - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - HslaColor original = HslaColor.FromColor(fastBitmap.GetPixel(x, y)); - HslaColor altered = HslaColor.FromHslaColor(degrees / 360f, original.S, original.L, original.A); - fastBitmap.SetPixel(x, y, altered); - } - } - } - else - { - for (int y = 0; y < height; y++) - { - for (int x = 0; x < width; x++) - { - HslaColor original = HslaColor.FromColor(fastBitmap.GetPixel(x, y)); - HslaColor altered = HslaColor.FromHslaColor((original.H + (degrees / 360f)) % 1, original.S, original.L, original.A); - fastBitmap.SetPixel(x, y, altered); - } - } - } - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/IGraphicsProcessor.cs b/old/src/ImageProcessor/Processors/IGraphicsProcessor.cs deleted file mode 100644 index 79f3e66c6..000000000 --- a/old/src/ImageProcessor/Processors/IGraphicsProcessor.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Defines properties and methods for ImageProcessor Plugins. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - #region Using - using System.Collections.Generic; - using System.Drawing; - using System.Text.RegularExpressions; - #endregion - - /// - /// Defines properties and methods for ImageProcessor Plugins. - /// - public interface IGraphicsProcessor - { - #region Properties - /// - /// Gets or sets the DynamicParameter. - /// - dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - Dictionary Settings { get; set; } - #endregion - - #region Methods - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - Image ProcessImage(ImageFactory factory); - #endregion - } -} diff --git a/old/src/ImageProcessor/Processors/Mask.cs b/old/src/ImageProcessor/Processors/Mask.cs deleted file mode 100644 index 82dad35b7..000000000 --- a/old/src/ImageProcessor/Processors/Mask.cs +++ /dev/null @@ -1,161 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Applies a mask to the given image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Colors; - using ImageProcessor.Imaging.Helpers; - - /// - /// Applies a mask to the given image. If the mask is not the same size as the image - /// it will be centered against the image. - /// - public class Mask : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Mask() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Bitmap mask = null; - Bitmap maskCropped = null; - Bitmap maskPositioned = null; - Image image = factory.Image; - - try - { - int width = image.Width; - int height = image.Height; - Tuple parameters = this.DynamicParameter; - mask = new Bitmap(parameters.Item1); - Point? position = parameters.Item2; - - if (mask.Size != image.Size) - { - Rectangle parent = new Rectangle(0, 0, width, height); - Rectangle child = ImageMaths.GetFilteredBoundingRectangle(mask, 0, RgbaComponent.A); - maskCropped = new Bitmap(child.Width, child.Height); - maskCropped.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // First crop any bounding transparency. - using (Graphics graphics = Graphics.FromImage(maskCropped)) - { - graphics.Clear(Color.Transparent); - graphics.DrawImage( - mask, - new Rectangle(0, 0, child.Width, child.Height), - child.X, - child.Y, - child.Width, - child.Height, - GraphicsUnit.Pixel); - } - - // Now position the mask in an image of the same dimensions as the original. - maskPositioned = new Bitmap(width, height); - maskPositioned.SetResolution(image.HorizontalResolution, image.VerticalResolution); - using (Graphics graphics = Graphics.FromImage(maskPositioned)) - { - graphics.Clear(Color.Transparent); - - if (position != null) - { - // Apply the mask at the given position. - graphics.DrawImage(maskCropped, position.Value); - } - else - { - // Center it instead - RectangleF centered = ImageMaths.CenteredRectangle(parent, child); - graphics.DrawImage(maskCropped, new PointF(centered.X, centered.Y)); - } - } - - newImage = Effects.ApplyMask(image, maskPositioned); - maskCropped.Dispose(); - maskPositioned.Dispose(); - } - else - { - newImage = Effects.ApplyMask(image, mask); - mask.Dispose(); - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (mask != null) - { - mask.Dispose(); - } - - if (maskCropped != null) - { - maskCropped.Dispose(); - } - - if (maskPositioned != null) - { - maskPositioned.Dispose(); - } - - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Meta.cs b/old/src/ImageProcessor/Processors/Meta.cs deleted file mode 100644 index 5eb2eabeb..000000000 --- a/old/src/ImageProcessor/Processors/Meta.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to control preservation of meta information. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - - /// - /// Encapsulates methods to control preservation of meta information. - /// - public class Meta : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Meta() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - try - { - factory.PreserveExifData = this.DynamicParameter; - } - catch (Exception ex) - { - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return factory.Image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Overlay.cs b/old/src/ImageProcessor/Processors/Overlay.cs deleted file mode 100644 index 71e7e0e6a..000000000 --- a/old/src/ImageProcessor/Processors/Overlay.cs +++ /dev/null @@ -1,141 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Adds an image overlay to the current image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Helpers; - - /// - /// Adds an image overlay to the current image. - /// If the overlay is larger than the image it will be scaled to match the image. - /// - public class Overlay : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Overlay() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - newImage = new Bitmap(image); - ImageLayer imageLayer = this.DynamicParameter; - Bitmap overlay = new Bitmap(imageLayer.Image); - - // Set the resolution of the overlay and the image to match. - overlay.SetResolution(newImage.HorizontalResolution, newImage.VerticalResolution); - - Size size = imageLayer.Size; - int width = image.Width; - int height = image.Height; - int overlayWidth = size != Size.Empty ? Math.Min(image.Size.Width, size.Width) : Math.Min(image.Size.Width, overlay.Size.Width); - int overlayHeight = size != Size.Empty ? Math.Min(image.Size.Height, size.Height) : Math.Min(image.Size.Height, overlay.Size.Height); - - Point? position = imageLayer.Position; - int opacity = imageLayer.Opacity; - - if (image.Size != overlay.Size || image.Size != new Size(overlayWidth, overlayHeight)) - { - // Find the maximum possible dimensions and resize the image. - ResizeLayer layer = new ResizeLayer(new Size(overlayWidth, overlayHeight), ResizeMode.Max); - overlay = new Resizer(layer).ResizeImage(overlay); - overlayWidth = overlay.Width; - overlayHeight = overlay.Height; - } - - // Figure out bounds. - Rectangle parent = new Rectangle(0, 0, width, height); - Rectangle child = new Rectangle(0, 0, overlayWidth, overlayHeight); - - // Apply opacity. - if (opacity < 100) - { - overlay = Adjustments.Alpha(overlay, opacity); - } - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - if (position != null) - { - // Draw the image in position catering for overflow. - graphics.DrawImage(overlay, new Point(Math.Min(position.Value.X, width - overlayWidth), Math.Min(position.Value.Y, height - overlayHeight))); - } - else - { - RectangleF centered = ImageMaths.CenteredRectangle(parent, child); - graphics.DrawImage(overlay, new PointF(centered.X, centered.Y)); - } - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Pixelate.cs b/old/src/ImageProcessor/Processors/Pixelate.cs deleted file mode 100644 index 7138982eb..000000000 --- a/old/src/ImageProcessor/Processors/Pixelate.cs +++ /dev/null @@ -1,141 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to pixelate an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Threading.Tasks; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging; - - /// - /// Encapsulates methods to pixelate an image. - /// - public class Pixelate : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Pixelate() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - Tuple parameters = this.DynamicParameter; - int size = parameters.Item1; - Rectangle rectangle = parameters.Item2 ?? new Rectangle(0, 0, image.Width, image.Height); - int x = rectangle.X; - int y = rectangle.Y; - int offset = size / 2; - int width = rectangle.Width; - int height = rectangle.Height; - int maxWidth = image.Width; - int maxHeight = image.Height; - - newImage = new Bitmap(image); - - using (FastBitmap fastBitmap = new FastBitmap(newImage)) - { - // Get the range of on the y-plane to choose from. - IEnumerable range = EnumerableExtensions.SteppedRange(y, i => i < y + height && i < maxHeight, size); - - Parallel.ForEach( - range, - j => - { - for (int i = x; i < x + width && i < maxWidth; i += size) - { - int offsetX = offset; - int offsetY = offset; - - // Make sure that the offset is within the boundary of the image. - while (j + offsetY >= maxHeight) - { - offsetY--; - } - - while (i + offsetX >= maxWidth) - { - offsetX--; - } - - // Get the pixel color in the centre of the soon to be pixelated area. - // ReSharper disable AccessToDisposedClosure - Color pixel = fastBitmap.GetPixel(i + offsetX, j + offsetY); - - // For each pixel in the pixelate size, set it to the centre color. - for (int l = j; l < j + size && l < maxHeight; l++) - { - for (int k = i; k < i + size && k < maxWidth; k++) - { - fastBitmap.SetPixel(k, l, pixel); - } - } - // ReSharper restore AccessToDisposedClosure - } - }); - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Quality.cs b/old/src/ImageProcessor/Processors/Quality.cs deleted file mode 100644 index 015c519eb..000000000 --- a/old/src/ImageProcessor/Processors/Quality.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the quality component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - - /// - /// Encapsulates methods to change the quality component of the image. - /// - public class Quality : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Quality() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - try - { - factory.CurrentImageFormat.Quality = this.DynamicParameter; - } - catch (Exception ex) - { - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return factory.Image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/ReplaceColor.cs b/old/src/ImageProcessor/Processors/ReplaceColor.cs deleted file mode 100644 index 4ce357780..000000000 --- a/old/src/ImageProcessor/Processors/ReplaceColor.cs +++ /dev/null @@ -1,168 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods allowing the replacement of a color within an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Threading.Tasks; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Common.Extensions; - using ImageProcessor.Imaging; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods allowing the replacement of a color within an image. - /// - public class ReplaceColor : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public ReplaceColor() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets the dynamic parameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - Tuple parameters = this.DynamicParameter; - Color original = parameters.Item1; - Color replacement = parameters.Item2; - - // Ensure that color comparison takes any gamma adjustments into consideration. - if (factory.FixGamma || Math.Abs(factory.CurrentGamma) > 0) - { - original = PixelOperations.Gamma(original, factory.CurrentGamma); - replacement = PixelOperations.Gamma(replacement, factory.CurrentGamma); - } - - byte originalR = original.R; - byte originalG = original.G; - byte originalB = original.B; - byte originalA = original.A; - - byte replacementR = replacement.R; - byte replacementG = replacement.G; - byte replacementB = replacement.B; - byte replacementA = replacement.A; - - int fuzziness = parameters.Item3; - - byte minR = (originalR - fuzziness).ToByte(); - byte minG = (originalG - fuzziness).ToByte(); - byte minB = (originalB - fuzziness).ToByte(); - - byte maxR = (originalR + fuzziness).ToByte(); - byte maxG = (originalG + fuzziness).ToByte(); - byte maxB = (originalB + fuzziness).ToByte(); - - newImage = new Bitmap(image); - int width = image.Width; - int height = image.Height; - - using (FastBitmap fastBitmap = new FastBitmap(newImage)) - { - Parallel.For( - 0, - height, - y => - { - for (int x = 0; x < width; x++) - { - // Get the pixel color. - // ReSharper disable once AccessToDisposedClosure - Color currentColor = fastBitmap.GetPixel(x, y); - byte currentR = currentColor.R; - byte currentG = currentColor.G; - byte currentB = currentColor.B; - byte currentA = currentColor.A; - - // Test whether it is in the expected range. - if (ImageMaths.InRange(currentR, minR, maxR)) - { - if (ImageMaths.InRange(currentG, minG, maxG)) - { - if (ImageMaths.InRange(currentB, minB, maxB)) - { - // Ensure the values are within an acceptable byte range - // and set the new value. - byte r = (originalR - currentR + replacementR).ToByte(); - byte g = (originalG - currentG + replacementG).ToByte(); - byte b = (originalB - currentB + replacementB).ToByte(); - - // Allow replacement with transparent color. - byte a = currentA; - if (originalA != replacementA) - { - a = replacementA; - } - - // ReSharper disable once AccessToDisposedClosure - fastBitmap.SetPixel(x, y, Color.FromArgb(a, r, g, b)); - } - } - } - } - }); - } - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Resize.cs b/old/src/ImageProcessor/Processors/Resize.cs deleted file mode 100644 index 56974bfbc..000000000 --- a/old/src/ImageProcessor/Processors/Resize.cs +++ /dev/null @@ -1,115 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Resizes an image to the given dimensions. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Globalization; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - - /// - /// Resizes an image to the given dimensions. - /// - public class Resize : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Resize() - { - this.RestrictedSizes = new List(); - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Gets or sets the list of sizes to restrict resizing methods to. - /// - public List RestrictedSizes { get; set; } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - ResizeLayer resizeLayer = this.DynamicParameter; - - // Augment the layer with the extra information. - resizeLayer.RestrictedSizes = this.RestrictedSizes; - Size maxSize = new Size(); - - int maxWidth; - int maxHeight; - int.TryParse(this.Settings["MaxWidth"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxWidth); - int.TryParse(this.Settings["MaxHeight"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxHeight); - - maxSize.Width = maxWidth; - maxSize.Height = maxHeight; - - resizeLayer.MaxSize = maxSize; - - Resizer resizer = new Resizer(resizeLayer); - newImage = resizer.ResizeImage(image); - - // Check that the original image has not been returned. - if (newImage != image) - { - // Reassign the image. - image.Dispose(); - image = newImage; - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/Rotate.cs b/old/src/ImageProcessor/Processors/Rotate.cs deleted file mode 100644 index 9d51bbc8d..000000000 --- a/old/src/ImageProcessor/Processors/Rotate.cs +++ /dev/null @@ -1,142 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to rotate an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - - using ImageProcessor.Common.Exceptions; - - /// - /// Encapsulates methods to rotate an image. - /// - public class Rotate : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Rotate() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - float angle = this.DynamicParameter; - - // Center of the image - float rotateAtX = Math.Abs(image.Width / 2); - float rotateAtY = Math.Abs(image.Height / 2); - - // Create a rotated image. - newImage = this.RotateImage(image, rotateAtX, rotateAtY, angle); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - - #region Private Methods - /// - /// Rotates an image to the given angle at the given position. - /// - /// The image to rotate - /// The horizontal pixel coordinate at which to rotate the image. - /// The vertical pixel coordinate at which to rotate the image. - /// The angle in degrees at which to rotate the image. - /// The image rotated to the given angle at the given position. - /// - /// Based on - /// - private Bitmap RotateImage(Image image, float rotateAtX, float rotateAtY, float angle) - { - Rectangle newSize = Imaging.Helpers.ImageMaths.GetBoundingRotatedRectangle(image.Width, image.Height, angle); - - int x = (newSize.Width - image.Width) / 2; - int y = (newSize.Height - image.Height) / 2; - - // Create a new empty bitmap to hold rotated image - Bitmap newImage = new Bitmap(newSize.Width, newSize.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Make a graphics object from the empty bitmap - using (Graphics graphics = Graphics.FromImage(newImage)) - { - // Reduce the jagged edge. - graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - // Put the rotation point in the "center" of the image - graphics.TranslateTransform(rotateAtX + x, rotateAtY + y); - - // Rotate the image - graphics.RotateTransform(angle); - - // Move the image back - graphics.TranslateTransform(-rotateAtX - x, -rotateAtY - y); - - // Draw passed in image onto graphics object - graphics.DrawImage(image, new PointF(x, y)); - } - - return newImage; - } - #endregion - } -} diff --git a/old/src/ImageProcessor/Processors/RotateBounded.cs b/old/src/ImageProcessor/Processors/RotateBounded.cs deleted file mode 100644 index a1180e910..000000000 --- a/old/src/ImageProcessor/Processors/RotateBounded.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the methods to rotate an image without expanding the canvas. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates the methods to rotate an image without expanding the canvas. - /// - public class RotateBounded : IGraphicsProcessor - { - /// - /// Gets or sets the DynamicParameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// The current instance of the class containing - /// the image to process. - /// - /// The processed image from the current instance of the class. - /// - /// - /// Based on - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - Tuple rotateParams = this.DynamicParameter; - - // Create a rotated image. - newImage = this.RotateImage(image, rotateParams.Item1, rotateParams.Item2); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - - /// - /// Rotates the inside of an image to the given angle at the given position. - /// - /// - /// The image to rotate - /// - /// - /// The angle in degrees. - /// - /// - /// Whether to keep the image dimensions. - /// - /// If set to true, the image is zoomed to fit the bounding area. - /// - /// - /// If set to false, the area is cropped to fit the rotated image. - /// - /// - /// - /// Based on the Rotate effect - /// - /// - /// The image rotated to the given angle at the given position. - /// - private Bitmap RotateImage(Image image, float angleInDegrees, bool keepSize) - { - Size newSize = new Size(image.Width, image.Height); - - float zoom = ImageMaths.ZoomAfterRotation(image.Width, image.Height, angleInDegrees); - - // if we don't keep the image dimensions, calculate the new ones - if (!keepSize) - { - newSize.Width = (int)Math.Floor(newSize.Width / zoom); - newSize.Height = (int)Math.Floor(newSize.Height / zoom); - } - - // Center of the image - float rotateAtX = Math.Abs(image.Width / 2); - float rotateAtY = Math.Abs(image.Height / 2); - - // Create a new empty bitmap to hold rotated image - Bitmap newImage = new Bitmap(newSize.Width, newSize.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Make a graphics object from the empty bitmap - using (Graphics graphics = Graphics.FromImage(newImage)) - { - // Reduce the jagged edge. - graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - if (keepSize) - { - // Put the rotation point in the "center" of the image - graphics.TranslateTransform(rotateAtX, rotateAtY); - - // Rotate the image - graphics.RotateTransform(angleInDegrees); - - // Zooms the image to fit the area - graphics.ScaleTransform(zoom, zoom); - - // Move the image back - graphics.TranslateTransform(-rotateAtX, -rotateAtY); - - // Draw passed in image onto graphics object - graphics.DrawImage(image, new PointF(0, 0)); - } - else - { - float previousX = rotateAtX; - float previousY = rotateAtY; - - // Calculate the difference between the center of the original image - // and the center of the new image. - rotateAtX = Math.Abs(newImage.Width / 2); - rotateAtY = Math.Abs(newImage.Height / 2); - - // Put the rotation point in the "center" of the image - graphics.TranslateTransform(rotateAtX, rotateAtY); - - // Rotate the image - graphics.RotateTransform(angleInDegrees); - - // Draw passed in image onto graphics object - graphics.DrawImage(image, new PointF(-previousX, -previousY)); - } - } - - return newImage; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/RoundedCorners.cs b/old/src/ImageProcessor/Processors/RoundedCorners.cs deleted file mode 100644 index 97c0f6078..000000000 --- a/old/src/ImageProcessor/Processors/RoundedCorners.cs +++ /dev/null @@ -1,177 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to add rounded corners to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - - /// - /// Encapsulates methods to add rounded corners to an image. - /// - public class RoundedCorners : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public RoundedCorners() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - RoundedCornerLayer roundedCornerLayer = this.DynamicParameter; - int radius = roundedCornerLayer.Radius; - bool topLeft = roundedCornerLayer.TopLeft; - bool topRight = roundedCornerLayer.TopRight; - bool bottomLeft = roundedCornerLayer.BottomLeft; - bool bottomRight = roundedCornerLayer.BottomRight; - - // Create a rounded image. - newImage = this.RoundCornerImage(image, radius, topLeft, topRight, bottomLeft, bottomRight); - - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - - /// - /// Adds rounded corners to the image - /// - /// The image to add corners too - /// The radius of the corners. - /// If the top left corner will have a rounded corner? - /// If the top right corner will have a rounded corner? - /// If the bottom left corner will have a rounded corner? - /// If the bottom right corner will have a rounded corner? - /// The image with rounded corners. - private Bitmap RoundCornerImage(Image image, int cornerRadius, bool topLeft = false, bool topRight = false, bool bottomLeft = false, bool bottomRight = false) - { - int width = image.Width; - int height = image.Height; - int cornerDiameter = cornerRadius * 2; - - // Create a new empty bitmap to hold rotated image - Bitmap newImage = new Bitmap(image.Width, image.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - // Make a graphics object from the empty bitmap - using (Graphics graphics = Graphics.FromImage(newImage)) - { - // Reduce the jagged edge. - graphics.SmoothingMode = SmoothingMode.HighQuality; - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - // Add rounded corners - using (GraphicsPath path = new GraphicsPath()) - { - // Determined if the top left has a rounded corner - if (topLeft) - { - path.AddArc(0, 0, cornerDiameter, cornerDiameter, 180, 90); - } - else - { - path.AddLine(0, 0, 0, 0); - } - - // Determined if the top right has a rounded corner - if (topRight) - { - path.AddArc(0 + width - cornerDiameter, 0, cornerDiameter, cornerDiameter, 270, 90); - } - else - { - path.AddLine(width, 0, width, 0); - } - - // Determined if the bottom left has a rounded corner - if (bottomRight) - { - path.AddArc(0 + width - cornerDiameter, 0 + height - cornerDiameter, cornerDiameter, cornerDiameter, 0, 90); - } - else - { - path.AddLine(width, height, width, height); - } - - // Determined if the bottom right has a rounded corner - if (bottomLeft) - { - path.AddArc(0, 0 + height - cornerDiameter, cornerDiameter, cornerDiameter, 90, 90); - } - else - { - path.AddLine(0, height, 0, height); - } - - using (Brush brush = new TextureBrush(image)) - { - graphics.FillPath(brush, path); - } - } - } - - return newImage; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Saturation.cs b/old/src/ImageProcessor/Processors/Saturation.cs deleted file mode 100644 index 10fbbbb1c..000000000 --- a/old/src/ImageProcessor/Processors/Saturation.cs +++ /dev/null @@ -1,144 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to change the saturation component of the image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Imaging; - - using ImageProcessor.Common.Exceptions; - - /// - /// Encapsulates methods to change the saturation component of the image. - /// - /// - /// - /// - public class Saturation : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Saturation() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - float saturationFactor = (float)this.DynamicParameter / 100; - - // Stop at -1 to prevent inversion. - saturationFactor++; - - // The matrix is set up to "shear" the colour space using the following set of values. - // Note that each colour component has an effective luminance which contributes to the - // overall brightness of the pixel. - float saturationComplement = 1.0f - saturationFactor; - float saturationComplementR = 0.3086f * saturationComplement; - float saturationComplementG = 0.6094f * saturationComplement; - float saturationComplementB = 0.0820f * saturationComplement; - - newImage = new Bitmap(image.Width, image.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - ColorMatrix colorMatrix = - new ColorMatrix( - new[] - { - new[] - { - saturationComplementR + saturationFactor, saturationComplementR, - saturationComplementR, 0, 0 - }, - new[] - { - saturationComplementG, saturationComplementG + saturationFactor, - saturationComplementG, 0, 0 - }, - new[] - { - saturationComplementB, saturationComplementB, - saturationComplementB + saturationFactor, 0, 0 - }, - new float[] { 0, 0, 0, 1, 0 }, - new float[] { 0, 0, 0, 0, 1 } - }); - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - using (ImageAttributes imageAttributes = new ImageAttributes()) - { - imageAttributes.SetColorMatrix(colorMatrix); - - graphics.DrawImage( - image, - new Rectangle(0, 0, image.Width, image.Height), - 0, - 0, - image.Width, - image.Height, - GraphicsUnit.Pixel, - imageAttributes); - - image.Dispose(); - image = newImage; - } - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} diff --git a/old/src/ImageProcessor/Processors/Tint.cs b/old/src/ImageProcessor/Processors/Tint.cs deleted file mode 100644 index 9fe68295d..000000000 --- a/old/src/ImageProcessor/Processors/Tint.cs +++ /dev/null @@ -1,104 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Tints an image with the given color. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Drawing2D; - using System.Drawing.Imaging; - - using ImageProcessor.Common.Exceptions; - - /// - /// Tints an image with the given color. - /// - public class Tint : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Tint() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter { get; set; } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings { get; set; } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - Color tintColour = this.DynamicParameter; - float[][] colorMatrixElements = - { - new[] { tintColour.R / 255f, 0, 0, 0, 0 }, // Red - new[] { 0, tintColour.G / 255f, 0, 0, 0 }, // Green - new[] { 0, 0, tintColour.B / 255f, 0, 0 }, // Blue - new[] { 0, 0, 0, tintColour.A / 255f, 0 }, // Alpha - new float[] { 0, 0, 0, 0, 1 } - }; - - ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); - newImage = new Bitmap(image.Width, image.Height); - newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.CompositingQuality = CompositingQuality.HighQuality; - - using (ImageAttributes attributes = new ImageAttributes()) - { - attributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); - graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); - - image.Dispose(); - image = newImage; - } - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/Vignette.cs b/old/src/ImageProcessor/Processors/Vignette.cs deleted file mode 100644 index 65075a3d2..000000000 --- a/old/src/ImageProcessor/Processors/Vignette.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods with which to add a vignette image effect to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Helpers; - - /// - /// Encapsulates methods with which to add a vignette image effect to an image. - /// - public class Vignette : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Vignette() - { - this.DynamicParameter = Color.Black; - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - Color baseColor = (Color)this.DynamicParameter; - newImage = new Bitmap(image); - - newImage = Effects.Vignette(newImage, baseColor); - - // Reassign the image. - image.Dispose(); - image = newImage; - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Processors/Watermark.cs b/old/src/ImageProcessor/Processors/Watermark.cs deleted file mode 100644 index d40a2b619..000000000 --- a/old/src/ImageProcessor/Processors/Watermark.cs +++ /dev/null @@ -1,235 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates methods to add a watermark text overlay to an image. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Processors -{ - using System; - using System.Collections.Generic; - using System.Drawing; - using System.Drawing.Text; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging; - - /// - /// Encapsulates methods to add a watermark text overlay to an image. - /// - public class Watermark : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public Watermark() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - Bitmap newImage = null; - Image image = factory.Image; - - try - { - newImage = new Bitmap(image); - TextLayer textLayer = this.DynamicParameter; - string text = textLayer.Text; - int opacity = Math.Min((int)Math.Ceiling((textLayer.Opacity / 100f) * 255), 255); - int fontSize = textLayer.FontSize; - FontStyle fontStyle = textLayer.Style; - bool fallbackUsed = false; - - using (Graphics graphics = Graphics.FromImage(newImage)) - { - using (Font font = this.GetFont(textLayer.FontFamily, fontSize, fontStyle)) - { - using (StringFormat drawFormat = new StringFormat()) - { - StringFormatFlags? formatFlags = this.GetFlags(textLayer); - if (formatFlags != null) - { - drawFormat.FormatFlags = formatFlags.Value; - } - - using (Brush brush = new SolidBrush(Color.FromArgb(opacity, textLayer.FontColor))) - { - Point? origin = textLayer.Position; - - // Work out the size of the text. - SizeF textSize = graphics.MeasureString(text, font, new SizeF(image.Width, image.Height), drawFormat); - - // We need to ensure that there is a position set for the watermark - if (origin == null) - { - int x = textLayer.RightToLeft - ? 0 - : (int)(image.Width - textSize.Width) / 2; - int y = (int)(image.Height - textSize.Height) / 2; - origin = new Point(x, y); - - fallbackUsed = true; - } - - // Set the hinting and draw the text. - graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; - - // Create bounds for the text. - RectangleF bounds; - - if (textLayer.DropShadow) - { - // Shadow opacity should change with the base opacity. - int shadowOpacity = opacity - (int)Math.Ceiling((30 / 100f) * 255); - int finalShadowOpacity = shadowOpacity > 0 ? shadowOpacity : 0; - - using (Brush shadowBrush = new SolidBrush(Color.FromArgb(finalShadowOpacity, Color.Black))) - { - // Scale the shadow position to match the font size. - // Magic number but it's based on artistic preference. - int shadowDiff = (int)Math.Ceiling(fontSize / 24f); - Point shadowPoint = new Point(origin.Value.X + shadowDiff, origin.Value.Y + shadowDiff); - - // Set the bounds so any overlapping text will wrap. - if (textLayer.RightToLeft && fallbackUsed) - { - bounds = new RectangleF(shadowPoint, new SizeF(image.Width - ((int)(image.Width - textSize.Width) / 2) - shadowPoint.X, image.Height - shadowPoint.Y)); - } - else - { - bounds = new RectangleF(shadowPoint, new SizeF(image.Width - shadowPoint.X, image.Height - shadowPoint.Y)); - } - - graphics.DrawString(text, font, shadowBrush, bounds, drawFormat); - } - } - - // Set the bounds so any overlapping text will wrap. - if (textLayer.RightToLeft && fallbackUsed) - { - bounds = new RectangleF(origin.Value, new SizeF(image.Width - ((int)(image.Width - textSize.Width) / 2), image.Height - origin.Value.Y)); - } - else - { - bounds = new RectangleF(origin.Value, new SizeF(image.Width - origin.Value.X, image.Height - origin.Value.Y)); - } - - graphics.DrawString(text, font, brush, bounds, drawFormat); - } - } - } - - image.Dispose(); - image = newImage; - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - - return image; - } - - /// - /// Returns the correct for the given parameters. - /// - /// - /// The name of the font. - /// - /// - /// The font size. - /// - /// - /// The style. - /// - /// - /// The correct - /// - private Font GetFont(FontFamily fontFamily, int fontSize, FontStyle fontStyle) - { - try - { - using (fontFamily) - { - return new Font(fontFamily, fontSize, fontStyle, GraphicsUnit.Pixel); - } - } - catch - { - using (FontFamily genericFontFamily = FontFamily.GenericSansSerif) - { - return new Font(genericFontFamily, fontSize, fontStyle, GraphicsUnit.Pixel); - } - } - } - - /// - /// Returns the correct flags for the given text layer. - /// - /// - /// The to return the flags for. - /// - /// - /// The . - /// - private StringFormatFlags? GetFlags(TextLayer textLayer) - { - if (textLayer.Vertical && textLayer.RightToLeft) - { - return StringFormatFlags.DirectionVertical | StringFormatFlags.DirectionRightToLeft; - } - - if (textLayer.Vertical) - { - return StringFormatFlags.DirectionVertical; - } - - if (textLayer.RightToLeft) - { - return StringFormatFlags.DirectionRightToLeft; - } - - return null; - } - } -} \ No newline at end of file diff --git a/old/src/ImageProcessor/Properties/AssemblyInfo.cs b/old/src/ImageProcessor/Properties/AssemblyInfo.cs deleted file mode 100644 index c589c6098..000000000 --- a/old/src/ImageProcessor/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// AssemblyInfo.cs -// -// -------------------------------------------------------------------------------------------------------------------- - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor")] -[assembly: AssemblyDescription("A library for on-the-fly processing of image files written in C#")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("James South")] -[assembly: AssemblyProduct("ImageProcessor")] -[assembly: AssemblyCopyright("Copyright © James South")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("bdaae9bd-0dc8-4b06-8722-e2e0c9a74301")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("2.2.4.0")] -[assembly: AssemblyFileVersion("2.2.4.0")] - -[assembly: InternalsVisibleTo("ImageProcessor.UnitTests")] -[assembly: InternalsVisibleTo("ImageProcessor.Web")] diff --git a/old/src/ImageProcessor/Settings.StyleCop b/old/src/ImageProcessor/Settings.StyleCop deleted file mode 100644 index b10054568..000000000 --- a/old/src/ImageProcessor/Settings.StyleCop +++ /dev/null @@ -1,28 +0,0 @@ - - - - Accord - argb - bitstream - bpp - dd - ddd - dllimport - gps - Haar - Kayyali - Laplacian - mmmm - orig - quantizable - rgb - Scharr - Sobel - specifier - ss - subfile - umbraco - ver - - - \ No newline at end of file diff --git a/old/src/ImageProcessor_Mono.sln b/old/src/ImageProcessor_Mono.sln deleted file mode 100644 index 85c025560..000000000 --- a/old/src/ImageProcessor_Mono.sln +++ /dev/null @@ -1,126 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -VisualStudioVersion = 12.0.30110.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{1E656CDE-124D-4FAF-837C-0EF1E192D418}" - ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config - .nuget\NuGet.exe = .nuget\NuGet.exe - .nuget\NuGet.targets = .nuget\NuGet.targets - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor", "ImageProcessor\ImageProcessor.csproj", "{3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Web_NET4", "ImageProcessor.Web\NET4\ImageProcessor.Web_NET4.csproj", "{4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Web_NET45", "ImageProcessor.Web\NET45\ImageProcessor.Web_NET45.csproj", "{D011A778-59C8-4BFA-A770-C350216BF161}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.Playground", "ImageProcessor.Playground\ImageProcessor.Playground.csproj", "{7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageProcessor.UnitTests", "ImageProcessor.UnitTests\ImageProcessor.UnitTests.csproj", "{03CA9055-F997-428C-BF28-F50F991777C6}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - All|Any CPU = All|Any CPU - All|Mixed Platforms = All|Mixed Platforms - All|x86 = All|x86 - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {03CA9055-F997-428C-BF28-F50F991777C6}.All|Any CPU.ActiveCfg = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.All|Any CPU.Build.0 = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.All|Mixed Platforms.ActiveCfg = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.All|Mixed Platforms.Build.0 = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.All|x86.ActiveCfg = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.All|x86.Build.0 = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Debug|x86.ActiveCfg = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Debug|x86.Build.0 = Debug|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Release|Any CPU.Build.0 = Release|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Release|x86.ActiveCfg = Release|Any CPU - {03CA9055-F997-428C-BF28-F50F991777C6}.Release|x86.Build.0 = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Any CPU.ActiveCfg = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Any CPU.Build.0 = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Mixed Platforms.ActiveCfg = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|Mixed Platforms.Build.0 = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.All|x86.ActiveCfg = All|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Debug|x86.ActiveCfg = Debug|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Any CPU.Build.0 = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3B5DD734-FB7A-487D-8CE6-55E7AF9AEA7E}.Release|x86.ActiveCfg = Release|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.All|Any CPU.ActiveCfg = All|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.All|Any CPU.Build.0 = All|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.All|Mixed Platforms.ActiveCfg = All|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.All|Mixed Platforms.Build.0 = All|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.All|x86.ActiveCfg = All|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Debug|x86.ActiveCfg = Debug|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Release|Any CPU.Build.0 = Release|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {4F7050F2-465F-4E10-8DB2-2FB97AC6AA43}.Release|x86.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Any CPU.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Any CPU.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|Mixed Platforms.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.All|x86.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Debug|x86.ActiveCfg = Debug|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Any CPU.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {7BF5274B-56A7-4B62-8105-E9BDF25BAFE7}.Release|x86.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Any CPU.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Any CPU.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Mixed Platforms.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|Mixed Platforms.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.All|x86.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Debug|x86.ActiveCfg = Debug|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Any CPU.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {D011A778-59C8-4BFA-A770-C350216BF161}.Release|x86.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - EndGlobalSection - GlobalSection(MonoDevelopProperties) = preSolution - StartupItem = ImageProcessor\ImageProcessor.csproj - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(TestCaseManagementSettings) = postSolution - CategoryFile = ImageProcessor.vsmdi - EndGlobalSection -EndGlobal diff --git a/old/src/Packages.dgml b/old/src/Packages.dgml deleted file mode 100644 index 946fab579..000000000 --- a/old/src/Packages.dgml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/AzureBlobCache.cs b/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/AzureBlobCache.cs deleted file mode 100644 index 46f5c9b50..000000000 --- a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/AzureBlobCache.cs +++ /dev/null @@ -1,349 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides an implementation that uses Azure blob storage. -// The cache is self healing and cleaning. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Web.Plugins.AzureBlobCache -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.IO; - using System.Linq; - using System.Net; - using System.Text.RegularExpressions; - using System.Threading.Tasks; - using System.Web; - - using ImageProcessor.Web.Caching; - using ImageProcessor.Web.Extensions; - using ImageProcessor.Web.Helpers; - using ImageProcessor.Web.HttpModules; - - using Microsoft.WindowsAzure.Storage; - using Microsoft.WindowsAzure.Storage.Blob; - - /// - /// Provides an implementation that uses Azure blob storage. - /// The cache is self healing and cleaning. - /// - public class AzureBlobCache : ImageCacheBase - { - /// - /// The regular expression for parsing a remote uri. - /// - private static readonly Regex RemoteRegex = new Regex("^http(s)?://", RegexOptions.Compiled); - - /// - /// The assembly version. - /// - private static readonly string AssemblyVersion = typeof(ImageProcessingModule).Assembly.GetName().Version.ToString(); - - /// - /// The cloud cached blob container. - /// - private readonly CloudBlobContainer cloudCachedBlobContainer; - - /// - /// The cloud source blob container. - /// - private readonly CloudBlobContainer cloudSourceBlobContainer; - - /// - /// The cached root url for a content delivery network. - /// - private readonly string cachedCdnRoot; - - /// - /// The cached rewrite path. - /// - private string cachedRewritePath; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The request path for the image. - /// - /// - /// The full path for the image. - /// - /// - /// The querystring containing instructions. - /// - public AzureBlobCache(string requestPath, string fullPath, string querystring) - : base(requestPath, fullPath, querystring) - { - // Retrieve storage accounts from connection string. - CloudStorageAccount cloudCachedStorageAccount = CloudStorageAccount.Parse(this.Settings["CachedStorageAccount"]); - - // Create the blob clients. - CloudBlobClient cloudCachedBlobClient = cloudCachedStorageAccount.CreateCloudBlobClient(); - - // Retrieve references to a previously created containers. - this.cloudCachedBlobContainer = cloudCachedBlobClient.GetContainerReference(this.Settings["CachedBlobContainer"]); - - string sourceAccount = this.Settings.ContainsKey("SourceStorageAccount") ? this.Settings["SourceStorageAccount"] : string.Empty; - - // Repeat for source if it exists - if (!string.IsNullOrWhiteSpace(sourceAccount)) - { - CloudStorageAccount cloudSourceStorageAccount = CloudStorageAccount.Parse(this.Settings["SourceStorageAccount"]); - CloudBlobClient cloudSourceBlobClient = cloudSourceStorageAccount.CreateCloudBlobClient(); - this.cloudSourceBlobContainer = cloudSourceBlobClient.GetContainerReference(this.Settings["SourceBlobContainer"]); - } - - this.cachedCdnRoot = this.Settings.ContainsKey("CachedCDNRoot") ? this.Settings["CachedCDNRoot"] : string.Empty; - } - - /// - /// Gets a value indicating whether the image is new or updated in an asynchronous manner. - /// - /// - /// The asynchronous returning the value. - /// - public override async Task IsNewOrUpdatedAsync() - { - string cachedFileName = await this.CreateCachedFileNameAsync(); - - // Collision rate of about 1 in 10000 for the folder structure. - // That gives us massive scope to store millions of files. - string pathFromKey = string.Join("\\", cachedFileName.ToCharArray().Take(6)); - this.CachedPath = Path.Combine(this.cloudCachedBlobContainer.Uri.ToString(), pathFromKey, cachedFileName).Replace(@"\", "/"); - this.cachedRewritePath = Path.Combine(this.cachedCdnRoot, this.cloudCachedBlobContainer.Name, pathFromKey, cachedFileName).Replace(@"\", "/"); - - bool isUpdated = false; - CachedImage cachedImage = CacheIndexer.Get(this.CachedPath); - - if (new Uri(this.CachedPath).IsFile) - { - FileInfo fileInfo = new FileInfo(this.CachedPath); - - if (fileInfo.Exists) - { - // Pull the latest info. - fileInfo.Refresh(); - - cachedImage = new CachedImage - { - Key = Path.GetFileNameWithoutExtension(this.CachedPath), - Path = this.CachedPath, - CreationTimeUtc = fileInfo.CreationTimeUtc - }; - - CacheIndexer.Add(cachedImage); - } - } - - if (cachedImage == null) - { - string blobPath = this.CachedPath.Substring(this.cloudCachedBlobContainer.Uri.ToString().Length + 1); - CloudBlockBlob blockBlob = this.cloudCachedBlobContainer.GetBlockBlobReference(blobPath); - - if (await blockBlob.ExistsAsync()) - { - // Pull the latest info. - await blockBlob.FetchAttributesAsync(); - - if (blockBlob.Properties.LastModified.HasValue) - { - cachedImage = new CachedImage - { - Key = Path.GetFileNameWithoutExtension(this.CachedPath), - Path = this.CachedPath, - CreationTimeUtc = - blockBlob.Properties.LastModified.Value.UtcDateTime - }; - - CacheIndexer.Add(cachedImage); - } - } - } - - if (cachedImage == null) - { - // Nothing in the cache so we should return true. - isUpdated = true; - } - else - { - // Check to see if the cached image is set to expire. - if (this.IsExpired(cachedImage.CreationTimeUtc)) - { - CacheIndexer.Remove(this.CachedPath); - isUpdated = true; - } - } - - return isUpdated; - } - - /// - /// Adds the image to the cache in an asynchronous manner. - /// - /// - /// The stream containing the image data. - /// - /// - /// The content type of the image. - /// - /// - /// The representing an asynchronous operation. - /// - public override async Task AddImageToCacheAsync(Stream stream, string contentType) - { - string blobPath = this.CachedPath.Substring(this.cloudCachedBlobContainer.Uri.ToString().Length + 1); - CloudBlockBlob blockBlob = this.cloudCachedBlobContainer.GetBlockBlobReference(blobPath); - - await blockBlob.UploadFromStreamAsync(stream); - - blockBlob.Properties.ContentType = contentType; - blockBlob.Properties.CacheControl = string.Format("public, max-age={0}", this.MaxDays * 86400); - await blockBlob.SetPropertiesAsync(); - - blockBlob.Metadata.Add("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion); - await blockBlob.SetMetadataAsync(); - } - - /// - /// Trims the cache of any expired items in an asynchronous manner. - /// - /// - /// The asynchronous representing an asynchronous operation. - /// - public override async Task TrimCacheAsync() - { - Uri uri = new Uri(this.CachedPath); - string path = uri.GetLeftPart(UriPartial.Path).Substring(this.cloudCachedBlobContainer.Uri.ToString().Length + 1); - string directory = path.Substring(0, path.LastIndexOf('/')); - string parent = directory.Substring(0, directory.LastIndexOf('/')); - - BlobContinuationToken continuationToken = null; - List results = new List(); - - // Loop through the all the files in a non blocking fashion. - do - { - BlobResultSegment response = await this.cloudCachedBlobContainer - .ListBlobsSegmentedAsync(parent, true, BlobListingDetails.Metadata, 5000, continuationToken, null, null); - continuationToken = response.ContinuationToken; - results.AddRange(response.Results); - } - while (continuationToken != null); - - // Now leap through and delete. - foreach (CloudBlockBlob blob in results - .Where((blobItem, type) => blobItem is CloudBlockBlob) - .Cast() - .OrderBy(b => b.Properties.LastModified != null ? b.Properties.LastModified.Value.UtcDateTime : new DateTime())) - { - if (blob.Properties.LastModified.HasValue - && !this.IsExpired(blob.Properties.LastModified.Value.UtcDateTime)) - { - break; - } - - // Remove from the cache and delete each CachedImage. - CacheIndexer.Remove(blob.Name); - await blob.DeleteAsync(); - } - } - - /// - /// Gets a string identifying the cached file name. - /// - /// - /// The asynchronous returning the value. - /// - public override async Task CreateCachedFileNameAsync() - { - string streamHash = string.Empty; - - try - { - if (new Uri(this.RequestPath).IsFile) - { - // Get the hash for the filestream. That way we can ensure that if the image is - // updated but has the same name we will know. - FileInfo imageFileInfo = new FileInfo(this.RequestPath); - if (imageFileInfo.Exists) - { - // Pull the latest info. - imageFileInfo.Refresh(); - - // Checking the stream itself is far too processor intensive so we make a best guess. - string creation = imageFileInfo.CreationTimeUtc.ToString(CultureInfo.InvariantCulture); - string length = imageFileInfo.Length.ToString(CultureInfo.InvariantCulture); - streamHash = string.Format("{0}{1}", creation, length); - } - } - else if (this.cloudSourceBlobContainer != null) - { - string container = RemoteRegex.Replace(this.cloudSourceBlobContainer.Uri.ToString(), string.Empty); - string blobPath = RemoteRegex.Replace(this.RequestPath, string.Empty); - blobPath = blobPath.Replace(container, string.Empty).TrimStart('/'); - CloudBlockBlob blockBlob = this.cloudSourceBlobContainer.GetBlockBlobReference(blobPath); - - if (await blockBlob.ExistsAsync()) - { - // Pull the latest info. - await blockBlob.FetchAttributesAsync(); - - if (blockBlob.Properties.LastModified.HasValue) - { - string creation = blockBlob.Properties - .LastModified.Value.UtcDateTime - .ToString(CultureInfo.InvariantCulture); - - string length = blockBlob.Properties.Length.ToString(CultureInfo.InvariantCulture); - streamHash = string.Format("{0}{1}", creation, length); - } - } - } - } - catch - { - streamHash = string.Empty; - } - - // Use an sha1 hash of the full path including the querystring to create the image name. - // That name can also be used as a key for the cached image and we should be able to use - // The characters of that hash as sub-folders. - string parsedExtension = ImageHelpers.GetExtension(this.FullPath, this.Querystring); - string encryptedName = (streamHash + this.FullPath).ToSHA1Fingerprint(); - - string cachedFileName = string.Format( - "{0}.{1}", - encryptedName, - !string.IsNullOrWhiteSpace(parsedExtension) ? parsedExtension.Replace(".", string.Empty) : "jpg"); - - return cachedFileName; - } - - /// - /// Rewrites the path to point to the cached image. - /// - /// - /// The encapsulating all information about the request. - /// - public override void RewritePath(HttpContext context) - { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.cachedRewritePath); - request.Method = "HEAD"; - - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) - { - HttpStatusCode responseCode = response.StatusCode; - context.Response.Redirect( - responseCode == HttpStatusCode.NotFound ? this.CachedPath : this.cachedRewritePath, - false); - } - } - } -} diff --git a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/ImageProcessor.Web.Plugins.AzureBlobCache.csproj b/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/ImageProcessor.Web.Plugins.AzureBlobCache.csproj deleted file mode 100644 index dd1e3b805..000000000 --- a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/ImageProcessor.Web.Plugins.AzureBlobCache.csproj +++ /dev/null @@ -1,98 +0,0 @@ - - - - - Debug - AnyCPU - {3C805E4C-D679-43F8-8C43-8909CDB4D4D7} - Library - Properties - ImageProcessor.Web.Plugins.AzureBlobCache - ImageProcessor.Web.Plugins.AzureBlobCache - v4.5 - 512 - ..\ - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\..\packages\Microsoft.Data.Edm.5.6.2\lib\net40\Microsoft.Data.Edm.dll - - - False - ..\..\..\packages\Microsoft.Data.OData.5.6.2\lib\net40\Microsoft.Data.OData.dll - - - False - ..\..\..\packages\Microsoft.Data.Services.Client.5.6.2\lib\net40\Microsoft.Data.Services.Client.dll - - - ..\..\..\packages\Microsoft.WindowsAzure.ConfigurationManager.1.8.0.0\lib\net35-full\Microsoft.WindowsAzure.Configuration.dll - - - ..\..\..\packages\WindowsAzure.Storage.4.3.0\lib\net40\Microsoft.WindowsAzure.Storage.dll - - - ..\..\..\packages\Newtonsoft.Json.5.0.8\lib\net45\Newtonsoft.Json.dll - - - - - - False - ..\..\..\packages\System.Spatial.5.6.2\lib\net40\System.Spatial.dll - - - - - - - - - - - - - - - {d011a778-59c8-4bfa-a770-c350216bf161} - ImageProcessor.Web - - - - - - - - - - \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/Properties/AssemblyInfo.cs b/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/Properties/AssemblyInfo.cs deleted file mode 100644 index e6b5c0b7f..000000000 --- a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.Web.AzureBlobCache")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ImageProcessor.Web.AzureBlobCache")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("90605e94-25f4-4c69-b602-6b1df0adb89e")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.1.0")] -[assembly: AssemblyVersion("1.0.1.0")] -[assembly: AssemblyFileVersion("1.0.1.0")] diff --git a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/packages.config b/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/packages.config deleted file mode 100644 index 5cdca6448..000000000 --- a/old/src/Plugins/ImageProcessor.Web/ImageProcessor.Web.Plugins.AzureBlobCache/packages.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/CairBootstrapper.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/CairBootstrapper.cs deleted file mode 100644 index 2baf4fa70..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/CairBootstrapper.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Defines the CairBootstrapper type. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair -{ - using System; - using System.IO; - using System.Reflection; - - using ImageProcessor.Configuration; - - /// - /// The cair bootstrapper. - /// - internal static class CairBootstrapper - { - /// - /// Initializes static members of the class. - /// - static CairBootstrapper() - { - RegisterCairExecutable(); - } - - /// - /// Gets the cair path. - /// - public static string CairExecutablePath { get; private set; } - - /// - /// Gets the cair base path. - /// - public static string CairPath { get; private set; } - - /// - /// Registers the embedded CAIR executable. - /// - public static void RegisterCairExecutable() - { - // None of the tools used here are called using dllimport so we don't go through the normal registration channel. - string folder = ImageProcessorBootstrapper.Instance.NativeBinaryFactory.Is64BitEnvironment ? "x64" : "x86"; - Assembly assembly = Assembly.GetExecutingAssembly(); - CairPath = Path.GetFullPath(Path.Combine(new Uri(assembly.Location).LocalPath, "..\\" + folder + "\\imageprocessor.cair\\")); - CairExecutablePath = Path.Combine(CairPath, "CAIR.exe"); - string multithreaderTargetPath = Path.Combine(CairPath, "pthreadVSE2.dll"); - - // Create the folder for storing temporary images. - // ReSharper disable once AssignNullToNotNullAttribute - DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(CairPath)); - if (!directoryInfo.Exists) - { - directoryInfo.Create(); - } - - // Get the resources and copy them across. - const string CairResourcePath = "ImageProcessor.Plugins.Cair.Resources.Unmanaged.x86.CAIR.exe"; - const string MultithreaderResourcePath = "ImageProcessor.Plugins.Cair.Resources.Unmanaged.x86.pthreadVSE2.dll"; - - // Write the two files out to the bin folder. - // Copy out the threading binary. - using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(MultithreaderResourcePath)) - { - if (resourceStream != null) - { - using (FileStream fileStream = File.OpenWrite(multithreaderTargetPath)) - { - resourceStream.CopyTo(fileStream); - } - } - } - - // Copy out the cair executable. - using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(CairResourcePath)) - { - if (resourceStream != null) - { - using (FileStream fileStream = File.OpenWrite(CairExecutablePath)) - { - resourceStream.CopyTo(fileStream); - } - } - } - } - } -} \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/ImageFactoryExtensions.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/ImageFactoryExtensions.cs deleted file mode 100644 index cba46c403..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/ImageFactoryExtensions.cs +++ /dev/null @@ -1,77 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Extends the ImageFactory class to provide a fluent API. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair -{ - using System.Collections.Generic; - using System.Drawing; - - using ImageProcessor.Plugins.Cair.Imaging; - using ImageProcessor.Plugins.Cair.Processors; - - /// - /// Extends the ImageFactory class to provide a fluent API. - /// - public static class ImageFactoryExtensions - { - /// - /// Resizes the current image to the given dimensions using Content Aware Resizing. - /// - /// - /// The current instance of the class - /// that this method extends. - /// - /// - /// The containing the width and height to set the image to. - /// - /// - /// The current instance of the class. - /// - public static ImageFactory ContentAwareResize(this ImageFactory factory, Size size) - { - if (factory.ShouldProcess) - { - int width = size.Width; - int height = size.Height; - - ContentAwareResizeLayer resizeLayer = new ContentAwareResizeLayer(new Size(width, height)); - return factory.ContentAwareResize(resizeLayer); - } - - return factory; - } - - /// - /// Resizes the current image to the given dimensions using Content Aware Resizing. - /// - /// - /// The current instance of the class - /// that this method extends. - /// - /// - /// The containing the properties required to resize the image. - /// - /// - /// The current instance of the class. - /// - public static ImageFactory ContentAwareResize(this ImageFactory factory, ContentAwareResizeLayer layer) - { - if (factory.ShouldProcess) - { - Dictionary resizeSettings = new Dictionary { { "MaxWidth", layer.Size.Width.ToString("G") }, { "MaxHeight", layer.Size.Height.ToString("G") } }; - - ContentAwareResize resize = new ContentAwareResize { DynamicParameter = layer, Settings = resizeSettings }; - factory.CurrentImageFormat.ApplyProcessor(resize.ProcessImage, factory); - } - - return factory; - } - } -} diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/ImageProcessor.Plugins.Cair.csproj b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/ImageProcessor.Plugins.Cair.csproj deleted file mode 100644 index 45c0d70a3..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/ImageProcessor.Plugins.Cair.csproj +++ /dev/null @@ -1,76 +0,0 @@ - - - - - Debug - AnyCPU - {C7D1F0DD-CBD6-4127-82B4-51949EFF0BF5} - Library - Properties - ImageProcessor.Plugins.Cair - ImageProcessor.Plugins.Cair - v4.5 - 512 - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - - - - - - - - - - - - - - - - - - - - - {3b5dd734-fb7a-487d-8ce6-55e7af9aea7e} - ImageProcessor - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/ContentAwareResizeLayer.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/ContentAwareResizeLayer.cs deleted file mode 100644 index 648f31879..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/ContentAwareResizeLayer.cs +++ /dev/null @@ -1,205 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Encapsulates the properties required to resize an image using content aware resizing. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair.Imaging -{ - using System.Drawing; - - /// - /// Encapsulates the properties required to resize an image using content aware resizing. - /// - public class ContentAwareResizeLayer - { - /// - /// The convolution type to apply to the layer. - /// - private ConvolutionType convolutionType = ConvolutionType.Prewitt; - - /// - /// The energy function to apply to the layer. - /// - private EnergyFunction energyFunction = EnergyFunction.Forward; - - /// - /// The expected output type. - /// - private OutputType outputType = OutputType.Cair; - - /// - /// Whether to assign multiple threads to the resizing method. - /// - private bool parallelize = true; - - /// - /// The timeout in milliseconds to attempt to resize for. - /// - private int timeout = 60000; - - /// - /// Initializes a new instance of the class. - /// - /// - /// The containing the width and height to set the image to. - /// - public ContentAwareResizeLayer(Size size) - { - this.Size = size; - } - - /// - /// Gets or sets the content aware resize convolution type (Default ContentAwareResizeConvolutionType.Prewitt). - /// - public ConvolutionType ConvolutionType - { - get - { - return this.convolutionType; - } - - set - { - this.convolutionType = value; - } - } - - /// - /// Gets or sets the energy function (Default EnergyFunction.Forward). - /// - public EnergyFunction EnergyFunction - { - get - { - return this.energyFunction; - } - - set - { - this.energyFunction = value; - } - } - - /// - /// Gets or sets the expected output type. - /// - public OutputType OutputType - { - get - { - return this.outputType; - } - - set - { - this.outputType = value; - } - } - - /// - /// Gets or sets the size. - /// - public Size Size { get; set; } - - /// - /// Gets or sets the the file path to a bitmap file that provides weight indicators specified using - /// color to guide preservation of image portions during carving. - /// - /// The following colors define weight guidance. - /// - Protect the weight. - /// - Remove the weight. - /// - No weight. - /// - /// - public string WeightPath { get; set; } - - /// - /// Gets or sets a value indicating whether to assign multiple threads to the resizing method. - /// (Default true) - /// - public bool Parallelize - { - get - { - return this.parallelize; - } - - set - { - this.parallelize = value; - } - } - - /// - /// Gets or sets the timeout in milliseconds to attempt to resize for (Default 60000). - /// - public int Timeout - { - get - { - return this.timeout; - } - - set - { - this.timeout = value; - } - } - - /// - /// Returns a value that indicates whether the specified object is an - /// object that is equivalent to - /// this object. - /// - /// - /// The object to test. - /// - /// - /// True if the given object is an object that is equivalent to - /// this object; otherwise, false. - /// - public override bool Equals(object obj) - { - ContentAwareResizeLayer resizeLayer = obj as ContentAwareResizeLayer; - - if (resizeLayer == null) - { - return false; - } - - return this.Size == resizeLayer.Size - && this.ConvolutionType == resizeLayer.ConvolutionType - && this.EnergyFunction == resizeLayer.EnergyFunction - && this.OutputType == resizeLayer.OutputType - && this.Parallelize == resizeLayer.Parallelize - && this.Timeout == resizeLayer.Timeout - && this.WeightPath == resizeLayer.WeightPath; - } - - /// - /// Returns the hash code for this instance. - /// - /// - /// A 32-bit signed integer that is the hash code for this instance. - /// - public override int GetHashCode() - { - unchecked - { - int hashCode = (int)this.ConvolutionType; - hashCode = (hashCode * 397) ^ (int)this.EnergyFunction; - hashCode = (hashCode * 397) ^ this.Parallelize.GetHashCode(); - hashCode = (hashCode * 397) ^ (int)this.OutputType; - hashCode = (hashCode * 397) ^ this.Timeout; - hashCode = (hashCode * 397) ^ this.Size.GetHashCode(); - hashCode = (hashCode * 397) ^ (this.WeightPath != null ? this.WeightPath.GetHashCode() : 0); - return hashCode; - } - } - } -} diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/ConvolutionType.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/ConvolutionType.cs deleted file mode 100644 index b9e0aa26a..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/ConvolutionType.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides enumeration of the content aware resize convolution types. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair.Imaging -{ - /// - /// Provides enumeration of the content aware resize convolution types. - /// - public enum ConvolutionType - { - /// - /// The Prewitt kernel convolution type. - /// - Prewitt = 0, - - /// - /// The V1 kernel convolution type. - /// - V1 = 1, - - /// - /// The VSquare kernel convolution type. - /// - VSquare = 2, - - /// - /// The Sobel kernel convolution type. - /// - Sobel = 3, - - /// - /// The Laplacian kernel convolution type. - /// - Laplacian = 4 - } -} \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/EnergyFunction.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/EnergyFunction.cs deleted file mode 100644 index f9e5a2f56..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/EnergyFunction.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Enumerates the energy functions available to the resize method. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair.Imaging -{ - /// - /// Enumerates the energy functions available to the resize method. - /// - public enum EnergyFunction - { - /// - /// The standard energy function. - /// - Backward = 0, - - /// - /// The forward energy function. A look-ahead is performed to reduce jagged edges - /// caused by removing areas of low energy. - /// - Forward = 1 - } -} diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/OutputType.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/OutputType.cs deleted file mode 100644 index 168776c6f..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Imaging/OutputType.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Enumerates the output type to produce. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair.Imaging -{ - /// - /// Enumerates the output type to produce. - /// - public enum OutputType - { - /// - /// Output the result as a carved image. The default action. - /// - Cair = 0, - - /// - /// Output the result as a greyscale image. - /// - Grayscale = 1, - - /// - /// Output the result highlighting the detected edges. - /// - Edge = 2, - - /// - /// Output the result highlighting the vertical energy patterns. - /// - VerticalEnergy = 3, - - /// - /// Output the result highlighting the vertical energy patterns. - /// - HorizontalEnergy = 4, - - /// - /// Appears to do nothing. - /// - Removal = 5, - - /// - /// Output the result as a carved image with the focus on high quality output over speed. - /// - CairHighDefinition = 6 - } -} diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Processors/ContentAwareResize.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Processors/ContentAwareResize.cs deleted file mode 100644 index 7900415fb..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Processors/ContentAwareResize.cs +++ /dev/null @@ -1,215 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Resizes an image to the given dimensions using content aware resizing. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.Cair.Processors -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Drawing; - using System.Drawing.Imaging; - using System.Globalization; - using System.IO; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Plugins.Cair.Imaging; - using ImageProcessor.Processors; - - /// - /// Resizes an image to the given dimensions using content aware resizing. - /// - public class ContentAwareResize : IGraphicsProcessor - { - /// - /// Initializes a new instance of the class. - /// - public ContentAwareResize() - { - this.Settings = new Dictionary(); - } - - /// - /// Gets or sets DynamicParameter. - /// - public dynamic DynamicParameter - { - get; - set; - } - - /// - /// Gets or sets any additional settings required by the processor. - /// - public Dictionary Settings - { - get; - set; - } - - /// - /// Processes the image. - /// - /// - /// The current instance of the class containing - /// the image to process. - /// - /// - /// The processed image from the current instance of the class. - /// - public Image ProcessImage(ImageFactory factory) - { - string fileName = Guid.NewGuid().ToString(); - - // Use bmp's as the temporary files since they are lossless and support transparency. - string sourcePath = Path.Combine(CairBootstrapper.CairPath, fileName + ".bmp"); - string resizedPath = Path.Combine(CairBootstrapper.CairPath, fileName + "-r.bmp"); - - // Gather the parameters. - ContentAwareResizeLayer layer = (ContentAwareResizeLayer)this.DynamicParameter; - int width = layer.Size.Width; - int height = layer.Size.Height; - int timeout = layer.Timeout > 0 ? layer.Timeout : 60000; - - int defaultMaxWidth; - int defaultMaxHeight; - - int.TryParse(this.Settings["MaxWidth"], NumberStyles.Any, CultureInfo.InvariantCulture, out defaultMaxWidth); - int.TryParse(this.Settings["MaxHeight"], NumberStyles.Any, CultureInfo.InvariantCulture, out defaultMaxHeight); - - Bitmap newImage = null; - Image image = factory.Image; - - try - { - int sourceWidth = image.Width; - int sourceHeight = image.Height; - - // Fractional variants for preserving aspect ratio. - double percentHeight = Math.Abs(height / (double)sourceHeight); - double percentWidth = Math.Abs(width / (double)sourceWidth); - - int maxWidth = defaultMaxWidth > 0 ? defaultMaxWidth : int.MaxValue; - int maxHeight = defaultMaxHeight > 0 ? defaultMaxHeight : int.MaxValue; - - // If height or width is not passed we assume that the standard ratio is to be kept. - if (height == 0) - { - height = (int)Math.Ceiling(sourceHeight * percentWidth); - } - - if (width == 0) - { - width = (int)Math.Ceiling(sourceWidth * percentHeight); - } - - if (width > 0 && height > 0 && width <= maxWidth && height <= maxHeight) - { - // Save the temporary bitmap. - image.Save(sourcePath, ImageFormat.Bmp); - - // Process the image using the CAIR executable. - string arguments = string.Format( - " -I \"{0}\" -O \"{1}\" -C {2} -X {3} -Y {4} -E {5} -T {6} -R {7}", - sourcePath, - resizedPath, - (int)layer.ConvolutionType, - width, - height, - (int)layer.EnergyFunction, - layer.Parallelize ? Math.Min(4, Environment.ProcessorCount) : 1, - (int)layer.OutputType); - - if (!string.IsNullOrWhiteSpace(layer.WeightPath)) - { - arguments = string.Format("{0} -W {1}", arguments, layer.WeightPath); - } - - this.ProcessCairImage(arguments, timeout); - - // Assign the new image. - newImage = new Bitmap(resizedPath); - newImage.MakeTransparent(); - - // Reassign the image. - image.Dispose(); - image = newImage; - } - } - catch (Exception ex) - { - if (newImage != null) - { - newImage.Dispose(); - } - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex); - } - finally - { - FileInfo sourceFileInfo = new FileInfo(sourcePath); - if (sourceFileInfo.Exists) - { - sourceFileInfo.Delete(); - } - - FileInfo resizedFileInfo = new FileInfo(resizedPath); - if (resizedFileInfo.Exists) - { - resizedFileInfo.Delete(); - } - } - - return image; - } - - /// - /// The process cair image. - /// - /// - /// The arguments. - /// - /// - /// The time in milliseconds to attempt to resize the image for. - /// - private void ProcessCairImage(string arguments, int timeout) - { - // Set up and start a new process to resize the image. - ProcessStartInfo start = new ProcessStartInfo(CairBootstrapper.CairExecutablePath, arguments) - { - WindowStyle = ProcessWindowStyle.Hidden, - UseShellExecute = false, - RedirectStandardInput = true, - RedirectStandardError = true, - RedirectStandardOutput = true, - CreateNoWindow = true, - }; - - using (Process process = Process.Start(start)) - { - if (process != null) - { - if (!process.WaitForExit(timeout)) - { - process.Kill(); - - throw new ImageProcessingException("Error processing image with " + this.GetType().Name + " due to timeout."); - } - - string output = string.Format(" {0} {1}", process.StandardError.ReadToEnd(), process.StandardOutput.ReadToEnd()); - - if (process.ExitCode != 0) - { - throw new ImageProcessingException("Error processing image with " + this.GetType().Name + output); - } - } - } - } - } -} diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Properties/AssemblyInfo.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Properties/AssemblyInfo.cs deleted file mode 100644 index 6c0f4b959..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.Plugins.Cair")] -[assembly: AssemblyDescription("Adds Content Aware Image Resizing to ImageProcessor")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ImageProcessor.Plugins.Cair")] -[assembly: AssemblyCopyright("Copyright James South © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("e0e88a19-d3ea-4f9c-ab3d-8c871359dc59")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.1.0")] -[assembly: AssemblyVersion("1.0.1.0")] -[assembly: AssemblyFileVersion("1.0.1.0")] diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/CAIR.exe.REMOVED.git-id b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/CAIR.exe.REMOVED.git-id deleted file mode 100644 index 9d07329a4..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/CAIR.exe.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -83a4594cf9aeb54e509a1cd04528e414eb673161 \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/GPL.txt b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/GPL.txt deleted file mode 100644 index 594162448..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/GPL.txt +++ /dev/null @@ -1,473 +0,0 @@ -CAIR - Content Aware Image Resizer -Copyright (C) 2008 Joseph Auman (brain.recall@gmail.com) -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/ReadMe.txt b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/ReadMe.txt deleted file mode 100644 index 2da7fd858..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/ReadMe.txt +++ /dev/null @@ -1,282 +0,0 @@ -User's ReadMe v2.18 - -CAIR - Content Aware Image Resizer -Copyright (C) 2008 Joseph Auman (brain.recall@gmail.com) - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ - -CAIR is an image resizing library that is based on the works of Shai Avidan and -Ariel Shamir. It is a high-performance multi-threaded library written in C++. -It is intended to be multi-platform and multi-architecture. - - -I am looking into implementing Poisson image reconstruction, which is mentioned -in the paper, to be used in CAIR_HD(). See the paper on the subject here: -http://research.microsoft.com/vision/cambridge/papers/perez_siggraph03.pdf -However, I’m having a bit of difficulty understanding the method and how I can -apply it to seam removal. If you know something about digital image processing -and are willing to help, please email me at brain.recall@gmail.com - - -Compiling CAIR is not difficult. A Makefile for Linux is included to demonstrate. -Compiling under Visual Studio is a bit different, since the pthread DLL library -and object library must be included for the linker. I suggest Google to see how -it's done. Whenever possible, I *highly* suggest using the Intel C++ compiler, -which gives about a 10% speed boost when all the optimization options are -turned on. It's freely available for the Linux platform, but Windows and Mac -license are in the $600 range outside of the 30 day trial. - -+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ - -In this file I'm going to present each file and its functions. This is going to -targeted at "users" of the library (those actually making a GUI with it). Further -detail can be gained by reading the source code (don't worry, I take *some* pride -in my comments, but pthread experience would be helpful). - - -CAIR_CML.h -================================================================================= -The CAIR Matrix Library. A template class used to hold the image information -in CAIR. The CML requires a size when creating the object. See main.cpp for -some examples in declaring and interfacing with the CML_Matrix. - -- Depends on: nothing outside of the STL - -- Types defined: --- CML_byte - An unsigned char used for each color channel. --- CML_RGBA - Structure for a 32 bit color pixel. - - Each channel is a CML_byte, named as: red, green, blue, alpha --- CML_color - A color matrix, replaces CML_Matrix; use for images. --- CML_int - An integer matrix, replaces CML_Matrix; use for weights. - -- Methods (the important ones, at least): --- CML_Matrix( int x, int y ) ---- Simple constructor. Requires the intended size of the matrix (can be changed - later, so dummy values of (1,1) could be used). --- void Fill( T value ) ---- Sets all elements of the matrix to the given value. --- operator()( int x, int y ) ---- Accessor and assignment methods, used to set and get matrix values. ---- These have no bounds checking. --- int Width() ---- Returns the width of the matrix. --- int Height() ---- Returns the height of the matrix. --- void Transpose( CML_Matrix * Source ) ---- Rotates Source on edge, storing the result into the matrix. --- T Get( int x, int y ) ---- Accessor function with full bounds checking. Out-of-bound accesses will be - constrained back into the matrix. --- void D_Resize( int x, int y ) ---- Destructively resize the matrix to the given values. --- void Resize_Width( int x ) ---- Careful with this one. Performs non-destructive "resizing" but only in the x - direction. Essentially only changes what Width() will report. Enlarging should - be done only after a Reserve(), for performance reasons. --- void Shift_Row( int x, int y, int shift ) ---- Shift the elements of a row, starting the (x,y) element. Shift determines - amount of shift and direction. Negative will shift left, positive for right. - - - -CAIR.h -================================================================================= -The CAIR function declarations. - -Depends on: CAIR_CML.h -Types defined: --- CAIR_NUM_THREADS - The number of default threads that will be used for Grayscale, Edge, and Add/Remove operations. --- CAIR_direction - An enumeration for CAIR_Removal() with the values of AUTO, - VERTICAL, and HORIZONTAL. AUTO lets CAIR_Remvoal() determine - the best direction to remove seams. VERTICAL and HORIZONTAL - force the function to remove from their respective directions. --- CAIR_convolution - An enumeration for all CAIR operations. It defines the available - convolution kernels. They include: - Prewitt: An X-Y kernel for decent edge detection. - Sobel: Works very much like Prewitt. - V1: Only the X-component of the Prewitt. More of an object detector - than strictly edges. Works well under some cases. - V_SQUARE: The result of V1 squared. This provides some of the - best object detection, thus some of the best operation. - Laplacian: A second-order edge detector. Nothing spectacular. --- CAIR_energy - An enumeration for all CAIR energy algorithms. - Backward: The traditional energy algorithm. - Forward: The new energy algorithm that determines future edge changes and tries - to redirect seams away from potential artifacts. Comes at a slight performance hit. - -Functions: -- void CAIR_Threads( int thread_count ) --- thread_count: the number of threads that the Grayscale/Edge/Add/Remove operations should use. Minimum of two. - -- bool CAIR( CML_color * Source, - CML_int * S_Weights, - int goal_x, - int goal_y, - CAIR_convolution conv, - CAIR_energy ener, - CML_int * D_Weights, - CML_color * Dest, - bool (*CAIR_callback)(float) ) --- Source: pointer to the source image --- S_Weights: pointer to the weights of the image, must be the same size as Source - The weights allow for linear protection and removal of desired portions of an - image. The values of the weights should not exceed -2,000,000 to 2,000,000 to - avoid integer overflows. Generally, I found a -10,000 to 10,000 range to be - adequate. Large values will protect pixel, while small values will make it - more likely to be removed first. ALWAYS use negative values for removal. When - no preference is given to a pixel, leave its value to zero. (I suggest Fill()'ing - the weight matrix with 0 before use, since the memory is not initialized when - allocated.) --- goal_x: the desired width of the Dest image --- goal_y: the desired height of the Dest image --- conv: The possible convolution kernels to use. See the above discussion. - It is important to note that if using V_SQUARE the weights must be at least an order - of magnitude larger for similar operation. add_weight needs to be several orders of - magnitude larger to avoid some stretching. This is because V_SQUARE produces larger - edge values, and thus large energy values. --- ener: The possible energy algorithms to use. See the above discussion. --- D_Weights: pointer to the Destination Weights (contents will be destroyed) --- Dest: pointer to the Destination image (contents will be destroyed) --- CAIR_callback: a function pointer to a status/callback system. The function is expected - to take a float of the percent complete (from 0 to 1) and is to return a false if the - resize is to be canceled, or true otherwise. If the resize is canceled, CAIR() will return - a false, leaving Dest and D_Weights in an unknown state. Set to NULL if not used. --- RETURNS: true if the resize ran to completion, false if it was canceled by CAIR_callback. - -- void CAIR_Grayscale( CML_color * Source, CML_color * Dest ) --- Source: pointer to the source image --- Dest: The grayscale of Source image. The gray value will be computed, then applied - to the three color channels to give the grayscale equivalent. -- void CAIR_Edge( CML_color * Source, CAIR_convolution conv, CML_color * Dest ) --- Source: pointer to the source image --- conv: The edge detection kernel. --- Dest: The dge detection of the source image. Values larger than a CML_byte - (255 in decimal) will be clipped down to 255. - -- CAIR_V_Energy( CML_color * Source, CAIR_convolution conv, CAIR_energy ener, CML_color * Dest ) and CAIR_H_Energy( CML_color * Source, CAIR_convolution conv, CAIR_energy ener, CML_color * Dest ) --- Source: pointer to the source image --- conv: The edge detection kernel. --- ener: The energy algorithm. --- Dest: The grayscale equivalent of the energy map of the source image. All values - are scaled down realtive to the largest value. Weights are assumed all zero, - since when they are not they dominate the image and produce uninteresting results. - -- bool CAIR_Removal( CML_color * Source, - CML_int * S_Weights, - CAIR_direction choice, - int max_attempts, - CAIR_convolution conv, - CAIR_energy ener, - CML_int * D_Weights, - CML_color * Dest, - bool (*CAIR_callback)(float) ) --- EXPERIMENTAL --- S_Weights: pointer to the given weights of the image --- choice: How the algorithm will remove the seams. In AUTO mode, it will count the - negative rows (for horizontal removal) and the negative columns (for vertical removal) - and then removes the least amount in that direction. Other settings will cause it to - remove in thier respective directions. After the removal, it is expanded back out to - its origional dimensions. --- max_attempts: The number of retries the algorithm will do to remove remaining negative - weights. Sometimes the algorithm may not remove everything in one pass, and this attempts - to give the algorithm another chance at it. There are situations, however, where the - algorithm will not be able to remove the requested portions due to other areas makred - for protection with a high weight. --- conv: The edge detection kernel. --- ener: The energy algorithm. --- D_Weights: pointer to the destination weights --- Dest: pointer to the destination image --- CAIR_callback: a function pointer to a status/callback system --- RETURNS: true if the resize ran to completion, false if it was canceled by CAIR_callback. - -- bool CAIR_HD( CML_color * Source, - CML_int * S_Weights, - int goal_x, - int goal_y, - CAIR_convolution conv, - CAIR_energy ener, - CML_int * D_Weights, - CML_color * Dest, - bool (*CAIR_callback)(float) ) --- See CAIR() for the same paramaters. --- CAIR_HD() is designed for quality, not speed. At each itteration, CAIR_HD() - determines which direction produces the least energy path for removal. It then - removes that path. CAIR_HD() can enlarge, but currently employs standard CAIR() - to perform it. - -CAIR.cpp -================================================================================= -The CAIR function definitions. Nothing really important to the user, except its -dependencies. - -Depends on: CAIR_CML.h, CAIR.h, pthread.h -Types defined: none visible -Functions: none visible - - - -main.cpp -================================================================================= -An example application that uses CAIR (mostly for testing by me). Functions to -read the source on are BMP_to_CML() and CML_to_BMP() to get an example on how to -convert to and from the CML. - -- Depends on: CAIR_CML.h, CAIR.h, EasyBMP.h -Types defined: none -Functions: nothing really important - - -+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -Content Amplification - -This is described in the paper, but I'll mention it here as well. This method -allows an object in the image to appear larger. Do this as following: -1) Enlarge an image using a standard linear technique by about 10% or so (more - than 25% might cause some artifacts). -2) Optional: Set a large weight for the desired object. -3) Seam carve the enlarged image back down to the origional size. - -+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ - - -Other Links: -http://brain.recall.googlepages.com/cair -http://c-a-i-r.wiki.sourceforge.net/ -http://sourceforge.net/projects/c-a-i-r/ -http://code.google.com/p/seam-carving-gui/ -http://www.faculty.idc.ac.il/arik/papers/imret.pdf -http://www.faculty.idc.ac.il/arik/papers/vidRet.pdf - -Special Thanks: -Ariel Shamir -Shai Avidan -Michael Rubinstein -Ramin Sabet -Brett Taylor -Gabe Rudy -Jean-Baptiste (Jib) -David Phillip Oster -Matt Newell -Klaus Nordby -Alexandre Prokoudine -Peter Berrington - -Further questions on CAIR can be directed to the source code, or my email. - -Sincerely, -Brain_ReCall aka Joe Auman -brain.recall@gmail.com diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/Usage.txt b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/Usage.txt deleted file mode 100644 index a6b19bcef..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/Usage.txt +++ /dev/null @@ -1,41 +0,0 @@ -CAIR CLI Usage: - -cair -I - -Other options: - -O - Default: Dependent on operation - -W - Bitmap with: Black- no weight - Green- Protect weight - Red- Remove weight - Default: Weights are all zero - -S - Default: 100,000 - -X - Default: Source image width - -Y - Default: Source image height - -R - CAIR: 0 - Grayscale: 1 - Edge: 2 - Vertical Energy: 3 - Horizontal Energy: 4 - Removal: 5 - CAIR_HD: 6 - Default: CAIR - -C - Prewitt: 0 - V1: 1 - V_SQUARE: 2 - Sobel: 3 - Laplacian: 4 - Default: Prewitt - - -E - Backward: 0 - Forward: 1 - Default: Backward - -T - Default : CAIR_NUM_THREADS (4) diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/pthreadVSE2.dll.REMOVED.git-id b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/pthreadVSE2.dll.REMOVED.git-id deleted file mode 100644 index c52d6fc50..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Resources/Unmanaged/x86/pthreadVSE2.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -af74faa46395cff6167217e471d0e9d8108bc829 \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Settings.StyleCop b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Settings.StyleCop deleted file mode 100644 index 50b7964dd..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.Cair/Settings.StyleCop +++ /dev/null @@ -1,9 +0,0 @@ - - - - cair - laplacian - sobel - - - \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/ImageProcessor.Plugins.WebP.csproj b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/ImageProcessor.Plugins.WebP.csproj deleted file mode 100644 index c1721713e..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/ImageProcessor.Plugins.WebP.csproj +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Debug - AnyCPU - {2CF69699-959A-44DC-A281-4E2596C25043} - Library - Properties - ImageProcessor.Plugins.WebP - ImageProcessor.Plugins.WebP - v4.5 - 512 - - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - - - - - - - - - - - - - - - - - - - - - {3b5dd734-fb7a-487d-8ce6-55e7af9aea7e} - ImageProcessor - - - - - \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Imaging/Formats/NativeMethods.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Imaging/Formats/NativeMethods.cs deleted file mode 100644 index a3add3488..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Imaging/Formats/NativeMethods.cs +++ /dev/null @@ -1,131 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides access to unmanaged native methods. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.WebP.Imaging.Formats -{ - using System; - using System.IO; - using System.Reflection; - using System.Runtime.InteropServices; - - using ImageProcessor.Configuration; - - /// - /// Provides access to unmanaged native methods. - /// - internal static class NativeMethods - { - /// - /// Initializes static members of the class. - /// - static NativeMethods() - { - string folder = ImageProcessorBootstrapper.Instance.NativeBinaryFactory.Is64BitEnvironment ? "x64" : "x86"; - string name = string.Format("ImageProcessor.Plugins.WebP.Resources.Unmanaged.{0}.libwebp.dll", folder); - using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) - { - using (MemoryStream memoryStream = new MemoryStream()) - { - if (stream != null) - { - stream.CopyTo(memoryStream); - ImageProcessorBootstrapper.Instance.NativeBinaryFactory.RegisterNativeBinary("libwebp.dll", memoryStream.ToArray()); - } - } - } - } - - #region WebP - /// - /// Validate the WebP image header and retrieve the image height and width. Pointers *width and *height can be passed NULL if deemed irrelevant - /// - /// - /// Pointer to WebP image data - /// - /// - /// This is the size of the memory block pointed to by data containing the image data - /// - /// - /// The width range is limited currently from 1 to 16383 - /// - /// - /// The height range is limited currently from 1 to 16383 - /// - /// - /// 1 if success, otherwise error code returned in the case of (a) formatting error(s). - /// - [DllImport("libwebp", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPGetInfo")] - public static extern int WebPGetInfo(IntPtr data, uint dataSize, out int width, out int height); - - /// - /// Decode WEBP image pointed to by *data and returns BGR samples into a pre-allocated buffer - /// - /// - /// Pointer to WebP image data - /// - /// - /// This is the size of the memory block pointed to by data containing the image data - /// - /// - /// Pointer to decoded WebP image - /// - /// - /// Size of allocated buffer - /// - /// - /// Specifies the distance between scan-lines - /// - /// - /// output_buffer if function succeeds; NULL otherwise - /// - [DllImport("libwebp", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPDecodeBGRAInto")] - public static extern IntPtr WebPDecodeBGRAInto(IntPtr data, uint dataSize, IntPtr outputBuffer, int outputBufferSize, int outputStride); - - /// - /// Lossy encoding images pointed to by *data in WebP format - /// - /// - /// Pointer to RGB image data - /// - /// - /// The width range is limited currently from 1 to 16383 - /// - /// - /// The height range is limited currently from 1 to 16383 - /// - /// - /// The stride. - /// - /// - /// Ranges from 0 (lower quality) to 100 (highest quality). Controls the loss and quality during compression - /// - /// - /// output_buffer with WebP image - /// - /// - /// Size of WebP Image - /// - [DllImport("libwebp", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPEncodeBGRA")] - public static extern int WebPEncodeBGRA(IntPtr rgb, int width, int height, int stride, float qualityFactor, out IntPtr output); - - /// - /// Frees the unmanaged memory. - /// - /// - /// The pointer. - /// - /// - /// 1 if success, otherwise error code returned in the case of (a) error(s). - /// - [DllImport("libwebp", CallingConvention = CallingConvention.Cdecl, EntryPoint = "WebPFree")] - public static extern int WebPFree(IntPtr pointer); - #endregion - } -} diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Imaging/Formats/WebPFormat.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Imaging/Formats/WebPFormat.cs deleted file mode 100644 index 0bc2e2b7b..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Imaging/Formats/WebPFormat.cs +++ /dev/null @@ -1,275 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// Provides the necessary information to support webp images. -// Adapted from -// by Jose M. Piñeiro -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ImageProcessor.Plugins.WebP.Imaging.Formats -{ - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.Drawing; - using System.Drawing.Imaging; - using System.IO; - using System.Runtime.InteropServices; - using System.Text; - - using ImageProcessor.Common.Exceptions; - using ImageProcessor.Imaging.Formats; - - /// - /// Provides the necessary information to support webp images. - /// Adapted from - /// by Jose M. Piñeiro - /// - [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed. Suppression is OK here.")] - public class WebPFormat : FormatBase - { - /// - /// Gets the file headers. - /// - public override byte[][] FileHeaders - { - get - { - return new[] { Encoding.ASCII.GetBytes("RIFF") }; - } - } - - /// - /// Gets the list of file extensions. - /// - public override string[] FileExtensions - { - get - { - return new[] { "webp" }; - } - } - - /// - /// Gets the standard identifier used on the Internet to indicate the type of data that a file contains. - /// - public override string MimeType - { - get - { - return "image/webp"; - } - } - - /// - /// Gets the file format of the image. - /// - public override ImageFormat ImageFormat - { - get - { - return null; - } - } - - /// - /// Applies the given processor the current image. - /// - /// The processor delegate. - /// The . - public override void ApplyProcessor(Func processor, ImageFactory factory) - { - base.ApplyProcessor(processor, factory); - - // Set the property item information from any Exif metadata. - // We do this here so that they can be changed between processor methods. - if (factory.PreserveExifData) - { - foreach (KeyValuePair propertItem in factory.ExifPropertyItems) - { - factory.Image.SetPropertyItem(propertItem.Value); - } - } - } - - /// - /// Decodes the image to process. - /// - /// - /// The containing the image information. - /// - /// - /// The . - /// - public override Image Load(Stream stream) - { - byte[] bytes = new byte[stream.Length]; - stream.Read(bytes, 0, bytes.Length); - return Decode(bytes); - } - - /// - /// Saves the current image to the specified file path. - /// - /// The path to save the image to. - /// The - /// to save. - /// - /// The . - /// - public override Image Save(string path, Image image) - { - byte[] bytes; - - // Encode in webP format. - if (EncodeLossly((Bitmap)image, this.Quality, out bytes)) - { - File.WriteAllBytes(path, bytes); - } - - return image; - } - - /// - /// Saves the current image to the specified output stream. - /// - /// The to save the image information to. - /// The to save. - /// - /// The . - /// - public override Image Save(Stream stream, Image image) - { - byte[] bytes; - - // Encode in webP format. - if (EncodeLossly((Bitmap)image, this.Quality, out bytes)) - { - using (MemoryStream memoryStream = new MemoryStream(bytes)) - { - memoryStream.CopyTo(stream); - memoryStream.Position = stream.Position = 0; - } - } - else - { - throw new ImageFormatException("Unable to encode WebP image."); - } - - return image; - } - - /// - /// Decodes a WebP image - /// - /// - /// The data to uncompress - /// - /// - /// The . - /// - private static Bitmap Decode(byte[] webpData) - { - // Get the image width and height - GCHandle pinnedWebP = GCHandle.Alloc(webpData, GCHandleType.Pinned); - IntPtr ptrData = pinnedWebP.AddrOfPinnedObject(); - uint dataSize = (uint)webpData.Length; - - Bitmap bitmap = null; - BitmapData bitmapData = null; - IntPtr outputBuffer = IntPtr.Zero; - int width; - int height; - - if (NativeMethods.WebPGetInfo(ptrData, dataSize, out width, out height) != 1) - { - throw new ImageFormatException("WebP image header is corrupted."); - } - - try - { - // Create a BitmapData and Lock all pixels to be written - bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); - bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); - - // Allocate memory for uncompress image - int outputBufferSize = bitmapData.Stride * height; - outputBuffer = Marshal.AllocHGlobal(outputBufferSize); - - // Uncompress the image - outputBuffer = NativeMethods.WebPDecodeBGRAInto(ptrData, dataSize, outputBuffer, outputBufferSize, bitmapData.Stride); - - // Write image to bitmap using Marshal - byte[] buffer = new byte[outputBufferSize]; - Marshal.Copy(outputBuffer, buffer, 0, outputBufferSize); - Marshal.Copy(buffer, 0, bitmapData.Scan0, outputBufferSize); - } - finally - { - // Unlock the pixels - if (bitmap != null) - { - bitmap.UnlockBits(bitmapData); - } - - // Free memory - pinnedWebP.Free(); - Marshal.FreeHGlobal(outputBuffer); - } - - return bitmap; - } - - /// - /// Lossy encodes the image in bitmap. - /// - /// - /// Bitmap with the image - /// - /// - /// Quality. 0 = minimum ... 100 = maximum quality - /// - /// - /// The byte array containing the encoded image data. - /// - /// - /// True if success; False otherwise - /// - private static bool EncodeLossly(Bitmap bitmap, int quality, out byte[] webpData) - { - webpData = null; - BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - IntPtr unmanagedData = IntPtr.Zero; - bool encoded; - - try - { - // Attempt to lossy encode the image. - int size = NativeMethods.WebPEncodeBGRA(bmpData.Scan0, bitmap.Width, bitmap.Height, bmpData.Stride, quality, out unmanagedData); - - // Copy image compress data to output array - webpData = new byte[size]; - Marshal.Copy(unmanagedData, webpData, 0, size); - encoded = true; - } - catch - { - encoded = false; - } - finally - { - // Unlock the pixels - bitmap.UnlockBits(bmpData); - - // Free memory - NativeMethods.WebPFree(unmanagedData); - } - - return encoded; - } - } -} \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Properties/AssemblyInfo.cs b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Properties/AssemblyInfo.cs deleted file mode 100644 index 43d37b175..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ImageProcessor.Plugins.WebP")] -[assembly: AssemblyDescription("Adds support to ImageProcessor for the WebP image format.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("James South")] -[assembly: AssemblyProduct("ImageProcessor.Plugins.WebP")] -[assembly: AssemblyCopyright("Copyright © James South")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("bf160db5-2ea7-4c85-9b0e-f1ddf2595e37")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.2.0")] -[assembly: AssemblyVersion("1.0.2.0")] -[assembly: AssemblyFileVersion("1.0.2.0")] diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/README.md b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/README.md deleted file mode 100644 index 864e04f8b..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/README.md +++ /dev/null @@ -1,23 +0,0 @@ -#Build instructions for libwebp.dll - -Download libwebp source via git or through http download. - -In Start Menu, run Visual Studio Tools > Command Prompt. - -Change to the libwebp directory and run - - nmake /f Makefile.vc CFG=release-dynamic RTLIBCFG=dynamic OBJDIR=output - -Repeat with the -Visual Studio x64 Cross Tools Command Prompt - - -Copy to x86 and x64 directories from /output/ - -To verify p/invokes have not changed: - -Review the following history logs for changes since the last release: - -http://git.chromium.org/gitweb/?p=webm/libwebp.git;a=history;f=src/webp/types.h;hb=HEAD -http://git.chromium.org/gitweb/?p=webm/libwebp.git;a=history;f=src/webp/encode.h;hb=HEAD -http://git.chromium.org/gitweb/?p=webm/libwebp.git;a=history;f=src/webp/decode.h;hb=HEAD \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Resources/Unmanaged/x64/libwebp.dll.REMOVED.git-id b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Resources/Unmanaged/x64/libwebp.dll.REMOVED.git-id deleted file mode 100644 index 35684c541..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Resources/Unmanaged/x64/libwebp.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -dcadab1b5b86469758707bff22558b33e5c51552 \ No newline at end of file diff --git a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Resources/Unmanaged/x86/libwebp.dll.REMOVED.git-id b/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Resources/Unmanaged/x86/libwebp.dll.REMOVED.git-id deleted file mode 100644 index 129db9826..000000000 --- a/old/src/Plugins/ImageProcessor/ImageProcessor.Plugins.WebP/Resources/Unmanaged/x86/libwebp.dll.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -ad47008dd1e64ea220bc745e28f568277434d661 \ No newline at end of file diff --git a/old/src/Settings.StyleCop b/old/src/Settings.StyleCop deleted file mode 100644 index 437aad55d..000000000 --- a/old/src/Settings.StyleCop +++ /dev/null @@ -1,42 +0,0 @@ - - - - behaviour - bootstrapper - cb - chrominance - colour - enum - exif - Mutexes - querystring - halftoning - interp - lomograph - Lomograph - lossy - octree - png - quantizer - uncalibrated - webp - - - - - - James South - Copyright (c) James South. -Licensed under the Apache License, Version 2.0. - - - - - - hi - lo - - - - - \ No newline at end of file diff --git a/old/src/TestWebsites/.gitignore b/old/src/TestWebsites/.gitignore deleted file mode 100644 index 8df228928..000000000 --- a/old/src/TestWebsites/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Cached images and test image copies -**/cache/ -**/images diff --git a/old/src/TestWebsites/MVC/App_Start/FilterConfig.cs b/old/src/TestWebsites/MVC/App_Start/FilterConfig.cs deleted file mode 100644 index 884ad21d3..000000000 --- a/old/src/TestWebsites/MVC/App_Start/FilterConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Web; -using System.Web.Mvc; - -namespace Test_Website_NET45 -{ - public class FilterConfig - { - public static void RegisterGlobalFilters(GlobalFilterCollection filters) - { - filters.Add(new HandleErrorAttribute()); - } - } -} \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/App_Start/RouteConfig.cs b/old/src/TestWebsites/MVC/App_Start/RouteConfig.cs deleted file mode 100644 index a2deff9e5..000000000 --- a/old/src/TestWebsites/MVC/App_Start/RouteConfig.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; - -namespace Test_Website_NET45 -{ - public class RouteConfig - { - public static void RegisterRoutes(RouteCollection routes) - { - routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); - - routes.MapRoute( - name: "Default", - url: "{controller}/{action}/{id}", - defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } - ); - } - } -} \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/App_Start/WebApiConfig.cs b/old/src/TestWebsites/MVC/App_Start/WebApiConfig.cs deleted file mode 100644 index 61aaf8674..000000000 --- a/old/src/TestWebsites/MVC/App_Start/WebApiConfig.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Http; - -namespace Test_Website_NET45 -{ - public static class WebApiConfig - { - public static void Register(HttpConfiguration config) - { - config.Routes.MapHttpRoute( - name: "DefaultApi", - routeTemplate: "api/{controller}/{id}", - defaults: new { id = RouteParameter.Optional } - ); - } - } -} diff --git a/old/src/TestWebsites/MVC/Content/responsive.min.css.REMOVED.git-id b/old/src/TestWebsites/MVC/Content/responsive.min.css.REMOVED.git-id deleted file mode 100644 index bcf841f2a..000000000 --- a/old/src/TestWebsites/MVC/Content/responsive.min.css.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -e0fbb23ec0c6b4a6980ac29f0c71b82ff900eebc \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Controllers/HomeController.cs b/old/src/TestWebsites/MVC/Controllers/HomeController.cs deleted file mode 100644 index 1eae92d44..000000000 --- a/old/src/TestWebsites/MVC/Controllers/HomeController.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; - -namespace Test_Website_NET45.Controllers -{ - public class HomeController : Controller - { - // - // GET: /Home/ - - public ActionResult Index() - { - return this.View(); - } - - public ActionResult Png() - { - return this.View(); - } - - public ActionResult Png8() - { - return this.View(); - } - - public ActionResult Gif() - { - return this.View(); - } - - public ActionResult Bmp() - { - return View(); - } - - public ActionResult Tiff() - { - return View(); - } - - public ActionResult WebP() - { - return View(); - } - - public ActionResult External() - { - return this.View(); - } - } -} diff --git a/old/src/TestWebsites/MVC/Global.asax b/old/src/TestWebsites/MVC/Global.asax deleted file mode 100644 index 66e38e1b7..000000000 --- a/old/src/TestWebsites/MVC/Global.asax +++ /dev/null @@ -1 +0,0 @@ -<%@ Application Codebehind="Global.asax.cs" Inherits="Test_Website_NET45.MvcApplication" Language="C#" %> diff --git a/old/src/TestWebsites/MVC/Global.asax.cs b/old/src/TestWebsites/MVC/Global.asax.cs deleted file mode 100644 index ef908f1ba..000000000 --- a/old/src/TestWebsites/MVC/Global.asax.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Http; -using System.Web.Mvc; -using System.Web.Routing; - -namespace Test_Website_NET45 -{ - using System.Diagnostics; - using System.Threading.Tasks; - using System.Web.UI.WebControls; - - using ImageProcessor.Web.Helpers; - using ImageProcessor.Web.HttpModules; - - // Note: For instructions on enabling IIS6 or IIS7 classic mode, - // visit http://go.microsoft.com/?LinkId=9394801 - public class MvcApplication : System.Web.HttpApplication - { - protected void Application_Start() - { - AreaRegistration.RegisterAllAreas(); - - WebApiConfig.Register(GlobalConfiguration.Configuration); - FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); - RouteConfig.RegisterRoutes(RouteTable.Routes); - - // Test the post processing event. - //ImageProcessingModule.OnPostProcessing += (sender, args) => Debug.WriteLine(args.CachedImagePath); - - //ImageProcessingModule.OnProcessQuerystring += (sender, args) => - // { - // if (!args.RawUrl.Contains("penguins")) - // { - // return args.Querystring += "watermark=protected&color=fff&fontsize=36&fontopacity=70textshadow=true&fontfamily=arial"; - // } - - // return args.Querystring; - // }; - } - - private async void WritePath(object sender, PostProcessingEventArgs e) - { - await Task.Run(() => Debug.WriteLine(e.CachedImagePath)); - } - } -} \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Properties/AssemblyInfo.cs b/old/src/TestWebsites/MVC/Properties/AssemblyInfo.cs deleted file mode 100644 index f1b6b5722..000000000 --- a/old/src/TestWebsites/MVC/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Test_Website_NET45")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Test_Website_NET45")] -[assembly: AssemblyCopyright("Copyright © 2013")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("32008595-f259-4c66-ab14-5503094adced")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/old/src/TestWebsites/MVC/TestImageService.cs b/old/src/TestWebsites/MVC/TestImageService.cs deleted file mode 100644 index 531a02490..000000000 --- a/old/src/TestWebsites/MVC/TestImageService.cs +++ /dev/null @@ -1,131 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) James South. -// Licensed under the Apache License, Version 2.0. -// -// -// The test image service. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace Test_Website_NET45 -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading.Tasks; - using System.Web; - using System.Web.Hosting; - - using ImageProcessor.Web.Helpers; - using ImageProcessor.Web.Services; - - /// - /// The test image service. - /// - public class TestImageService : IImageService - { - /// - /// The prefix for the given implementation. - /// - private string prefix = "testprovider.axd"; - - /// - /// Gets or sets the prefix for the given implementation. - /// - /// This value is used as a prefix for any image requests that should use this service. - /// - /// - public string Prefix - { - get - { - return this.prefix; - } - - set - { - this.prefix = value; - } - } - - /// - /// Gets a value indicating whether the image service requests files from - /// the locally based file system. - /// - public bool IsFileLocalService - { - get - { - return true; - } - } - - /// - /// Gets or sets any additional settings required by the service. - /// - public Dictionary Settings { get; set; } - - /// - /// Gets or sets the white list of . - /// - public Uri[] WhiteList { get; set; } - - /// - /// Gets a value indicating whether the current request passes sanitizing rules. - /// - /// - /// The image path. - /// - /// - /// True if the request is valid; otherwise, False. - /// - public bool IsValidRequest(string path) - { - return ImageHelpers.IsValidImageExtension(path.Split(new[] { '&', '?' })[0]); - } - - /// - /// Gets the image using the given identifier. - /// - /// - /// The value identifying the image to fetch. - /// - /// - /// The array containing the image data. - /// - public async Task GetImage(object id) - { - const string AppData = "~/App_Data/images"; - string imageRoot = HostingEnvironment.MapPath(AppData); - - if (imageRoot == null) - { - throw new HttpException(404, "No root path found to serve " + id); - } - - // In this instance we are just processing a set path. - // If you are using the querystring params as a means of identifying the correct image - // then you can do something with it here. - string path = Path.Combine(imageRoot, id.ToString().Split(new[] { '&', '?' })[0]); - byte[] buffer; - - // Check to see if the file exists. - // ReSharper disable once AssignNullToNotNullAttribute - FileInfo fileInfo = new FileInfo(path); - - if (!fileInfo.Exists) - { - throw new HttpException(404, "Nothing found at " + id); - } - - using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) - { - buffer = new byte[file.Length]; - await file.ReadAsync(buffer, 0, (int)file.Length); - } - - return buffer; - } - } -} \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Test_Website_MVC.csproj b/old/src/TestWebsites/MVC/Test_Website_MVC.csproj deleted file mode 100644 index a53fcbde1..000000000 --- a/old/src/TestWebsites/MVC/Test_Website_MVC.csproj +++ /dev/null @@ -1,248 +0,0 @@ - - - - - Debug - AnyCPU - - - 2.0 - {F6A208E9-C18F-43E9-B051-3C6EED30FDAF} - {E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - Test_Website_NET45 - Test_Website_NET45 - v4.5 - false - true - - - - - ..\..\..\ - true - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - - - - - True - ..\..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - - ..\..\packages\Microsoft.AspNet.Mvc.FixedDisplayModes.1.0.1\lib\net40\Microsoft.Web.Mvc.FixedDisplayModes.dll - - - ..\..\..\packages\Newtonsoft.Json.5.0.8\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - - - True - ..\..\..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.Helpers.dll - - - True - ..\..\packages\Microsoft.AspNet.Mvc.4.0.40804.0\lib\net40\System.Web.Mvc.dll - - - True - ..\..\..\packages\Microsoft.AspNet.Razor.2.0.30506.0\lib\net40\System.Web.Razor.dll - - - True - ..\..\..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.dll - - - True - ..\..\..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Deployment.dll - - - True - ..\..\..\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\System.Web.WebPages.Razor.dll - - - - - - - - - - - - - - ..\packages\Microsoft.AspNet.WebApi.Client.4.0.20710.0\lib\net40\System.Net.Http.Formatting.dll - - - - - ..\packages\Microsoft.AspNet.WebApi.Core.4.0.20710.0\lib\net40\System.Web.Http.dll - - - ..\packages\Microsoft.AspNet.WebApi.WebHost.4.0.20710.0\lib\net40\System.Web.Http.WebHost.dll - - - - - - - Global.asax - - - - - - - - - - - Designer - - - Web.config - - - Web.config - - - - - - - - - - Designer - - - - - - - - - - - - - - {3c805e4c-d679-43f8-8c43-8909cdb4d4d7} - ImageProcessor.Web.Plugins.AzureBlobCache - - - {55d08737-7d7e-4995-8892-bd9f944329e6} - ImageProcessor.Web.PostProcessor - - - {d011a778-59c8-4bfa-a770-c350216bf161} - ImageProcessor.Web - - - {3b5dd734-fb7a-487d-8ce6-55e7af9aea7e} - ImageProcessor - - - {2cf69699-959a-44dc-a281-4e2596c25043} - ImageProcessor.Plugins.WebP - - - - - Designer - - - - - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - - - - True - True - 56639 - / - http://localhost:56639/ - False - False - - - False - - - - - - - - - - \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Views/Home/Bmp.cshtml b/old/src/TestWebsites/MVC/Views/Home/Bmp.cshtml deleted file mode 100644 index 92632c475..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/Bmp.cshtml +++ /dev/null @@ -1,100 +0,0 @@ -@{ - ViewBag.Title = "Bmp"; -} - -
-

Bmp

-
-
-
-

Resized

- -
-
-

Cropped

- -
-
-
-
-

Filter

-
-
-

blackwhite

- -
-
-

comic

- -
-
-
-
-

lomograph

- -
-
-

greyscale

- -
-
-
-
-

polaroid

- -
-
-

sepia

- -
-
-
-
-

gotham

- -
-
-

hisatch

- -
-
-
-
-

losatch

- -
-
-
-
-
-
-

Watermark

- -
-
-

Format

- -
-
-
-
-
-
-

Rotate

- -
-
-

Quality

- -
-
-
-
-
-
-

Alpha

- -
-
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Home/External.cshtml b/old/src/TestWebsites/MVC/Views/Home/External.cshtml deleted file mode 100644 index 0e18af825..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/External.cshtml +++ /dev/null @@ -1,28 +0,0 @@ -@{ - ViewBag.Title = "External"; -} -

External

-
-
-
-

Current

- -

Legacy

- -
-
-

Current

- -

Legacy

- -
-
-
-
-

Current

- -

Legacy

- -
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Home/Gif.cshtml b/old/src/TestWebsites/MVC/Views/Home/Gif.cshtml deleted file mode 100644 index fdaaf184e..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/Gif.cshtml +++ /dev/null @@ -1,107 +0,0 @@ -@{ - ViewBag.Title = "Gif"; -} -
-

Gif

-
-
-
-

Resized

- -
-
-

Cropped

- -
-
-
-
-

Filter

-
-
-

blackwhite

- -
-
-

comic

- -
-
-
-
-

lomograph

- -
-
-

greyscale

- -
-
-
-
-

polaroid

- -
-
-

sepia

- -
-
-
-
-

gotham

- -
-
-

hisatch

- -
-
-
-
-

losatch

- -
-
-
-
-
-
-

Watermark

- -
-
-

Format

- -
-
-
-
-
-
-

Rotate

- -
-
-

Quality

- -
-
-
-
-
-
-

Alpha

- -
-
-
-
-
-
-

Animated

- -
-
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Home/Index.cshtml b/old/src/TestWebsites/MVC/Views/Home/Index.cshtml deleted file mode 100644 index bdc7dccba..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/Index.cshtml +++ /dev/null @@ -1,29 +0,0 @@ -@{ - ViewBag.Title = "Home Page"; -} -
-

Jpg

-
-
-
-

Resized

- - - - -
-
-

Resized Remote

- -
-
-
-
-
-
-

Resized Remote

- -
-
-
-
\ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Views/Home/Png.cshtml b/old/src/TestWebsites/MVC/Views/Home/Png.cshtml deleted file mode 100644 index 370f154ee..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/Png.cshtml +++ /dev/null @@ -1,103 +0,0 @@ -@{ - ViewBag.Title = "Png"; -} -
-

Png

-
-
-
-

Resized

- -
-
-

Cropped

- -
-
-
-
-

Filter

-
-
-

blackwhite

- -
-
-

comic

- -
-
-
-
-

lomograph

- -
-
-

greyscale

- -
-
-
-
-

polaroid

- -
-
-

sepia

- -
-
-
-
-

gotham

- -
-
-

hisatch

- -
-
-
-
-

losatch

- -
-
-
-
-
-
-

Watermark

- -
-
-

Format

- -
-
-
-
-
-
-

Rotate

- -
-
-

Quality

- -
-
-
-
-
-
-

Alpha

- -
-
-

Rounded Corners

- -
-
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Home/Png8.cshtml b/old/src/TestWebsites/MVC/Views/Home/Png8.cshtml deleted file mode 100644 index 83965572b..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/Png8.cshtml +++ /dev/null @@ -1,100 +0,0 @@ -@{ - ViewBag.Title = "Png8"; -} - -
-

Png8

-
-
-
-

Resized

- -
-
-

Cropped

- -
-
-
-
-

Filter

-
-
-

blackwhite

- -
-
-

comic

- -
-
-
-
-

lomograph

- -
-
-

greyscale

- -
-
-
-
-

polaroid

- -
-
-

sepia

- -
-
-
-
-

gotham

- -
-
-

hisatch

- -
-
-
-
-

losatch

- -
-
-
-
-
-
-

Watermark

- -
-
-

Format

- -
-
-
-
-
-
-

Rotate

- -
-
-

Quality

- -
-
-
-
-
-
-

Alpha

- -
-
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Home/Tiff.cshtml b/old/src/TestWebsites/MVC/Views/Home/Tiff.cshtml deleted file mode 100644 index 2a09241e2..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/Tiff.cshtml +++ /dev/null @@ -1,99 +0,0 @@ -@{ - ViewBag.Title = "Tiff"; -} -
-

Tiff

-
-
-
-

Resized

- -
-
-

Cropped

- -
-
-
-
-

Filter

-
-
-

blackwhite

- -
-
-

comic

- -
-
-
-
-

lomograph

- -
-
-

greyscale

- -
-
-
-
-

polaroid

- -
-
-

sepia

- -
-
-
-
-

gotham

- -
-
-

hisatch

- -
-
-
-
-

losatch

- -
-
-
-
-
-
-

Watermark

- -
-
-

Format

- -
-
-
-
-
-
-

Rotate

- -
-
-

Quality

- -
-
-
-
-
-
-

Alpha

- -
-
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Home/WebP.cshtml b/old/src/TestWebsites/MVC/Views/Home/WebP.cshtml deleted file mode 100644 index 020647610..000000000 --- a/old/src/TestWebsites/MVC/Views/Home/WebP.cshtml +++ /dev/null @@ -1,100 +0,0 @@ -@{ - ViewBag.Title = "WebP"; -} - -
-

WebP

-
-
-
-

Resized

- -
-
-

Cropped

- -
-
-
-
-

Filter

-
-
-

blackwhite

- -
-
-

comic

- -
-
-
-
-

lomograph

- -
-
-

greyscale

- -
-
-
-
-

polaroid

- -
-
-

sepia

- -
-
-
-
-

gotham

- -
-
-

hisatch

- -
-
-
-
-

losatch

- -
-
-
-
-
-
-

Watermark

- -
-
-

Format

- -
-
-
-
-
-
-

Rotate

- -
-
-

Quality

- -
-
-
-
-
-
-

Alpha

- -
-
-
-
diff --git a/old/src/TestWebsites/MVC/Views/Shared/_Layout.cshtml b/old/src/TestWebsites/MVC/Views/Shared/_Layout.cshtml deleted file mode 100644 index 5f8255ea4..000000000 --- a/old/src/TestWebsites/MVC/Views/Shared/_Layout.cshtml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - @ViewBag.Title - - - - -
-
-

ImageProcessor NET4.5

-
- -
- @RenderBody() -
-
- - diff --git a/old/src/TestWebsites/MVC/Views/Web.config b/old/src/TestWebsites/MVC/Views/Web.config deleted file mode 100644 index ca2f8f0fb..000000000 --- a/old/src/TestWebsites/MVC/Views/Web.config +++ /dev/null @@ -1,58 +0,0 @@ - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/old/src/TestWebsites/MVC/Views/_ViewStart.cshtml b/old/src/TestWebsites/MVC/Views/_ViewStart.cshtml deleted file mode 100644 index efda124b1..000000000 --- a/old/src/TestWebsites/MVC/Views/_ViewStart.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@{ - Layout = "~/Views/Shared/_Layout.cshtml"; -} \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Web.Debug.config b/old/src/TestWebsites/MVC/Web.Debug.config deleted file mode 100644 index 3e2a97c95..000000000 --- a/old/src/TestWebsites/MVC/Web.Debug.config +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Web.Release.config b/old/src/TestWebsites/MVC/Web.Release.config deleted file mode 100644 index 9fd481fdf..000000000 --- a/old/src/TestWebsites/MVC/Web.Release.config +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/Web.config b/old/src/TestWebsites/MVC/Web.config deleted file mode 100644 index 6da269c4c..000000000 --- a/old/src/TestWebsites/MVC/Web.config +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/old/src/TestWebsites/MVC/config/imageprocessor/cache.config b/old/src/TestWebsites/MVC/config/imageprocessor/cache.config deleted file mode 100644 index 0ddede8b8..000000000 --- a/old/src/TestWebsites/MVC/config/imageprocessor/cache.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/old/src/TestWebsites/MVC/config/imageprocessor/processing.config b/old/src/TestWebsites/MVC/config/imageprocessor/processing.config deleted file mode 100644 index 4b41cafd3..000000000 --- a/old/src/TestWebsites/MVC/config/imageprocessor/processing.config +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/old/src/TestWebsites/MVC/config/imageprocessor/security.config b/old/src/TestWebsites/MVC/config/imageprocessor/security.config deleted file mode 100644 index 5c0e8da08..000000000 --- a/old/src/TestWebsites/MVC/config/imageprocessor/security.config +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/old/src/TestWebsites/MVC/packages.config b/old/src/TestWebsites/MVC/packages.config deleted file mode 100644 index 4fa29d03a..000000000 --- a/old/src/TestWebsites/MVC/packages.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ImageProcessor/ImageProcessor.csproj b/src/ImageProcessor/ImageProcessor.csproj index f5db1868f..5b100ca08 100644 --- a/src/ImageProcessor/ImageProcessor.csproj +++ b/src/ImageProcessor/ImageProcessor.csproj @@ -181,12 +181,10 @@ - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - \ No newline at end of file + diff --git a/tests/ImageProcessor.Tests/ImageProcessor.Tests.csproj b/tests/ImageProcessor.Tests/ImageProcessor.Tests.csproj index 1302c6aa2..893425d4d 100644 --- a/tests/ImageProcessor.Tests/ImageProcessor.Tests.csproj +++ b/tests/ImageProcessor.Tests/ImageProcessor.Tests.csproj @@ -78,7 +78,5 @@ - - - \ No newline at end of file +