├── .gitattributes
├── .gitignore
├── Agent.cs
├── ContainerInfo.cs
├── ImageInfo.cs
├── ImageUtility.cs
├── N2ImageAgentGithub.csproj
├── N2ImageAgentGithub.sln
├── README.md
└── Utility.cs
/.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 |
--------------------------------------------------------------------------------
/.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 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/Agent.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 | using Octokit;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Drawing;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Text;
9 | using System.Threading;
10 |
11 | namespace N2ImageAgentGithub
12 | {
13 |
14 | public class Agent
15 | {
16 |
17 | private GitHubClient GithubClient;
18 |
19 |
20 | private Repository Repo { get; set; }
21 |
22 | public Agent(ContainerInfo containerInfo)
23 | {
24 | if (containerInfo == null)
25 | {
26 | throw new ArgumentNullException("containerInfo");
27 | }
28 |
29 | GithubClient = new GitHubClient(new ProductHeaderValue(containerInfo.ProductHeaderValue));
30 | var tokenAuth = new Credentials(containerInfo.GithubToken);
31 | GithubClient.Credentials = tokenAuth;
32 |
33 |
34 | Repo = GithubClient.Repository.Get(containerInfo.GithubName, containerInfo.RepoName).Result;
35 |
36 |
37 |
38 | }
39 |
40 | ///
41 | /// Get Image thumb url from Github
42 | /// if the file not existed I will copy from N2SOURCE/{id}.gif
43 | /// And make thumb file to N2_{w}x{h}/id.gif and return
44 | /// 取得縮圖的網址,如果沒有的話我會從 N2SOURCE/{id}.gif 來製作縮圖
45 | /// 放置 N2_{w}x{h}/id.gif 並且回傳網址
46 | ///
47 | /// 圖片編號
48 | /// 寬度 如果0 隨高度換算
49 | /// 高度 如果0 隨寬度換算
50 | ///
51 | public string GetImageThumbFromSource(string id, int w, int h)
52 | {
53 | if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id");
54 |
55 | RepositoryContent repoContent = GetFileRepositoryContent("N2SOURCE" + "/" + id + ".gif");
56 | if (repoContent == null) return null;
57 |
58 | if (w == 0 && h == 0)
59 | {
60 | return repoContent.DownloadUrl;
61 | }
62 |
63 | RepositoryContent repoContentThumb = GetFileRepositoryContent("N2_" + w + "x" + h + "/" + id + ".gif");
64 | if (repoContentThumb != null)
65 | {
66 | return repoContentThumb.DownloadUrl;
67 | }
68 |
69 | //Get Image From Source
70 | var bytes = Convert.FromBase64String(repoContent.EncodedContent);
71 | var sourceImage = Image.FromStream(new MemoryStream(bytes));
72 |
73 | var thumbHandler = new ImageUtility();
74 |
75 | Image source2 = null;
76 | //按照寬度,高度隨意
77 | if (w > 0 && h == 0)
78 | {
79 | source2 = thumbHandler.MakeThumbnail(sourceImage, w, h, "W");
80 |
81 | }
82 |
83 |
84 | ////按照高度,寬度隨意
85 | if (h > 0 && w == 0)
86 | {
87 | source2 = thumbHandler.MakeThumbnail(sourceImage, w, h, "H");
88 |
89 | }
90 |
91 | ////強制任性
92 | if (h > 0 && w > 0)
93 | {
94 | source2 = thumbHandler.MakeThumbnail(sourceImage, w, h, "WH");
95 |
96 | }
97 |
98 | var memStream = new MemoryStream();
99 | source2.Save(memStream, sourceImage.RawFormat);
100 | UpoloadImage(id, memStream.ToArray(), "upload by N2ImageAgent", "N2_" + w + "x" + h);
101 | sourceImage.Dispose();
102 | source2.Dispose();
103 |
104 | return GetFileRepositoryContent("N2_" + w + "x" + h + "/" + id + ".gif").DownloadUrl;
105 |
106 | }
107 |
108 |
109 |
110 | ///
111 | /// Is file existed.
112 | /// 是否檔案存在
113 | ///
114 | ///
115 | ///
116 | protected bool IsFileExisted(string pathFilename)
117 | {
118 | try
119 | {
120 | var res = GithubClient.Repository.Content.GetAllContents(Repo.Id, pathFilename).Result;
121 | if (res.Count > 0)
122 | {
123 | return true;
124 | }
125 | return false;
126 | }
127 | catch
128 | {
129 | return false;
130 | }
131 | }
132 |
133 |
134 | ///
135 | /// Is N2INFO/{id}.gif existed
136 | /// 是否 N2INFO/{id}.gif 存在
137 | ///
138 | ///
139 | ///
140 | public bool IsImageInfoExisted(string id)
141 | {
142 | return IsFileExisted("N2INFO" + "/" + id + ".json");
143 | }
144 |
145 |
146 | ///
147 | /// Is thumb existed in N2_{w}x{h}/{id}.gif or N2SOURCE/{id}.gif
148 | /// 是否縮圖存在於 N2_{w}x{h}/{id}.gif or N2SOURCE/{id}.gif
149 | ///
150 | ///
151 | ///
152 | ///
153 | ///
154 | public bool IsImageThumbExisted(string id, int w, int h)
155 | {
156 | if (w == 0 && h == 0)
157 | {
158 | return IsFileExisted("N2SOURCE" + "/" + id + ".gif");
159 | }
160 | return IsFileExisted("N2_" + w + "x" + h + "/" + id + ".gif");
161 | }
162 |
163 |
164 | ///
165 | /// Upload Image info
166 | /// 上傳圖片資訊
167 | ///
168 | ///
169 | ///
170 | public void UpoloadImageInfo(ImageInfo imageInfo, string message)
171 | {
172 |
173 | if (imageInfo == null) throw new ArgumentNullException("imageInfo");
174 |
175 |
176 |
177 | DeleteImageInfo(imageInfo.Id);
178 |
179 | var updateRequest = new UpdateFileRequest(message, JsonConvert.SerializeObject(imageInfo), "SHA", true);
180 |
181 | var res = GithubClient.Repository.Content.UpdateFile(Repo.Id, "N2INFO" + "/" + imageInfo.Id + ".json", updateRequest).Result;
182 |
183 | }
184 |
185 |
186 | ///
187 | /// Upload image to N2SOURCE/{id}.gif
188 | /// 上傳圖片至 N2SOURCE/{id}.gif
189 | ///
190 | /// 圖片編號
191 | /// 本地圖片位置
192 | /// comment
193 | public void UpoloadImageToSource(string id, string localImagePath, string message)
194 | {
195 | if (string.IsNullOrEmpty(localImagePath)) throw new ArgumentNullException("localImagePath");
196 | if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id");
197 |
198 | if (!File.Exists(localImagePath))
199 | {
200 | throw new FileNotFoundException("local image not found.");
201 | }
202 |
203 | DeleteSource(id);
204 |
205 | var updateRequest = new UpdateFileRequest(message, Convert.ToBase64String(File.ReadAllBytes(localImagePath)), "SHA", false);
206 |
207 | var res = GithubClient.Repository.Content.UpdateFile(Repo.Id, "N2SOURCE" + "/" + id + ".gif", updateRequest).Result;
208 |
209 | }
210 |
211 | ///
212 | /// Upload image to N2SOURCE/{id}.gif
213 | /// 上傳圖片至 N2SOURCE/{id}.gif
214 | ///
215 | ///
216 | ///
217 | ///
218 | public void UpoloadImageToSource(string id, byte[] imageBytes, string message)
219 | {
220 |
221 | if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id");
222 | if (imageBytes == null) throw new ArgumentNullException("imageBytes");
223 |
224 | DeleteSource(id);
225 | var updateRequest = new UpdateFileRequest(message, Convert.ToBase64String(imageBytes), "SHA", false);
226 |
227 | var res = GithubClient.Repository.Content.UpdateFile(Repo.Id, "N2SOURCE" + "/" + id + ".gif", updateRequest).Result;
228 |
229 | }
230 |
231 |
232 | private void UpoloadImage(string id, byte[] imageBytes, string message, string path)
233 | {
234 |
235 | if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id");
236 | if (imageBytes == null) throw new ArgumentNullException("imageBytes");
237 |
238 | DeleteFile(path + "/" + id + ".gif");
239 | var updateRequest = new UpdateFileRequest(message, Convert.ToBase64String(imageBytes), "SHA", false);
240 | var res = GithubClient.Repository.Content.UpdateFile(Repo.Id, path + "/" + id + ".gif", updateRequest).Result;
241 |
242 | }
243 |
244 | ///
245 | /// Is Source Image existed in N2SOURCE/{id}.gif
246 | ///
247 | ///
248 | ///
249 | ///
250 | public bool IsSourceExisted(string id)
251 | {
252 | return IsImageInfoExisted("N2SOURCE" + "/" + id + ".gif");
253 | }
254 |
255 | ///
256 | /// Get Path RepositoryContent
257 | ///
258 | ///
259 | ///
260 | private RepositoryContent GetFileRepositoryContent(string filepath)
261 | {
262 | try
263 | {
264 | var res = GithubClient.Repository.Content.GetAllContents(Repo.Id, filepath).Result;
265 | if (res.Count > 0)
266 | {
267 | return res[0];
268 | }
269 | return null;
270 | }
271 | catch
272 | {
273 | return null;
274 | }
275 | }
276 |
277 | ///
278 | /// Get Source Image RepositoryContent
279 | ///
280 | ///
281 | ///
282 | private RepositoryContent GetSourceRepositoryContent(string id)
283 | {
284 | try
285 | {
286 | var res = GithubClient.Repository.Content.GetAllContents(Repo.Id, "N2SOURCE" + "/" + id + ".gif").Result;
287 | if (res.Count > 0)
288 | {
289 | return res[0];
290 | }
291 | return null;
292 | }
293 | catch
294 | {
295 | return null;
296 | }
297 | }
298 |
299 | ///
300 | /// Delete File
301 | ///
302 | ///
303 | public async void DeleteFile(string pathfile)
304 | {
305 | try
306 | {
307 | var res = GithubClient.Repository.Content.GetAllContents(Repo.Id, pathfile).Result;
308 | if (res.Count > 0)
309 | {
310 | await GithubClient.Repository.Content.DeleteFile(Repo.Id, pathfile, new DeleteFileRequest("delete file", res[0].Sha));
311 |
312 | }
313 |
314 | }
315 | catch (Exception ex)
316 | {
317 |
318 | }
319 | }
320 |
321 | ///
322 | /// Delete Image Info from N2INFO/{id}.json
323 | ///
324 | ///
325 | public async void DeleteImageInfo(string id)
326 | {
327 | try
328 | {
329 | var res = GithubClient.Repository.Content.GetAllContents(Repo.Id, "N2INFO" + "/" + id + ".json").Result;
330 | if (res.Count > 0)
331 | {
332 | await GithubClient.Repository.Content.DeleteFile(Repo.Id, "N2INFO/" + id + ".json", new DeleteFileRequest("delete file", res[0].Sha));
333 |
334 | }
335 |
336 | }
337 | catch
338 | {
339 |
340 | }
341 | }
342 |
343 | ///
344 | /// Delete Source from N2SOURCE/{id}.gif
345 | ///
346 | ///
347 | public async void DeleteSource(string id)
348 | {
349 |
350 | var res = GetSourceRepositoryContent(id);
351 | if (res != null)
352 | {
353 | await GithubClient.Repository.Content.DeleteFile(Repo.Id, "N2SOURCE/" + id + ".gif", new DeleteFileRequest("delete file", res.Sha));
354 |
355 | }
356 |
357 | }
358 |
359 |
360 | ///
361 | /// Delete All Image Thumb from all Sizes.
362 | /// 刪除所有某id 的縮圖,預設 delay 1000 , 是因為刪得太快速他會莫名的不成功
363 | ///
364 | ///
365 | /// call fast will be fail. unit is milliseconds
366 | public void DeleteAllImageById(string id, int delay = 1000)
367 | {
368 | var res = GithubClient.Repository.Content.GetAllContents(Repo.Id, "/").Result;
369 | if (res.Count > 0)
370 | {
371 | foreach (var r in res)
372 | {
373 | if (r.Type.Value == ContentType.Dir)
374 | {
375 | if (r.Name.StartsWith("N2_"))
376 | {
377 | try
378 | {
379 | GithubClient.Repository.Content.DeleteFile(Repo.Id, r.Name + "/" + id + ".gif", new DeleteFileRequest("delete file", GithubClient.Repository.Content.GetAllContents(Repo.Id, r.Name + "/" + id + ".gif").Result[0].Sha));
380 | Thread.Sleep(delay);
381 | }
382 |
383 | catch (Exception ex)
384 | {
385 | Thread.Sleep(delay);
386 | continue;
387 | }
388 | }
389 |
390 | }
391 | }
392 | }
393 | GC.Collect();
394 | }
395 |
396 | }
397 | }
398 |
--------------------------------------------------------------------------------
/ContainerInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace N2ImageAgentGithub
4 | {
5 | public class ContainerInfo
6 | {
7 |
8 |
9 | ///
10 | /// Github Token
11 | /// Create from : https://github.com/settings/tokens
12 | ///
13 | public string GithubToken { get; set; }
14 |
15 |
16 | ///
17 | /// Your Github UserName
18 | ///
19 | public string GithubName { get; set; }
20 |
21 |
22 | ///
23 | /// Repository Name
24 | ///
25 | public string RepoName { get; set; }
26 |
27 | ///
28 | /// Anychars
29 | ///
30 | public string ProductHeaderValue { get; set; }
31 |
32 | ///
33 | /// Ctor
34 | ///
35 | /// Github Token
36 | /// Your Github UserName
37 | /// Repository Name
38 | /// Anychars
39 | public ContainerInfo(string githubToken, string githubName, string repoName,string productHeadre="N2ImageAgent")
40 | {
41 | if (string.IsNullOrEmpty(githubToken)) throw new ArgumentNullException("githubToken");
42 | if (string.IsNullOrEmpty(githubName)) throw new ArgumentNullException("githubName");
43 | if (string.IsNullOrEmpty(repoName)) throw new ArgumentNullException("repoName");
44 | if (string.IsNullOrEmpty(productHeadre)) throw new ArgumentNullException("productHeadre");
45 | GithubToken = githubToken;
46 | GithubName = githubName;
47 | RepoName = repoName;
48 | ProductHeaderValue = productHeadre;
49 | }
50 |
51 |
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/ImageInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace N2ImageAgentGithub
6 | {
7 | public class ImageBlobResult
8 | {
9 | public string Url { get; set; }
10 | public string Para { get; set; }
11 |
12 | public DateTime ExpireTime { get; set; }
13 |
14 | public string FullUrl
15 | {
16 | get
17 | {
18 | return Url + Para;
19 | }
20 | }
21 | }
22 | public class ImageInfo
23 | {
24 | public string Id { set; get; }
25 | public int Width { set; get; }
26 | public int Height { set; get; }
27 | public string Extension { set; get; }
28 | public string Tag { get; set; }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/ImageUtility.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Drawing;
3 | using System.Drawing.Imaging;
4 | using System.IO;
5 | using System.Linq;
6 | namespace N2ImageAgentGithub
7 | {
8 | public class ImageUtility
9 | {
10 | #region 產生縮圖
11 | ///
12 | /// 產生縮圖
13 | ///
14 | /// 圖片物件
15 | /// 縮圖寬度
16 | /// 縮圖高度
17 | /// 縮圖模式
18 | /// 縮圖後的圖片物件
19 | public Image MakeThumbnail(Image img, int width, int height, string mode)
20 | {
21 | int towidth = width;
22 | int toheight = height;
23 |
24 | int x = 0;
25 | int y = 0;
26 | int ow = img.Width;
27 | int oh = img.Height;
28 |
29 | switch (mode)
30 | {
31 | case "HW"://指定高寬縮放(可能變形)
32 | break;
33 | case "W"://指定寬,高按比例
34 | toheight = img.Height * width / img.Width;
35 | break;
36 | case "H"://指定高,寬按比例
37 | towidth = img.Width * height / img.Height;
38 | break;
39 | case "Cut"://指定高寬裁減(不變形)
40 | if ((double)img.Width / (double)img.Height > (double)towidth / (double)toheight)
41 | {
42 | oh = img.Height;
43 | ow = img.Height * towidth / toheight;
44 | y = 0;
45 | x = (img.Width - ow) / 2;
46 | }
47 | else
48 | {
49 | ow = img.Width;
50 | oh = img.Width * height / towidth;
51 | x = 0;
52 | y = (img.Height - oh) / 2;
53 | }
54 | break;
55 | default:
56 | break;
57 | }
58 |
59 |
60 | Bitmap bitmap = new Bitmap(towidth, toheight);
61 | using (Graphics grphs = Graphics.FromImage(bitmap))
62 | {
63 | grphs.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
64 |
65 | grphs.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
66 |
67 | grphs.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
68 |
69 | //grphs.DrawImage(img, 0, 0, bitmap.Width, bitmap.Height);
70 | grphs.DrawImage(img, new Rectangle(0, 0, towidth, toheight),
71 | new Rectangle(x, y, ow, oh),
72 | GraphicsUnit.Pixel);
73 | }
74 | return bitmap;
75 | }
76 | #endregion
77 |
78 | #region 產生jpg圖
79 | ///
80 | /// 產生jpg圖
81 | ///
82 | /// 圖片物件
83 | /// JPG圖片物件
84 | public Image MakeJpgImage(Image img)
85 | {
86 | int towidth = img.Width;
87 | int toheight = img.Height;
88 |
89 | int x = 0;
90 | int y = 0;
91 |
92 | Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
93 |
94 | Graphics g = System.Drawing.Graphics.FromImage(bitmap);
95 |
96 | g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
97 | g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
98 |
99 | g.Clear(Color.White);
100 |
101 | g.DrawImage(img, new Rectangle(0, 0, towidth, toheight),
102 | new Rectangle(x, y, towidth, toheight),
103 | GraphicsUnit.Pixel);
104 | img.Dispose();
105 | g.Dispose();
106 | return bitmap;
107 | }
108 | #endregion
109 |
110 | #region 儲存縮圖
111 | ///
112 | /// 儲存縮圖
113 | ///
114 | /// 圖片物件
115 | /// 儲存路徑
116 | public void ImageSaveFile(Image img, string imgpath, string picxet)
117 | {
118 | try
119 | {
120 |
121 |
122 | EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
123 |
124 | //Magic Code .開到三檔變成高畫質
125 | var encoderParams = new EncoderParameters(1);
126 |
127 | encoderParams.Param[0] = qualityParam;
128 |
129 | if (picxet.ToLower() == "gif")
130 | {
131 | string lookupKey = "image/gif";
132 | var jpegCodec = ImageCodecInfo.GetImageEncoders().Where(i => i.MimeType.Equals(lookupKey)).FirstOrDefault();
133 |
134 | //以Gif格式保存縮略圖
135 | img.Save(imgpath, jpegCodec, encoderParams);
136 | }
137 | if (picxet.ToLower() == "jpg" || picxet.ToLower() == "jpeg")
138 | {
139 | string lookupKey = "image/jpeg";
140 | var jpegCodec = ImageCodecInfo.GetImageEncoders().Where(i => i.MimeType.Equals(lookupKey)).FirstOrDefault();
141 |
142 | //以Jpg格式保存縮略圖
143 | img.Save(imgpath, jpegCodec, encoderParams);
144 | }
145 | if (picxet.ToLower() == "png")
146 | {
147 | string lookupKey = "image/png";
148 | var jpegCodec = ImageCodecInfo.GetImageEncoders().Where(i => i.MimeType.Equals(lookupKey)).FirstOrDefault();
149 |
150 | //以Gif格式保存縮略圖
151 | img.Save(imgpath, jpegCodec, encoderParams);
152 | }
153 | }
154 | catch (System.Exception ex)
155 | {
156 | System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "errorlog");
157 | File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "errorlog" + Path.DirectorySeparatorChar + "[ImageThumber]" + DateTime.Now.ToString("yyyyMMdd hhmmss"), ex.Message + "\r\n" + ex.StackTrace);
158 | }
159 | finally
160 | {
161 | img.Dispose();
162 | }
163 | }
164 | #endregion
165 |
166 |
167 | #region 判斷縮圖模式
168 | ///
169 | /// 判斷縮圖模式
170 | ///
171 | /// 圖片物件
172 | /// 模式
173 | public string DecisionThumbMode(Image img)
174 | {
175 | try
176 | {
177 | string mode = "";
178 | if (img.Width > img.Height)
179 | {
180 | mode = "W";
181 | }
182 | else if (img.Width < img.Height)
183 | {
184 | mode = "H";
185 | }
186 | else
187 | {
188 | mode = "Cut";
189 | }
190 | return mode;
191 | }
192 | catch (Exception ex)
193 | {
194 | System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "errorlog");
195 | File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "errorlog" + Path.DirectorySeparatorChar + "[ImageThumber]" + DateTime.Now.ToString("yyyyMMdd hhmmss"), ex.Message + "\r\n" + ex.StackTrace);
196 | return "";
197 | }
198 | }
199 | #endregion
200 |
201 | public Image MakeMerge(Image img1, Image img2, int width, int height, string mode)
202 | {
203 | int towidth = width;
204 | int toheight = img1.Height + img2.Height;
205 |
206 | int x = 0;
207 | int y = 0;
208 | int ow = img1.Width;
209 | int oh = img1.Height;
210 | int sw = img2.Width;
211 | int sh = img2.Height;
212 |
213 | switch (mode)
214 | {
215 | case "HW"://指定高寬縮放(可能變形)
216 | break;
217 | case "W"://指定寬,高按比例
218 | toheight = img1.Height * width / img1.Width;
219 | break;
220 | case "H"://指定高,寬按比例
221 | towidth = img1.Width * height / img1.Height;
222 | break;
223 | case "Cut"://指定高寬裁減(不變形)
224 | if ((double)img1.Width / (double)img1.Height > (double)towidth / (double)toheight)
225 | {
226 | oh = img1.Height;
227 | ow = img1.Height * towidth / toheight;
228 | y = 0;
229 | x = (img1.Width - ow) / 2;
230 | }
231 | else
232 | {
233 | ow = img1.Width;
234 | oh = img1.Width * height / towidth;
235 | x = 0;
236 | y = (img1.Height - oh) / 2;
237 | }
238 | break;
239 | default:
240 | break;
241 | }
242 |
243 | //新建一個bmp圖片
244 | Image bitmap = new System.Drawing.Bitmap(towidth, toheight + img2.Height);
245 |
246 | //新建一個畫板
247 | Graphics g = System.Drawing.Graphics.FromImage(bitmap);
248 |
249 | //設定高品質插值法
250 | g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
251 |
252 | //設定高品質,低速度呈現平滑程度
253 | g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
254 |
255 | //清空畫布並以透明背景色填充
256 | g.Clear(Color.Empty);
257 |
258 | //在指定位置並且按指定大小繪制原圖片的指定部分
259 | g.DrawImage(img1, new Rectangle(0, 0, towidth, toheight),
260 | new Rectangle(x, y, ow, oh),
261 | GraphicsUnit.Pixel);
262 | g.DrawImage(img2, new Rectangle(0, toheight, towidth, sh),
263 | new Rectangle(x, y, sw, sh),
264 | GraphicsUnit.Pixel);
265 |
266 | img1.Dispose();
267 | img2.Dispose();
268 | g.Dispose();
269 | return bitmap;
270 | }
271 |
272 | ///
273 | /// 自動判斷圖片格式
274 | ///
275 | ///
276 | ///
277 | public static System.Drawing.Imaging.ImageFormat GetImageFormat(System.Drawing.Image img)
278 | {
279 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
280 | return System.Drawing.Imaging.ImageFormat.Jpeg;
281 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp))
282 | return System.Drawing.Imaging.ImageFormat.Bmp;
283 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
284 | return System.Drawing.Imaging.ImageFormat.Png;
285 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Emf))
286 | return System.Drawing.Imaging.ImageFormat.Emf;
287 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Exif))
288 | return System.Drawing.Imaging.ImageFormat.Exif;
289 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
290 | return System.Drawing.Imaging.ImageFormat.Gif;
291 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Icon))
292 | return System.Drawing.Imaging.ImageFormat.Icon;
293 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.MemoryBmp))
294 | return System.Drawing.Imaging.ImageFormat.MemoryBmp;
295 | if (img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Tiff))
296 | return System.Drawing.Imaging.ImageFormat.Tiff;
297 | else
298 | return System.Drawing.Imaging.ImageFormat.Wmf;
299 | }
300 | }
301 | }
302 |
--------------------------------------------------------------------------------
/N2ImageAgentGithub.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/N2ImageAgentGithub.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29519.181
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "N2ImageAgentGithub", "N2ImageAgentGithub.csproj", "{D84011AD-0525-40C0-B363-7316ABD5FC97}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {D84011AD-0525-40C0-B363-7316ABD5FC97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {D84011AD-0525-40C0-B363-7316ABD5FC97}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {D84011AD-0525-40C0-B363-7316ABD5FC97}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {D84011AD-0525-40C0-B363-7316ABD5FC97}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {44017729-5E8C-4CD1-B470-C7021467D735}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ImageHelper base on Github
2 |
3 | Tutorial
4 | ----
5 |
6 | 一套 library 可以讓你無 server 配合 Github 做出一套 Image Service ,簡單說就可以把 github 當圖床用?,因為這是 library 版本 ,如果你是想要直接使用 Server 版本,你可以到這裡 https://github.com/donma/N2ImageAgent.AzureBlob2020 ,使用 Azure 版本,除非我找時間來寫 sever 版本 base on Github 。 這套 library 製作出來的 repo 會長這樣 https://github.com/gitozhack/imgstock1 ,如果有幫助就幫我 star 一下了,感恩。
7 |
8 | Happy Coding :)
9 |
10 | Document
11 | ----
12 |
13 | #### Init Github ContainerInfo
14 | ```C#
15 |
16 | //your_github_token get from : https://github.com/settings/tokens
17 | var containerInfo = new N2ImageAgentGithub.ContainerInfo("your_github_token", "your_username", "yout_reponame");
18 |
19 | var agent = new N2ImageAgentGithub.Agent(containerInfo);
20 |
21 | ```
22 |
23 | #### Upload Image From Local File.
24 | ```C#
25 | Console.WriteLine("Upload Image To Source");
26 | agent.UpoloadImageToSource("imageid", AppDomain.CurrentDomain.BaseDirectory + "sample1.jpg", "test upload image source");
27 |
28 | ```
29 |
30 | #### Upload Image From File Byte[]
31 |
32 | ```C#
33 | Console.WriteLine("Upload Image To Source from byte[]");
34 | agent.UpoloadImageToSource("imageid", File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "sample1.jpg"), "測試上傳:"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
35 |
36 | ```
37 |
38 | #### Get Image Info By Utility and Upload Info
39 |
40 | ```C#
41 | Console.WriteLine("Get Image Info And Upload");
42 | var info = Utility.GetImageInfo(AppDomain.CurrentDomain.BaseDirectory + "sample1.jpg", "imageid", "taginfo");
43 | Console.WriteLine(JsonConvert.SerializeObject(info));
44 | agent.UpoloadImageInfo(info, "測試上傳:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
45 |
46 | ```
47 |
48 | #### Delete Image Info And Source By Id
49 |
50 | ```C#
51 | Console.WriteLine("Delete Source and Info");
52 | agent.DeleteSource("imageid");
53 | agent.DeleteImageInfo("imageid");
54 | ```
55 |
56 | #### Delete All Thumb By Id
57 |
58 | ```C#
59 | Console.WriteLine("Delete All Thumb");
60 | agent.DeleteAllImageById("imageid",1000);
61 |
62 | ```
63 |
64 | #### Is Image Source Exist
65 |
66 | ```C#
67 | Console.WriteLine("Check image in Source");
68 | agent.IsSourceExisted("imageid");
69 |
70 | ```
71 |
72 | #### Is Image Info Exist
73 |
74 | ```C#
75 |
76 | Console.WriteLine("Check image info is existed");
77 | agent.IsImageInfoExisted("imageid");
78 |
79 | ```
80 |
81 | #### Is Image Thumb Exist
82 |
83 | ```C#
84 | Console.WriteLine("Check image info is existed");
85 | agent.IsImageThumbExisted("imageid");
86 |
87 | ```
88 |
89 | #### Get Image source or thumb url from Github
90 |
91 | ```C#
92 | //source
93 | var source_url = agent.GetImageThumbFromSource("imageid", 0, 0);
94 | Console.WriteLine(source_url);
95 | //thumb1 : get width 100 and height depend on width.
96 | var thumb1 = agent.GetImageThumbFromSource("imageid", 100, 0);
97 | Console.WriteLine(thumb1);
98 | //thumb2 : get height 200 and width depend on height.
99 | var thumb2 = agent.GetImageThumbFromSource("imageid", 0, 200);
100 | Console.WriteLine(thumb2);
101 |
102 |
103 | ```
104 |
105 |
106 |
--------------------------------------------------------------------------------
/Utility.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Drawing;
4 | using System.Text;
5 |
6 | namespace N2ImageAgentGithub
7 | {
8 | public class Utility
9 | {
10 |
11 | ///
12 | /// Get Image Info from File.
13 | ///
14 | ///
15 | ///
16 | ///
17 | ///
18 | public static ImageInfo GetImageInfo(string localImagePath, string id, string tag)
19 | {
20 | if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("id");
21 | if (string.IsNullOrEmpty(localImagePath)) throw new ArgumentNullException("localImagePath");
22 | var source = Image.FromFile(localImagePath);
23 |
24 | var imgInfo = new ImageInfo();
25 | imgInfo.Id = id;
26 | imgInfo.Width = source.Width;
27 | imgInfo.Height = source.Height;
28 | imgInfo.Extension = ImageUtility.GetImageFormat(source).ToString().ToLower();
29 | imgInfo.Tag = tag;
30 |
31 | return imgInfo;
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------