2012年7月17日 星期二

ASP.NET 縮圖

記錄一下縮圖的語法:

  使用者上傳檔案時,我會先將檔案rename為xxxxxx_temp.jpg
  最後縮完圖後,再將新圖存成xxxxxx.jpg
  順便再刪除中介圖片xxxxxx_temp.jpg

   Imports System.Drawing

   Protected Sub ChangeSize(ByVal FilePath As String)
      Dim imgSource As Image = Image.FromFile(FilePath)
      Dim intFixLength As Integer = 750
      Dim intChangedWidth As Integer = 0
      Dim intChangedHeight As Integer = 0

      ' 設短邊為750px, 長邊等比例縮放
      With imgSource
         If .Width < .Height Then
            intChangedWidth = intFixLength
            intChangedHeight = .Height / .Width * intFixLength
         Else
            intChangedWidth = .Width / .Height * intFixLength
            intChangedHeight = intFixLength
         End If
      End With

      Dim bmpIntermediary As New Bitmap(intChangedWidth, intChangedHeight)
      Dim gphPainter As Graphics = Graphics.FromImage(bmpIntermediary)
      ' 圖片繪製品質
      gphPainter.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
      ' 圖片呈現品質
      gphPainter.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
      ' 圖片插補模式
      gphPainter.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBilinear
      ' 1:要繪製的圖片 2:起始x座標 3:起始y座標 4:寬度 5:高度
      gphPainter.DrawImage(imgSource, 0, 0, intChangedWidth, intChangedHeight)

      bmpIntermediary.Save(Replace(FilePath, "_temp.jpg", ".jpg"), Imaging.ImageFormat.Jpeg)

      bmpIntermediary.Dispose()
      gphPainter.Dispose()
      imgSource.Dispose()

      Dim fiSource As New FileInfo(FilePath)
      If fiSource.Exists Then
         fiSource.Delete()
      End If
   End Sub

這個語法還有一個好處
就是最後完成的圖片會是 RGB 格式的圖片
即使原始圖片是 CMYK 格式也一樣 (不知不覺中就轉檔了)

參考自工頭大大的BLOG [軟體工頭的分享BLOG]

沒有留言:

張貼留言