關於朱泰銓-個人資料



[ASP.NET]上傳圖片後進行等比例縮圖(Zoom)

一樣,最近作專案有用到

用途是於上傳圖片的同時進行縮圖處理

如此日後可以減少圖片下載時所需的頻寬(因為圖檔被縮小了)

也可以強制圖片必須為長寬多少內~(若使用者本身不懂縮圖,這個函數會自動幫忙處理)

 

分享一下原始碼跟方法

‘原始碼開始

 

  ’縮圖


    Sub imgresize(ByVal width As Integer, ByVal height As Integer, ByVal saveurl As String, ByVal filebytes As Byte(), ByVal filelength As Integer)


        Dim ms As MemoryStream = New MemoryStream

        ms.Write(filebytes, 0, filelength)

        ms.Flush()

        Dim img1 As System.Drawing.Image = System.Drawing.Image.FromStream(ms)

        If img1.Height > height Or img1.Width > width Then

            ’是否有超高or寬

            Dim newimg As System.Drawing.Image

            Dim thumbnailScale As Integer() = getThumbnailImageScale(width, height, img1.Width, img1.Height)

            ’算出原圖長寬比

            newimg = img1.GetThumbnailImage(thumbnailScale(0), thumbnailScale(1), Nothing, IntPtr.Zero)

            ’釋放資源

            newimg.Save(saveurl)

            newimg.Dispose()

            img1.Dispose()

            ms.Close()

        End If


    End Sub


    Function getThumbnailImageScale(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal oldWidth As Integer, ByVal oldHeight As Integer) As Integer()

        Dim result() As Integer = New Integer() {0, 0}

        Dim widthDividend As Single, heightDividend As Single, commonDividend As Single

        widthDividend = oldWidth / maxWidth

        heightDividend = oldHeight / maxHeight

        If (heightDividend > widthDividend) Then

            commonDividend = heightDividend

        Else

            commonDividend = widthDividend

        End If

        result(0) = CType((oldWidth / commonDividend), Integer)

        result(1) = CType((oldHeight / commonDividend), Integer)

        Return result

    End Function

 

‘原始碼結束

5 comments to [ASP.NET]上傳圖片後進行等比例縮圖(Zoom)

  • Peter Lin

    您好,最近我在研究上傳圖片自動縮圖的問題,看到您的分享程式碼,真的很棒。
    想請教,一般看到的處理方式都是用暫存檔,您是用記憶體來處理,這個部分如果碰到太大的原始圖片(5MB以上的JPG),會不會造成伺服器記憶體資源不足的問題?
    另外,關於imgresize函式參數裡的filebytes,filelength,請問是要帶入甚麼值?
    width 圖片寬度、height 圖片高度、saveurl 存檔位址,這三項我還看得懂,就是後面兩項百思不得其解,在 ms.Write(filebytes, 0, filelength)這邊您做了寫入位元組區塊至目前的資料流的動作,所以我必須把原圖的檔案大小算出來帶入嗎?
    很抱歉問這麼多問題,因為我不想只是單純的COPY程式碼來用,我希望能真正的從高手的程式碼中學到東西,還請多多包涵。

    • Lansea.chu

      >>如果碰到太大的原始圖片
      一般Server的記憶體應該沒那麼少吧..
      而且縮完圖就會釋放掉了~
      發生的機率應該不大,
      就算記憶體吃完理應也會塞到分頁去排..

      那兩個參數帶入fileupload控制項的值就可以
      例如: FileUpload1.FileBytes, FileUpload1.FileBytes.Length

  • Lansea.chu

    抱歉那麼晚回覆您(我在放年假啦 哈哈)

  • Peter Lin

    感謝您的回覆,我後來有試過getThumbnailImageScale做出來的所圖品質很糟,因為我要縮的原圖都是3000多像素以上的數位相機照片,所以就改用System.Drawing的方式來處理了,雖然要多等個幾秒,但是縮圖的品質就比getThumbnailImageScale好。

  • pingpong1023

    真正要做到高品質的縮圖程式,這篇文章可以參考一下:http://goo.gl/UwsF

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>