影像處理(Image)

  • 匯入命名空間
    <%@Import Namespace="System.Drawing.Imaging" %>

  • 變換影像物件儲存類型(如 .bmp → .gif)

'refer to: http://aspnet.4guysfromrolla.com/articles/012203-1.aspx


' 擷取影像檔存入影像物件

Dim fullSizeImg As System.Drawing.Image
fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath("~/images/MyPic.bmp"))

' 變換影像物件儲存類型
Response.ContentType = "image/gif"        ' "image/jpeg" for .jpg
fullSizeImg.Save(Response.OutputStream, ImageFormat.Gif)
fullSizeImg.Save(Server.MapPath("~/images/New.gif"))

' 將影像物件顯示於網頁
fullSizeImg.Dispose()

  • 變更影像大小

'refer to: http://aspnet.4guysfromrolla.com/articles/012203-1.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
'Read in the image filename to create a thumbnail of
Dim imageUrl As String = "MyPicture.jpg" 'Request.QueryString("img")

'Make sure that the image URL doesn't contain any /'s or \'s
If imageUrl.IndexOf("/") >= 0 Or imageUrl.IndexOf("\") >= 0 Then
'We found a / or \
Response.End()
End If

'Add on the appropriate directory
imageUrl = "~/images/" & imageUrl

'Get the image.
' 擷取影像檔存入影像物件
Dim fullSizeImg As System.Drawing.Image
fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(imageUrl))

'New image
' 宣告新影像物件
Dim thumbNailImg As System.Drawing.Image

' 不知所為為何,但這是一定要的!
Dim dummyCallBack As System.Drawing.Image.GetThumbnailImageAbort
dummyCallBack = New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbNailCallBack)

Dim imageHeight As Integer = fullSizeImg.Height
Dim imageWidth As Integer = fullSizeImg.Width

' Convert to 200 x 200
' 變更大小為 200 x 200,維持長寬比()
Dim resizedHeight, resizedWidth As Integer
If imageHeight > imageWidth Then
resizedHeight = 200
resizedWidth = 200 * imageWidth / imageHeight
Else
resizedWidth = 200
resizedHeight = 200 * imageHeight / imageWidth
End If
thumbNailImg = fullSizeImg.GetThumbnailImage(resizedWidth, resizedHeight, dummyCallBack, IntPtr.Zero)

'Set the ContentType to "image/jpg" and output the image's data
Response.ContentType = "image/jpeg"
' 依指定類型存入影像物件
thumbNailImg.Save(Response.OutputStream, ImageFormat.Jpeg)
' 存檔
thumbNailImg.Save(Server.MapPath("~/images/resized.jpg"))

'Dispose/clean up...
' 將影像物件顯示於網頁
thumbNailImg.Dispose()
End Sub

Function ThumbNailCallBack() As Boolean
' 不知所為為何,但這是一定要的!
Return False
End Function

 

相關參考:

 

 

r李明山 如意網站 ASP.NET 教學網