├── .gitattributes ├── .github └── workflows │ └── dotnet-core.yml ├── .gitignore ├── ImageResizer.AspNetCore ├── Funcs │ ├── Crop.cs │ ├── Padding.cs │ ├── RotateAndFlip.cs │ └── Watermark.cs ├── Helpers │ ├── Extensions.cs │ └── Params.cs ├── ImageResizer.AspNetCore.csproj ├── ImageResizerMiddleware.cs ├── ImageResizing.ico ├── ImageResizing.png ├── Models │ ├── WatermarkImageModel.cs │ ├── WatermarkTextModel.cs │ └── WatermarksModel.cs └── Properties │ └── launchSettings.json ├── ImageResizing.sln ├── LICENSE ├── README.md └── TestExample ├── .config └── dotnet-tools.json ├── Controllers └── HomeController.cs ├── Program.cs ├── Properties └── launchSettings.json ├── Startup.cs ├── TestExample.csproj ├── Views ├── Home │ └── Index.cshtml ├── Shared │ ├── Error.cshtml │ └── _Layout.cshtml ├── _ViewImports.cshtml └── _ViewStart.cshtml ├── appsettings.Development.json ├── appsettings.json ├── libman.json ├── output.jpg └── wwwroot ├── ImageResizerJson.json └── images ├── kurdcity.jpg ├── kurdcity1.jpg ├── kurdcity2.jpg └── kurdcity3.jpg /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/dotnet-core.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: 4 | push: 5 | branches: [ release ] 6 | pull_request: 7 | branches: [ release ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Setup .NET Core 17 | uses: actions/setup-dotnet@v1 18 | with: 19 | dotnet-version: 3.1.301 20 | - name: Install dependencies 21 | run: dotnet restore 22 | - name: Build 23 | run: dotnet build --configuration Release --no-restore 24 | - name: Test 25 | run: dotnet test --no-restore --verbosity normal 26 | - name: Publish 27 | uses: tanaka-takayoshi/nuget-publish-to-github-packages-action@v2.1 28 | with: 29 | nupkg-path: './artifacts/*.nupkg' 30 | repo-owner: 'cornelha' 31 | gh-user: 'cornelha' 32 | token: ${{ secrets.GITHUB_TOKEN }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Funcs/Crop.cs: -------------------------------------------------------------------------------- 1 | using ImageResizer.AspNetCore.Helpers; 2 | using SkiaSharp; 3 | using System; 4 | 5 | namespace ImageResizer.AspNetCore.Funcs 6 | { 7 | internal static class Crop 8 | { 9 | internal static SKBitmap CropImage(SKBitmap original, ResizeParams resizeParams) 10 | { 11 | var cropSides = 0; 12 | var cropTopBottom = 0; 13 | 14 | // calculate amount of pixels to remove from sides and top/bottom 15 | if ((float)resizeParams.w / original.Width < resizeParams.h / original.Height) // crop sides 16 | cropSides = original.Width - (int)Math.Round((float)original.Height / resizeParams.h * resizeParams.w); 17 | else 18 | cropTopBottom = original.Height - (int)Math.Round((float)original.Width / resizeParams.w * resizeParams.h); 19 | 20 | // setup crop rect 21 | var cropRect = new SKRectI 22 | { 23 | Left = cropSides / 2, 24 | Top = cropTopBottom / 2, 25 | Right = original.Width - cropSides + cropSides / 2, 26 | Bottom = original.Height - cropTopBottom + cropTopBottom / 2 27 | }; 28 | 29 | // crop 30 | SKBitmap bitmap = new SKBitmap(cropRect.Width, cropRect.Height); 31 | original.ExtractSubset(bitmap, cropRect); 32 | original.Dispose(); 33 | 34 | return bitmap; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Funcs/Padding.cs: -------------------------------------------------------------------------------- 1 | using SkiaSharp; 2 | 3 | 4 | namespace ImageResizer.AspNetCore.Funcs 5 | { 6 | internal static class Padding 7 | { 8 | internal static SKBitmap PaddingImage(SKBitmap original, int paddedWidth, int paddedHeight, bool isOpaque) 9 | { 10 | // setup new bitmap and optionally clear 11 | var bitmap = new SKBitmap(paddedWidth, paddedHeight, isOpaque); 12 | var canvas = new SKCanvas(bitmap); 13 | if (isOpaque) 14 | canvas.Clear(new SKColor(255, 255, 255)); // we could make this color a resizeParam 15 | else 16 | canvas.Clear(SKColor.Empty); 17 | 18 | // find co-ords to draw original at 19 | var left = original.Width < paddedWidth ? (paddedWidth - original.Width) / 2 : 0; 20 | var top = original.Height < paddedHeight ? (paddedHeight - original.Height) / 2 : 0; 21 | 22 | var drawRect = new SKRectI 23 | { 24 | Left = left, 25 | Top = top, 26 | Right = original.Width + left, 27 | Bottom = original.Height + top 28 | }; 29 | 30 | // draw original onto padded version 31 | canvas.DrawBitmap(original, drawRect); 32 | canvas.Flush(); 33 | canvas.Dispose(); 34 | original.Dispose(); 35 | 36 | return bitmap; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Funcs/RotateAndFlip.cs: -------------------------------------------------------------------------------- 1 | using SkiaSharp; 2 | using System.Linq; 3 | 4 | namespace ImageResizer.AspNetCore.Funcs 5 | { 6 | internal static class RotateAndFlip 7 | { 8 | internal static SKBitmap RotateAndFlipImage(SKBitmap original, SKEncodedOrigin origin) 9 | { 10 | // these are the origins that represent a 90 degree turn in some fashion 11 | var differentOrientations = new SKEncodedOrigin[] 12 | { 13 | SKEncodedOrigin.LeftBottom, 14 | SKEncodedOrigin.LeftTop, 15 | SKEncodedOrigin.RightBottom, 16 | SKEncodedOrigin.RightTop 17 | }; 18 | 19 | // check if we need to turn the image 20 | bool isDifferentOrientation = differentOrientations.Any(o => o == origin); 21 | 22 | // define new width/height 23 | var width = isDifferentOrientation ? original.Height : original.Width; 24 | var height = isDifferentOrientation ? original.Width : original.Height; 25 | 26 | var bitmap = new SKBitmap(width, height, original.AlphaType == SKAlphaType.Opaque); 27 | 28 | // todo: the stuff in this switch statement should be rewritten to use pointers 29 | switch (origin) 30 | { 31 | case SKEncodedOrigin.LeftBottom: 32 | 33 | for (var x = 0; x < original.Width; x++) 34 | for (var y = 0; y < original.Height; y++) 35 | bitmap.SetPixel(y, original.Width - 1 - x, original.GetPixel(x, y)); 36 | break; 37 | 38 | case SKEncodedOrigin.RightTop: 39 | 40 | for (var x = 0; x < original.Width; x++) 41 | for (var y = 0; y < original.Height; y++) 42 | bitmap.SetPixel(original.Height - 1 - y, x, original.GetPixel(x, y)); 43 | break; 44 | 45 | case SKEncodedOrigin.RightBottom: 46 | 47 | for (var x = 0; x < original.Width; x++) 48 | for (var y = 0; y < original.Height; y++) 49 | bitmap.SetPixel(original.Height - 1 - y, original.Width - 1 - x, original.GetPixel(x, y)); 50 | 51 | break; 52 | 53 | case SKEncodedOrigin.LeftTop: 54 | 55 | for (var x = 0; x < original.Width; x++) 56 | for (var y = 0; y < original.Height; y++) 57 | bitmap.SetPixel(y, x, original.GetPixel(x, y)); 58 | break; 59 | 60 | case SKEncodedOrigin.BottomLeft: 61 | 62 | for (var x = 0; x < original.Width; x++) 63 | for (var y = 0; y < original.Height; y++) 64 | bitmap.SetPixel(x, original.Height - 1 - y, original.GetPixel(x, y)); 65 | break; 66 | 67 | case SKEncodedOrigin.BottomRight: 68 | 69 | for (var x = 0; x < original.Width; x++) 70 | for (var y = 0; y < original.Height; y++) 71 | bitmap.SetPixel(original.Width - 1 - x, original.Height - 1 - y, original.GetPixel(x, y)); 72 | break; 73 | 74 | case SKEncodedOrigin.TopRight: 75 | 76 | for (var x = 0; x < original.Width; x++) 77 | for (var y = 0; y < original.Height; y++) 78 | bitmap.SetPixel(original.Width - 1 - x, y, original.GetPixel(x, y)); 79 | break; 80 | 81 | } 82 | 83 | original.Dispose(); 84 | 85 | return bitmap; 86 | 87 | 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Funcs/Watermark.cs: -------------------------------------------------------------------------------- 1 | using ImageResizer.AspNetCore.Helpers; 2 | using ImageResizer.AspNetCore.Models; 3 | using SkiaSharp; 4 | 5 | namespace ImageResizer.AspNetCore.Funcs 6 | { 7 | internal static class Watermark 8 | { 9 | internal static SKBitmap WatermarkText(SKBitmap original, ResizeParams resizeParams, WatermarkTextModel watermarkText) 10 | { 11 | var toBitmap = new SKBitmap(original.Width, original.Height); 12 | var canvas = new SKCanvas(toBitmap); 13 | // Draw a bitmap rescaled 14 | 15 | 16 | var paint = new SKPaint(); 17 | //paint.Typeface = SKTypeface.FromFamilyName("Arial"); 18 | paint.TextSize = watermarkText.TextSize; 19 | paint.TextAlign = watermarkText.TextAlign.GetSKTextAlign(); 20 | if (watermarkText.IsVerticalText) 21 | paint.IsVerticalText = true; 22 | else 23 | paint.IsLinearText = true; 24 | 25 | if (watermarkText.Type == 2) 26 | { 27 | paint.IsStroke = true; 28 | paint.StrokeWidth = watermarkText.StrokeWidth; 29 | paint.StrokeCap = SKStrokeCap.Round; 30 | } 31 | paint.Style = watermarkText.Type.GetSKPaintStyle(); 32 | paint.FilterQuality = watermarkText.Quality.GetSKFilterQuality(); 33 | paint.TextSkewX = watermarkText.TextSkewX; 34 | paint.IsAntialias = true; 35 | 36 | //https://www.color-hex.com/ 37 | if (SKColor.TryParse(watermarkText.Color, out SKColor color)) 38 | { 39 | paint.Color = color; 40 | } 41 | else 42 | { 43 | paint.Color = SKColors.Black; 44 | } 45 | 46 | canvas.DrawBitmap(original, 0,0); 47 | 48 | var x = watermarkText.PositionMeasureType == 1 ? watermarkText.X : watermarkText.X.ToPixel(original.Width); 49 | var y = watermarkText.PositionMeasureType == 1 ? watermarkText.Y : watermarkText.Y.ToPixel(original.Height); 50 | 51 | canvas.DrawText(watermarkText.Value, x, y, paint); 52 | 53 | canvas.Flush(); 54 | 55 | canvas.Dispose(); 56 | paint.Dispose(); 57 | original.Dispose(); 58 | 59 | return toBitmap; 60 | } 61 | internal static SKBitmap WatermarkImage(SKBitmap original, ResizeParams resizeParams, WatermarkImageModel watermarkImage) 62 | { 63 | return null; 64 | } 65 | 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Helpers/Extensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using SkiaSharp; 4 | 5 | namespace ImageResizer.AspNetCore.Helpers 6 | { 7 | public static class Extensions 8 | { 9 | public static IServiceCollection AddImageResizer(this IServiceCollection services) 10 | { 11 | return services.AddMemoryCache(); 12 | } 13 | 14 | public static IApplicationBuilder UseImageResizer(this IApplicationBuilder builder) 15 | { 16 | return builder.UseMiddleware(); 17 | } 18 | 19 | internal static SKTextAlign GetSKTextAlign(this short align) 20 | { 21 | switch (align) 22 | { 23 | case 1: 24 | return SKTextAlign.Right; 25 | case 2: 26 | return SKTextAlign.Center; 27 | case 3: 28 | return SKTextAlign.Left; 29 | default: 30 | return SKTextAlign.Center; 31 | } 32 | } 33 | internal static SKFilterQuality GetSKFilterQuality(this short quality) 34 | { 35 | switch (quality) 36 | { 37 | case 1: 38 | return SKFilterQuality.None; 39 | case 2: 40 | return SKFilterQuality.Low; 41 | case 3: 42 | return SKFilterQuality.Medium; 43 | case 4: 44 | return SKFilterQuality.High; 45 | default: 46 | return SKFilterQuality.Medium; 47 | } 48 | } 49 | internal static SKPaintStyle GetSKPaintStyle(this short type) 50 | { 51 | switch (type) 52 | { 53 | case 1: 54 | return SKPaintStyle.Fill; 55 | case 2: 56 | return SKPaintStyle.Stroke; 57 | case 3: 58 | return SKPaintStyle.StrokeAndFill; 59 | default: 60 | return SKPaintStyle.Fill; 61 | } 62 | } 63 | internal static float ToPixel(this float persent, float imageXOrY) 64 | { 65 | return (imageXOrY * persent) / 100; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Helpers/Params.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace ImageResizer.AspNetCore.Helpers 6 | { 7 | struct ResizeParams 8 | { 9 | public bool hasParams; 10 | public int w; 11 | public int h; 12 | public bool autorotate; 13 | public int quality; // 0 - 100 14 | public string format; // png, jpg, jpeg 15 | public string mode; // pad, max, crop, stretch 16 | public short wmtext; 17 | public short wmimage; 18 | 19 | public static string[] modes = new string[] { "pad", "max", "crop", "stretch" }; 20 | 21 | public override string ToString() 22 | { 23 | var sb = new StringBuilder(); 24 | sb.Append($"w: {w}, "); 25 | sb.Append($"h: {h}, "); 26 | sb.Append($"autorotate: {autorotate}, "); 27 | sb.Append($"quality: {quality}, "); 28 | sb.Append($"format: {format}, "); 29 | sb.Append($"mode: {mode}, "); 30 | sb.Append($"wmtext: {wmtext}, "); 31 | sb.Append($"wmimage: {wmimage}"); 32 | 33 | return sb.ToString(); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/ImageResizer.AspNetCore.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Library 5 | net6.0;netcoreapp3.1; 6 | ImageResizing.ico 7 | 3.0.0 8 | Keyvan Abdollahzadeh 9 | 10 | ImageResizer.AspNetCore is the image server for ASP.NET CORE. It can be dropped into existing apps and works, enable fast and adaptive websites, and improve your sales by reducing page load time. 11 | it can do: 12 | Resize, Crop, Padding, Max, Stretch, Change Quality, Change Format 13 | Forked from: https://github.com/keyone2693/ImageResizer.AspNetCore 14 | 15 | Target Net 6.0 16 | Fix Middleware static file lookup path 17 | 18 | ImageResizer.AspNetCore 19 | https://github.com/cornelha/ImageResizer.AspNetCore 20 | https://github.com/cornelha/ImageResizer.AspNetCore 21 | public 22 | LICENSE 23 | ImageResizing.png 24 | 25 | ImageResizer.AspNetCore 26 | ImageResizer.AspNetCore 27 | ImageResizer.AspNetCore 28 | 2.0.0 29 | true 30 | 2.0.0 31 | 32 | 33 | true 34 | snupkg 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | True 55 | 56 | 57 | 58 | True 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/ImageResizerMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.Extensions.Caching.Memory; 4 | using Microsoft.Extensions.Logging; 5 | using SkiaSharp; 6 | using System; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Reflection; 10 | using ImageResizer.AspNetCore.Helpers; 11 | using System.Threading.Tasks; 12 | using ImageResizer.AspNetCore.Funcs; 13 | using Newtonsoft.Json; 14 | using ImageResizer.AspNetCore.Models; 15 | using Microsoft.Extensions.FileProviders; 16 | 17 | namespace ImageResizer.AspNetCore 18 | { 19 | public class ImageResizerMiddleware 20 | { 21 | private readonly RequestDelegate _req; 22 | private readonly ILogger _logger; 23 | private readonly IWebHostEnvironment _env; 24 | private readonly IMemoryCache _memoryCache; 25 | private readonly IFileProvider _fileProvider; 26 | private WatermarkTextModel watermarkText; 27 | private WatermarkImageModel watermarkImage; 28 | 29 | private static readonly string[] suffixes = new string[] { 30 | ".png", 31 | ".jpg", 32 | ".jpeg" 33 | }; 34 | 35 | public ImageResizerMiddleware( 36 | RequestDelegate req, 37 | IWebHostEnvironment env, 38 | ILogger logger, 39 | IMemoryCache memoryCache, 40 | IFileProvider fileProvider) 41 | { 42 | _req = req; 43 | _env = env; 44 | _logger = logger; 45 | _memoryCache = memoryCache; 46 | _fileProvider = fileProvider; 47 | } 48 | public async Task InvokeAsync(HttpContext context) 49 | { 50 | var path = context.Request.Path; 51 | 52 | var rootPath = _env.WebRootPath ?? _env.ContentRootPath; //use web or content root path 53 | 54 | 55 | // hand to next middleware if we are not dealing with an image 56 | if (context.Request.Query.Count == 0 || !IsImagePath(path)) 57 | { 58 | await _req.Invoke(context); 59 | return; 60 | } 61 | 62 | // hand to next middleware if we are dealing with an image but it doesn't have any usable resize querystring params 63 | var resizeParams = GetResizeParams(path, context.Request.Query); 64 | if (!resizeParams.hasParams) 65 | { 66 | await _req.Invoke(context); 67 | return; 68 | } 69 | var imageResizerJsonPath = Path.Combine(rootPath, "ImageResizerJson.json"); 70 | 71 | // if json file doesn't exist we don't work with watermark 72 | if (File.Exists(imageResizerJsonPath)) 73 | { 74 | var watermarks = new WatermarksModel(); 75 | 76 | using (StreamReader r = new StreamReader(imageResizerJsonPath)) 77 | { 78 | string json = r.ReadToEnd(); 79 | watermarks = JsonConvert.DeserializeObject(json); 80 | } 81 | 82 | if (resizeParams.wmtext != 0) 83 | { 84 | if (watermarks.WatermarkTextList.Any()) 85 | { 86 | watermarkText = watermarks.WatermarkTextList.FirstOrDefault(p => p.Key == resizeParams.wmtext); 87 | } 88 | } 89 | if (resizeParams.wmimage != 0) 90 | { 91 | if (watermarks.WatermarkImageList.Any()) 92 | { 93 | watermarkImage = watermarks.WatermarkImageList.FirstOrDefault(p => p.Key == resizeParams.wmimage); 94 | } 95 | } 96 | } 97 | 98 | // if we got this far, resize it 99 | _logger.LogInformation($"Resizing {path.Value} with params {resizeParams}"); 100 | var imagePath = _fileProvider.GetFileInfo(path.Value).PhysicalPath; 101 | //// get the image location on disk 102 | //var imagePath = Path.Combine( 103 | // rootPath.Replace("\\wwwroot", ""), 104 | // path.Value.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar)); 105 | 106 | // check file lastwrite 107 | var lastWriteTimeUtc = File.GetLastWriteTimeUtc(imagePath); 108 | if (lastWriteTimeUtc.Year == 1601) // file doesn't exist, pass to next middleware 109 | { 110 | await _req.Invoke(context); 111 | return; 112 | } 113 | 114 | var imageData = GetImageData(imagePath, resizeParams, lastWriteTimeUtc); 115 | 116 | // write to stream 117 | context.Response.ContentType = resizeParams.format == "png" ? "image/png" : "image/jpeg"; 118 | context.Response.ContentLength = imageData.Size; 119 | await context.Response.Body.WriteAsync(imageData.ToArray(), 0, (int)imageData.Size); 120 | 121 | // cleanup 122 | imageData.Dispose(); 123 | 124 | } 125 | private SKData GetImageData(string imagePath, ResizeParams resizeParams, DateTime lastWriteTimeUtc) 126 | { 127 | // check cache and return if cached 128 | long cacheKey; 129 | unchecked 130 | { 131 | cacheKey = imagePath.GetHashCode() + lastWriteTimeUtc.ToBinary() + resizeParams.ToString().GetHashCode(); 132 | } 133 | 134 | SKData imageData; 135 | bool isCached = _memoryCache.TryGetValue(cacheKey, out byte[] imageBytes); 136 | if (isCached) 137 | { 138 | _logger.LogInformation("Serving from cache"); 139 | return SKData.CreateCopy(imageBytes); 140 | } 141 | 142 | using (var fs = File.OpenRead(imagePath)) 143 | { 144 | // origin represents the EXIF orientation 145 | var bitmap = LoadBitmap(fs, out SKEncodedOrigin origin); // always load as 32bit (to overcome issues with indexed color) 146 | 147 | if (resizeParams.w == 0) 148 | { 149 | resizeParams.w = bitmap.Width; 150 | } 151 | if (resizeParams.h == 0) 152 | { 153 | resizeParams.h = bitmap.Height; 154 | } 155 | 156 | // if autorotate = true, and origin isn't correct for the rotation, rotate it 157 | if (resizeParams.autorotate && origin != SKEncodedOrigin.TopLeft) 158 | bitmap = RotateAndFlip.RotateAndFlipImage(bitmap, origin); 159 | 160 | // if either w or h is 0, set it based on ratio of original image 161 | if (resizeParams.h == 0) 162 | resizeParams.h = (int)Math.Round(bitmap.Height * (float)resizeParams.w / bitmap.Width); 163 | else if (resizeParams.w == 0) 164 | resizeParams.w = (int)Math.Round(bitmap.Width * (float)resizeParams.h / bitmap.Height); 165 | 166 | // if we need to crop, crop the original before resizing 167 | if (resizeParams.mode == "crop") 168 | bitmap = Crop.CropImage(bitmap, resizeParams); 169 | 170 | // store padded height and width 171 | var paddedHeight = resizeParams.h; 172 | var paddedWidth = resizeParams.w; 173 | 174 | // if we need to pad, or max, set the height or width according to ratio 175 | if (resizeParams.mode == "pad" || resizeParams.mode == "max") 176 | { 177 | var bitmapRatio = (float)bitmap.Width / bitmap.Height; 178 | var resizeRatio = (float)resizeParams.w / resizeParams.h; 179 | 180 | if (bitmapRatio > resizeRatio) // original is more "landscape" 181 | resizeParams.h = (int)Math.Round(bitmap.Height * ((float)resizeParams.w / bitmap.Width)); 182 | else 183 | resizeParams.w = (int)Math.Round(bitmap.Width * ((float)resizeParams.h / bitmap.Height)); 184 | } 185 | 186 | // resize 187 | var resizedImageInfo = new SKImageInfo(resizeParams.w, resizeParams.h, SKImageInfo.PlatformColorType, bitmap.AlphaType); 188 | var resizedBitmap = bitmap.Resize(resizedImageInfo, SKFilterQuality.High); 189 | 190 | // optionally pad 191 | if (resizeParams.mode == "pad") 192 | resizedBitmap = Padding.PaddingImage(resizedBitmap, paddedWidth, paddedHeight, resizeParams.format != "png"); 193 | 194 | // watermarkText 195 | if (resizeParams.wmtext != 0) 196 | { 197 | if (watermarkText != null) 198 | resizedBitmap = Watermark.WatermarkText(resizedBitmap, resizeParams, watermarkText); 199 | } 200 | // watermarkImage 201 | if (resizeParams.wmimage != 0) 202 | { 203 | if (watermarkImage != null) 204 | resizedBitmap = Watermark.WatermarkImage(resizedBitmap, resizeParams, watermarkImage); 205 | } 206 | 207 | 208 | // encode 209 | var resizedImage = SKImage.FromBitmap(resizedBitmap); 210 | var encodeFormat = resizeParams.format == "png" ? SKEncodedImageFormat.Png : SKEncodedImageFormat.Jpeg; 211 | imageData = resizedImage.Encode(encodeFormat, resizeParams.quality); 212 | 213 | // cache the result 214 | _memoryCache.Set(cacheKey, imageData.ToArray()); 215 | 216 | // cleanup 217 | resizedImage.Dispose(); 218 | bitmap.Dispose(); 219 | resizedBitmap.Dispose(); 220 | 221 | return imageData; 222 | } 223 | } 224 | 225 | private SKBitmap LoadBitmap(Stream stream, out SKEncodedOrigin origin) 226 | { 227 | using (var s = new SKManagedStream(stream)) 228 | using (var skData = SKData.Create(s)) 229 | using (var codec = SKCodec.Create(skData)) 230 | { 231 | origin = codec.EncodedOrigin; 232 | var info = codec.Info; 233 | var bitmap = new SKBitmap(info.Width, info.Height, SKImageInfo.PlatformColorType, info.IsOpaque ? SKAlphaType.Opaque : SKAlphaType.Premul); 234 | 235 | IntPtr length; 236 | var result = codec.GetPixels(bitmap.Info, bitmap.GetPixels(out length)); 237 | if (result == SKCodecResult.Success || result == SKCodecResult.IncompleteInput) 238 | { 239 | return bitmap; 240 | } 241 | else 242 | { 243 | throw new ArgumentException("Unable to load bitmap from provided data"); 244 | } 245 | } 246 | } 247 | 248 | private bool IsImagePath(PathString path) 249 | { 250 | if (path == null || !path.HasValue) 251 | return false; 252 | 253 | return suffixes.Any(x => x.EndsWith(x, StringComparison.OrdinalIgnoreCase)); 254 | } 255 | 256 | private ResizeParams GetResizeParams(PathString path, IQueryCollection query) 257 | { 258 | ResizeParams resizeParams = new ResizeParams(); 259 | 260 | // before we extract, do a quick check for resize params 261 | resizeParams.hasParams = 262 | resizeParams.GetType().GetTypeInfo() 263 | .GetFields().Where(f => f.Name != "hasParams") 264 | .Any(f => query.ContainsKey(f.Name)); 265 | 266 | // if no params present, bug out 267 | if (!resizeParams.hasParams) 268 | return resizeParams; 269 | 270 | // extract resize params 271 | 272 | if (query.ContainsKey("format")) 273 | resizeParams.format = query["format"]; 274 | else 275 | resizeParams.format = path.Value.Substring(path.Value.LastIndexOf('.') + 1); 276 | 277 | if (query.ContainsKey("autorotate")) 278 | bool.TryParse(query["autorotate"], out resizeParams.autorotate); 279 | 280 | int quality = 100; 281 | if (query.ContainsKey("quality")) 282 | int.TryParse(query["quality"], out quality); 283 | resizeParams.quality = quality; 284 | 285 | int w = 0; 286 | if (query.ContainsKey("w")) 287 | int.TryParse(query["w"], out w); 288 | resizeParams.w = w; 289 | 290 | int h = 0; 291 | if (query.ContainsKey("h")) 292 | int.TryParse(query["h"], out h); 293 | resizeParams.h = h; 294 | 295 | resizeParams.mode = "max"; 296 | // only apply mode if it's a valid mode and both w and h are specified 297 | if (h != 0 && w != 0 && query.ContainsKey("mode") && ResizeParams.modes.Any(m => query["mode"] == m)) 298 | resizeParams.mode = query["mode"]; 299 | 300 | if (query.ContainsKey("wmtext")) 301 | resizeParams.wmtext = short.Parse(query["wmtext"]); 302 | else 303 | resizeParams.wmtext = 0; 304 | 305 | if (query.ContainsKey("wmimage")) 306 | resizeParams.wmimage = short.Parse(query["wmimage"]); 307 | else 308 | resizeParams.wmimage = 0; 309 | 310 | return resizeParams; 311 | } 312 | } 313 | } 314 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/ImageResizing.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/ImageResizer.AspNetCore/ImageResizing.ico -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/ImageResizing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/ImageResizer.AspNetCore/ImageResizing.png -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Models/WatermarkImageModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace ImageResizer.AspNetCore.Models 6 | { 7 | public class WatermarkImageModel 8 | { 9 | public short Key { get; set; } 10 | public string Url { get; set; } 11 | public short SizeMeasureType { get; set; } 12 | public float Width { get; set; } 13 | public float Height { get; set; } 14 | public short PositionMeasureType { get; set; } 15 | public float Top { get; set; } 16 | public float Right { get; set; } 17 | public float Bottom { get; set; } 18 | public float Left { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Models/WatermarkTextModel.cs: -------------------------------------------------------------------------------- 1 | using SkiaSharp; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace ImageResizer.AspNetCore.Models 7 | { 8 | public class WatermarkTextModel 9 | { 10 | public short Key { get; set; } 11 | public string Value { get; set; } 12 | public short PositionMeasureType { get; set; } 13 | public float X { get; set; } 14 | public float Y { get; set; } 15 | 16 | public bool IsVerticalText { get; set; } 17 | public string Color { get; set; } 18 | 19 | public short Type { get; set; } 20 | public float StrokeWidth { get; set; } 21 | 22 | public short Quality { get; set; } 23 | public float TextSize { get; set; } 24 | public short TextAlign { get; set; } 25 | public float TextSkewX { get; set; } 26 | public bool IsAntialias { get; set; } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Models/WatermarksModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace ImageResizer.AspNetCore.Models 6 | { 7 | public class WatermarksModel 8 | { 9 | public IEnumerable WatermarkTextList { get; set; } 10 | public IEnumerable WatermarkImageList { get; set; } 11 | } 12 | 13 | 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ImageResizer.AspNetCore/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "ImageResizer.AspNetCore": { 4 | "commandName": "Project" 5 | } 6 | } 7 | } -------------------------------------------------------------------------------- /ImageResizing.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29609.76 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImageResizer.AspNetCore", "ImageResizer.AspNetCore\ImageResizer.AspNetCore.csproj", "{524EDD8B-4CCC-43AD-8C64-5AFB99BC55A8}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestExample", "TestExample\TestExample.csproj", "{5CDC3CC8-E682-4911-85D0-A7C56F0C2476}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {524EDD8B-4CCC-43AD-8C64-5AFB99BC55A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {524EDD8B-4CCC-43AD-8C64-5AFB99BC55A8}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {524EDD8B-4CCC-43AD-8C64-5AFB99BC55A8}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {524EDD8B-4CCC-43AD-8C64-5AFB99BC55A8}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {5CDC3CC8-E682-4911-85D0-A7C56F0C2476}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {5CDC3CC8-E682-4911-85D0-A7C56F0C2476}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {5CDC3CC8-E682-4911-85D0-A7C56F0C2476}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {5CDC3CC8-E682-4911-85D0-A7C56F0C2476}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {927CE114-1AA5-4748-B04E-C7FF45E9F207} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Keyvan Abodollahzadeh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # ImageResizer.AspNetCore 3 | 4 | ## Development 5 | 6 | 7 | 8 | [![Build status](https://img.shields.io/appveyor/ci/keyone2693/imageresizer-aspnetcore.svg)](https://ci.appveyor.com/project/keyone2693/imageresizer-aspnetcore) 9 | [![NuGet](https://img.shields.io/nuget/v/ImageResizer.AspNetCore.svg)](https://www.nuget.org/packages/ImageResizer.AspNetCore/) 10 | [![GitHub issues](https://img.shields.io/github/issues/keyone2693/ImageResizer.AspNetCore.svg?maxAge=25920?style=plastic)](https://github.com/keyone2693/ImageResizer.AspNetCore/issues) 11 | [![GitHub stars](https://img.shields.io/github/stars/keyone2693/ImageResizer.AspNetCore.svg?maxAge=25920?style=plastic)](https://github.com/keyone2693/ImageResizer.AspNetCore/stargazers) 12 | [![GitHub license](https://img.shields.io/github/license/keyone2693/ImageResizer.AspNetCore.svg?maxAge=25920?style=plastic)](https://github.com/keyone2693/ImageResizer.AspNetCore/blob/master/LICENSE) 13 | 14 | 15 | ### You can see the DEMO here: [Demo](http://imageresizer.keyone2693.ir/) 16 | 17 | ### Before posting new issues: [Test samples](https://github.com/keyone2693/ImageResizer.AspNetCore/tree/master/TestExample) 18 | 19 | 20 | #### Current version: 2.0.x [Stable] 21 | In this version: 22 | all main functionality working 23 | except for disk cache and watermark which will be added soon 24 | the watermark as a text just added but need some bug fix 25 | 26 | ## Overview 27 | 28 | ## it's for DotNetCore only 29 | aspnetcore 2.0 + 30 | 31 | ## Easy to install 32 | Use the library as dll, reference from [nuget](https://www.nuget.org/packages/ImageResizer.AspNetCore/) 33 | or use this in package manager console 34 | ```c# 35 | Install-Package ImageResizer.AspNetCore 36 | ``` 37 | 38 | 39 | 40 | # Wiki 41 | 42 | for using this awesome library, you only need to add two things 43 | 44 | first: 45 | add this line of code to your Startup.cs 46 | 47 | 48 | ```c# 49 | public void ConfigureServices(IServiceCollection services) 50 | { 51 | services.AddSingleton(_ => new PhysicalFileProvider(_env.WebRootPath ?? _env.ContentRootPath)); 52 | //... 53 | services.AddImageResizer(); 54 | //... 55 | } 56 | ``` 57 | 58 | you may need this: 59 | 60 | ```c# 61 | private readonly IWebHostEnvironment _env; 62 | public Startup(IWebHostEnvironment env) 63 | { 64 | _env = env; 65 | var builder = new ConfigurationBuilder() 66 | .SetBasePath(env.ContentRootPath) 67 | .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 68 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 69 | .AddEnvironmentVariables(); 70 | Configuration = builder.Build(); 71 | } 72 | ``` 73 | 74 | Then this one : 75 | 76 | ```c# 77 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 78 | { 79 | //... 80 | // services.AddSingleton(_ => new PhysicalFileProvider(_env.WebRootPath ?? _env.ContentRootPath)); 81 | app.UseStaticFiles(); 82 | app.UseImageResizer(); 83 | //... 84 | } 85 | ``` 86 | and you can use it in your client-side(html,css,ts,...) just like below: 87 | 88 | Simple As That Enjoy :)) 89 | 90 | ```html 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | ``` 106 | 107 | -------------------------------------------------------------------------------- /TestExample/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "dotnet-ef": { 6 | "version": "3.1.0", 7 | "commands": [ 8 | "dotnet-ef" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /TestExample/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace TestExample.Controllers 8 | { 9 | public class HomeController : Controller 10 | { 11 | public IActionResult Index() 12 | { 13 | return View(); 14 | } 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /TestExample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace TestExample 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TestExample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:53764", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "TestExample": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "applicationUrl": "http://localhost:5000", 22 | "environmentVariables": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TestExample/Startup.cs: -------------------------------------------------------------------------------- 1 | using ImageResizer.AspNetCore.Helpers; 2 | 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Hosting; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.FileProviders; 8 | using Microsoft.Extensions.Hosting; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace TestExample 12 | { 13 | public class Startup 14 | { 15 | private readonly IWebHostEnvironment _env; 16 | 17 | public Startup(IWebHostEnvironment env) 18 | { 19 | _env = env; 20 | var builder = new ConfigurationBuilder() 21 | .SetBasePath(env.ContentRootPath) 22 | .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 23 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 24 | .AddEnvironmentVariables(); 25 | Configuration = builder.Build(); 26 | } 27 | public IConfigurationRoot Configuration { get; } 28 | public void ConfigureServices(IServiceCollection services) 29 | { 30 | services.AddSingleton(_ => new PhysicalFileProvider(_env.WebRootPath ?? _env.ContentRootPath)); 31 | services.AddControllersWithViews(); 32 | //AddImageResizer 33 | services.AddImageResizer(); 34 | } 35 | 36 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) 37 | { 38 | //loggerFactory.AddConsole(Configuration.GetSection("Logging")); 39 | //loggerFactory.AddDebug(); 40 | 41 | if (env.IsDevelopment()) 42 | { 43 | app.UseDeveloperExceptionPage(); 44 | } 45 | else 46 | { 47 | app.UseExceptionHandler("/Home/Error"); 48 | } 49 | //UseImageResizer 50 | app.UseImageResizer(); 51 | 52 | app.UseStaticFiles(); 53 | app.UseRouting(); 54 | app.UseEndpoints(endpoints => 55 | { 56 | endpoints.MapControllerRoute( 57 | name: "default", 58 | pattern: "{controller=Home}/{action=Index}/{id?}"); 59 | }); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /TestExample/TestExample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0;netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /TestExample/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "ImageResizer.AspNetCore Usage"; 3 | } 4 | 13 |
14 |
16 |

#Demo

17 |

The example for all functionality will be added here

18 |
19 |
20 | 21 |
22 |
23 |

#New Features

24 |

Watermark as a text just added :) still work to do

25 |
26 |
27 |
28 |
29 |
example.com/kurdcity.jpg?wmtext=1
30 | 33 | 50 |
51 |
52 |
example.com/kurdcity.jpg?wmtext=2
53 | 56 | 73 |
74 |
75 |
76 |
77 |
example.com/kurdcity.jpg?wmtext=3
78 | 81 | 98 |
99 |
100 |
example.com/kurdcity.jpg?wmtext=4
101 | 104 | 121 |
122 |
123 |
124 |
125 |

#Other Functionality

126 |

Will be improved if needed

127 |
128 |
129 | 130 |
131 |
132 |
example.com/kurdcity.jpg?w=200
133 | 136 | 153 |
154 |
155 |
example.com/kurdcity.jpg?h=300
156 | 159 | 176 |
177 |
178 | 179 | 180 |
181 |
182 |
example.com/kurdcity.jpg?format=png
183 | 186 | 203 |
204 |
205 |
example.com/kurdcity.jpg?format=jpg
206 | 209 | 226 |
227 |
228 | 229 |
230 |
231 |
example.com/kurdcity.jpg?format=jpeg
232 | 235 | 252 |
253 |
254 |
example.com/kurdcity.jpg?w=100&h=200&mode=pad
255 | 258 | 275 |
276 |
277 | 278 |
279 |
280 |
example.com/kurdcity.jpg?w=100&h=200&mode=max
281 | 284 | 301 |
302 |
303 |
example.com/kurdcity.jpg?w=100&h=200&mode=crop
304 | 307 | 324 |
325 |
326 | 327 |
328 |
329 |
example.com/kurdcity.jpg?w=100&h=200&mode=stretch
330 | 333 | 350 |
351 |
352 |
example.com/kurdcity.jpg?autorotate=true
353 | 356 | 373 |
374 |
375 | 376 |
377 |
378 |
example.com/kurdcity.jpg?autorotate=false
379 | 382 | 399 |
400 |
401 | 402 |
example.com/kurdcity.jpg?quality=5
403 | 406 | 423 |
424 |
425 | 426 |
427 |
428 |
example.com/kurdcity.jpg?quality=20
429 | 432 | 449 |
450 |
451 |
example.com/kurdcity.jpg?w=400&quality=80
452 | 455 | 472 |
473 |
474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | -------------------------------------------------------------------------------- /TestExample/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewData["Title"] = "Error"; 3 | } 4 | 5 |

Error.

6 |

An error occurred while processing your request.

7 | 8 |

Development Mode

9 |

10 | Swapping to Development environment will display more detailed information about the error that occurred. 11 |

12 |

13 | Development environment should not be enabled in deployed applications, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the ASPNETCORE_ENVIRONMENT environment variable to Development, and restarting the application. 14 |

15 | -------------------------------------------------------------------------------- /TestExample/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewData["Title"] - Web 7 | 8 | 9 | 10 | 11 | 12 | 13 | 23 |
24 | @RenderBody() 25 |
26 |
27 |

© 2019 - Keyvan Abdollahzadeh

30 |
31 |
32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 45 | 51 | 52 | 53 | 54 | @RenderSection("Scripts", required: false) 55 | 56 | 57 | -------------------------------------------------------------------------------- /TestExample/Views/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @using TestExample 2 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 3 | -------------------------------------------------------------------------------- /TestExample/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "_Layout"; 3 | } 4 | -------------------------------------------------------------------------------- /TestExample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /TestExample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /TestExample/libman.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0", 3 | "defaultProvider": "cdnjs", 4 | "libraries": [] 5 | } -------------------------------------------------------------------------------- /TestExample/output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/TestExample/output.jpg -------------------------------------------------------------------------------- /TestExample/wwwroot/ImageResizerJson.json: -------------------------------------------------------------------------------- 1 | { 2 | "WatermarkTextList": [ 3 | { 4 | "Key": 1, 5 | "Value": "Hello Word 1", 6 | "PositionMeasureType": 2, 7 | "X": 20, 8 | "Y": 20, 9 | "IsVerticalText": false, 10 | "Color": "#ff3838", 11 | "Type": 1, 12 | "StrokeWidth": "0", 13 | "Quality": 4, 14 | "TextSize": 25, 15 | "TextAlign": 3, 16 | "TextSkewX": 0, 17 | "IsAntialias": true 18 | }, 19 | { 20 | "Key": 3, 21 | "Value": "Hello Word 3", 22 | "PositionMeasureType": 2, 23 | "X": 20, 24 | "Y": 20, 25 | "IsVerticalText": true, 26 | "Color": "#ff3838", 27 | "Type": 1, 28 | "StrokeWidth": "0", 29 | "Quality": 4, 30 | "TextSize": 45, 31 | "TextAlign": 3, 32 | "TextSkewX": 1, 33 | "IsAntialias": true 34 | }, 35 | { 36 | "Key": 2, 37 | "Value": "Hello Word 2", 38 | "PositionMeasureType": 2, 39 | "X": 20, 40 | "Y": 20, 41 | "IsVerticalText": false, 42 | "Color": "#ff3838", 43 | "Type": 2, 44 | "StrokeWidth": "2", 45 | "Quality": 4, 46 | "TextSize": 45, 47 | "TextAlign": 3, 48 | "TextSkewX": 0, 49 | "IsAntialias": true 50 | }, 51 | 52 | { 53 | "Key": 4, 54 | "Value": "Hello Word 4", 55 | "PositionMeasureType": 2, 56 | "X": 20, 57 | "Y": 20, 58 | "IsVerticalText": true, 59 | "Color": "#ff3838", 60 | "Type": 3, 61 | "StrokeWidth": "2", 62 | "Quality": 4, 63 | "TextSize": 45, 64 | "TextAlign": 3, 65 | "TextSkewX": 0, 66 | "IsAntialias": true 67 | } 68 | ], 69 | "WatermarkImageList": [] 70 | } 71 | -------------------------------------------------------------------------------- /TestExample/wwwroot/images/kurdcity.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/TestExample/wwwroot/images/kurdcity.jpg -------------------------------------------------------------------------------- /TestExample/wwwroot/images/kurdcity1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/TestExample/wwwroot/images/kurdcity1.jpg -------------------------------------------------------------------------------- /TestExample/wwwroot/images/kurdcity2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/TestExample/wwwroot/images/kurdcity2.jpg -------------------------------------------------------------------------------- /TestExample/wwwroot/images/kurdcity3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keyone2693/ImageResizer.AspNetCore/8c4c9ffa15b92c691915b363bf451e835f17cda4/TestExample/wwwroot/images/kurdcity3.jpg --------------------------------------------------------------------------------