2015年7月4日 星期六

ASP.NET 即時產生縮圖

參考引用來源:[ASP.NET] 即時產生縮圖
--
需求:傳入圖片網址,產生即時縮圖。
可依需求做在一隻檔案裡面 .. 有需要就傳值給它去處理。 (這隻檔案 ContentType 會是 image/Jpeg)
需 Import 進下列 Namespace:
Imports System.Drawing
Imports System.Net
Imports System.IO
Imports System.Web

'''
    ''' 不儲存縮圖的即時繪製縮圖方法
    '''
    ''' 圖檔網址
    '''
    '''
    '''
    '''
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

沒有留言:

張貼留言