Skip to content

Instantly share code, notes, and snippets.

@jz5
Created May 11, 2015 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jz5/1a854f16f26fdefea799 to your computer and use it in GitHub Desktop.
Save jz5/1a854f16f26fdefea799 to your computer and use it in GitHub Desktop.
Imports System.Drawing
Imports System.Net
Imports Microsoft.ProjectOxford.Vision
Public Class ApiController
Inherits System.Web.Mvc.Controller
Async Function Index(url As String) As Threading.Tasks.Task(Of ActionResult)
If url Is Nothing Then
Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
End If
Dim result As Contract.AnalysisResult
Try
' API 呼び出し
Dim client = New VisionServiceClient("0b1ff4ab7a634bb0a6f7d532659f5d77")
If Uri.IsWellFormedUriString(url, UriKind.Absolute) Then
result = Await client.AnalyzeImageAsync(url)
Else
Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
End If
Catch cEx As ClientException
Return FileStream(url)
Catch ex As Exception
Return FileStream(url)
End Try
If result.Categories IsNot Nothing AndAlso result.Categories.Any AndAlso
result.Categories.First.Name.StartsWith("food_") Then ' 画像のカテゴリーが食べ物
' モザイク画像作成
Dim webClient = New WebClient
Dim inBmp = New Bitmap(webClient.OpenRead(url))
Dim tmpBmp = New Bitmap(inBmp.Width \ 10, inBmp.Height \ 10)
Dim outBmp = New Bitmap(inBmp.Width, inBmp.Height)
Using g = Graphics.FromImage(tmpBmp)
g.InterpolationMode = Drawing2D.InterpolationMode.NearestNeighbor
g.DrawImage(inBmp, 0, 0, tmpBmp.Width, tmpBmp.Height)
End Using
Using g = Graphics.FromImage(outBmp)
g.InterpolationMode = Drawing2D.InterpolationMode.NearestNeighbor
g.DrawImage(tmpBmp, 0, 0, outBmp.Width, outBmp.Height)
End Using
Response.ContentType = "image/png"
outBmp.Save(Response.OutputStream, Imaging.ImageFormat.Png)
Return New EmptyResult
Else
Return FileStream(url)
End If
End Function
Private Function FileStream(url As String) As ActionResult
Try
Dim req = HttpWebRequest.CreateHttp(url)
Dim res = DirectCast(req.GetResponse, HttpWebResponse)
Response.ContentType = res.ContentType
res.GetResponseStream.CopyTo(Response.OutputStream)
Catch ex As WebException
If ex.Status = System.Net.WebExceptionStatus.ProtocolError Then
Dim r = DirectCast(ex.Response, System.Net.HttpWebResponse)
Response.StatusCode = r.StatusCode
End If
End Try
Return New EmptyResult
End Function
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment