[ASP.NET] 即時產生縮圖

Standard

需求:傳入圖片網址,產生即時縮圖。

可依需求做在一隻檔案裡面,有需要就傳值給它去處理。 (這隻檔案的 ContentType 會是 image/Jpeg)

Import 下列 Namespace:

Imports System.Drawing
Imports System.Net
Imports System.IO
Imports System.Web

        ''' <summary>
        ''' 不儲存縮圖的即時繪製縮圖方法
        ''' </summary>
        ''' <param name="durl">圖檔網址</param>
        ''' <param name="w">寬</param>
        ''' <param name="h">高</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
    Public Function renderThumb(ByVal durl As String, ByVal w As Integer, ByVal h As Integer)

        Dim width, height As Integer

        Dim wc As WebClient = New WebClient()
        Dim ms As MemoryStream = New MemoryStream(wc.DownloadData(durl))
        Dim image As System.Drawing.Image = New Bitmap(ms)

        width = image.Width
        height = image.Height


        If Not (width < w And height < h) Then
            If width > height Then
                h = w * height / width
            Else
                w = h * width / height
            End If
        End If


        Dim img As System.Drawing.Bitmap = New System.Drawing.Bitmap(w, h)
        Dim graphic As Graphics = Graphics.FromImage(img)
        graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        graphic.DrawImage(image, 0, 0, w, h)

        image.Dispose()

        Dim ms_r As New System.IO.MemoryStream()
        img.Save(ms_r, System.Drawing.Imaging.ImageFormat.Jpeg)
        HttpContext.Current.Response.ClearContent()
        HttpContext.Current.Response.ContentType = "image/Jpeg"
        HttpContext.Current.Response.BinaryWrite(ms_r.ToArray())

        img.Dispose()
        graphic.Dispose()

    End Function

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *