[VB.NET]壓縮圖檔

網頁上傳圖檔時可先經過壓縮處理,可省下相當大的磁碟空間,也可讓使用者瀏覽網站圖片時下載得更快

一般網頁上不需要放太高解析度的圖檔,網頁上傳圖檔時可先經過壓縮處理,可省下相當大的磁碟空間,也可讓使用者瀏覽網站圖檔時下載得更快,以下是一種壓縮圖檔的做法。

scaleFactor = 壓縮比,例0.1

sFileName = 來源完整檔案路徑

tFileName = 目標完整檔案路徑


Imports System.IO
Imports System.Drawing
Imports System.Drawing.Drawing2D

  Public Sub ResizeImageTool(ByRef scaleFactor As Double, ByRef sFileName As String, ByRef tFileName As String)
        If File.Exists(tFileName) Then
            File.Delete(tFileName)
        End If
        Dim sFileStream As FileStream = File.OpenRead(sFileName)
        Dim tFileStream As FileStream = File.Create(tFileName)
        ResizeImage(scaleFactor, sFileStream, tFileStream)
        sFileStream.Close()
        tFileStream.Close()
    End Sub
    Private Sub ResizeImage(ByRef scaleFactor As Double, ByRef fromStream As Stream, ByRef toStream As Stream)
        Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(fromStream)
        Dim newWidth As Integer = CType((image.Width * scaleFactor), Integer)
        Dim newHeight As Integer = CType((image.Height * scaleFactor), Integer)
        Dim thumbnailBitmap As Bitmap = New Bitmap(newWidth, newHeight)
        Dim thumbnailGraph As Graphics = Graphics.FromImage(thumbnailBitmap)
        thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality
        thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality
        thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic
        Dim imageRectangle As Rectangle = New Rectangle(0, 0, newWidth, newHeight)
        thumbnailGraph.DrawImage(image, imageRectangle)
        thumbnailBitmap.Save(toStream, image.RawFormat)
        thumbnailGraph.Dispose()
        thumbnailBitmap.Dispose()
        image.Dispose()
    End Sub