You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET图片上传器优化:改进压缩与尺寸缩减功能

ASP.NET图片上传压缩代码优化方案

问题说明

我使用Classic ASP,但现有一款ASP.NET上传器,它能对大文件进行图片压缩并调整至可用尺寸,但部分情况下处理后的图片体积会大于原文件。由于不了解.NET技术,无法自行调整,恳请优化代码提升效率。

原代码

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim strFileName As String = String.Format("Photo{0}.jpg", hdnAgentID.value)
        If fupPhoto.HasFile Then
            Try
                If fupPhoto.PostedFile.ContentLength <= 10000000 Then
                    fupPhoto.SaveAs("M:\my path\" & strFileName)
                    resizeImage("M:\my path & strFileName)
                End If
            Catch ex As Exception
                lblAlert.Text = "ERROR: " & ex.ToString()
            End Try
            hdnPhotoURL.Value = String.Format(https://websiteaddress/uploads/{0}, strFileName)
        End If
        
        strFileName = String.Format("Logo{0}.jpg", hdnAgentID.Value)
        If fupLogo.HasFile Then
            Try
                If fupLogo.PostedFile.ContentLength <= 10000000 Then
                    fupLogo.SaveAs("M:\my path\" & strFileName)
                   resizeImage("M:\my path\" & strFileName)
                End If
    
            Catch ex As Exception
                lblAlert.Text = "ERROR: " & ex.ToString()
            End Try
            hdnLogoURL.Value = String.Format(https://websiteaddress/uploads/{0}, strFileName)
        End If

        
        'Update UI and Create JS to populate the fields on memberpage.asp
      pnlMain.Visible = true
      litJS.visible = true
    End Sub
    

    Private Sub resizeImage(ByVal location As String)
             ' Get the source bitmap.
             Dim bm_source As Bitmap = system.drawing.image.fromfile(location)
        
            If bm_source.Width > 450 Then
                Dim PercentageScaleWidth As Decimal = 450 / bm_source.Width
            
                ' Make a bitmap for the result.
                Dim bm_dest As New Bitmap( _
                    CInt(bm_source.Width * PercentageScaleWidth), _
                    CInt(bm_source.Height * PercentageScaleWidth))

                ' Make a Graphics object for the result Bitmap.
                Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

                ' Copy the source image into the destination bitmap.
                gr_dest.DrawImage(bm_source, 0, 0, _
                    bm_dest.Width + 1, _
                    bm_dest.Height + 1)

                ' Save the result.
                bm_source.Dispose()
                bm_source = Nothing

                Threading.Thread.Sleep(1000)
            
                bm_dest.Save(location)
                bm_dest.Dispose()
                bm_dest = Nothing
    
                gr_dest.Dispose()
                gr_dest = Nothing
            else
            
                bm_source.Dispose()
                bm_source = Nothing
            
            End If
              

    End Sub

优化后的代码

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim savePath As String = "M:\my path\"
    Dim webPath As String = "https://websiteaddress/uploads/{0}"
    
    ' 处理照片上传
    Dim photoFileName As String = String.Format("Photo{0}.jpg", hdnAgentID.Value)
    If fupPhoto.HasFile Then
        Try
            If fupPhoto.PostedFile.ContentLength <= 10000000 Then
                Dim fullPhotoPath As String = Path.Combine(savePath, photoFileName)
                fupPhoto.SaveAs(fullPhotoPath)
                OptimizeImage(fullPhotoPath, 450, 85) ' 85为JPEG质量,可根据需求调整(0-100)
            End If
        Catch ex As Exception
            lblAlert.Text = "照片上传错误: " & ex.ToString()
        End Try
        hdnPhotoURL.Value = String.Format(webPath, photoFileName)
    End If
    
    ' 处理Logo上传
    Dim logoFileName As String = String.Format("Logo{0}.jpg", hdnAgentID.Value)
    If fupLogo.HasFile Then
        Try
            If fupLogo.PostedFile.ContentLength <= 10000000 Then
                Dim fullLogoPath As String = Path.Combine(savePath, logoFileName)
                fupLogo.SaveAs(fullLogoPath)
                OptimizeImage(fullLogoPath, 450, 85)
            End If
        Catch ex As Exception
            lblAlert.Text = "Logo上传错误: " & ex.ToString()
        End Try
        hdnLogoURL.Value = String.Format(webPath, logoFileName)
    End If
    
    ' 更新UI
    pnlMain.Visible = True
    litJS.Visible = True
End Sub

Private Sub OptimizeImage(ByVal imagePath As String, ByVal maxWidth As Integer, ByVal jpegQuality As Integer)
    ' 使用Using语句自动释放资源,避免内存泄漏
    Using sourceImg As Image = Image.FromFile(imagePath)
        Dim targetWidth As Integer = sourceImg.Width
        Dim targetHeight As Integer = sourceImg.Height
        
        ' 计算缩放尺寸
        If sourceImg.Width > maxWidth Then
            Dim scaleRatio As Double = CDbl(maxWidth) / sourceImg.Width
            targetWidth = maxWidth
            targetHeight = CInt(sourceImg.Height * scaleRatio)
        End If
        
        ' 创建目标位图
        Using targetBmp As New Bitmap(targetWidth, targetHeight)
            Using g As Graphics = Graphics.FromImage(targetBmp)
                ' 设置高质量绘图参数,避免缩放模糊
                g.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                g.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
                g.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
                g.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
                
                ' 精准绘制缩放后的图片
                g.DrawImage(sourceImg, New Rectangle(0, 0, targetWidth, targetHeight), 
                            New Rectangle(0, 0, sourceImg.Width, sourceImg.Height), GraphicsUnit.Pixel)
            End Using
            
            ' 设置JPEG保存参数,控制文件大小
            Dim jpegParams As New Imaging.EncoderParameters(1)
            jpegParams.Param(0) = New Imaging.EncoderParameter(Imaging.Encoder.Quality, jpegQuality)
            
            ' 获取JPEG编码器
            Dim jpegCodec As ImageCodecInfo = GetEncoderInfo("image/jpeg")
            
            ' 保存优化后的图片
            targetBmp.Save(imagePath, jpegCodec, jpegParams)
        End Using
    End Using
End Sub

' 辅助方法:获取指定格式的图像编码器
Private Function GetEncoderInfo(ByVal mimeType As String) As ImageCodecInfo
    Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
    For Each codec As ImageCodecInfo In codecs
        If codec.MimeType = mimeType Then
            Return codec
        End If
    Next
    Return Nothing
End Function

优化要点说明

  • 修复语法错误:原代码中resizeImage调用存在路径拼接引号未闭合问题,改用Path.Combine统一处理路径,避免拼接错误
  • 移除无用延迟:删除Thread.Sleep(1000),完全不影响图片处理,消除不必要的效率损耗
  • 核心体积控制:通过指定JPEG编码器质量参数(0-100),直接控制输出文件大小,解决处理后体积反增的问题
  • 提升图片质量:添加高质量绘图模式,避免缩放后图片模糊失真
  • 自动资源管理:使用Using语句替代手动Dispose,确保资源及时释放,避免内存泄漏
  • 统一逻辑简化:提取重复的路径处理逻辑,代码更简洁易维护
  • 兼容小图优化:即使原图宽度不超过450,也会对JPEG质量进行优化,进一步压缩体积

内容的提问来源于stack exchange,提问作者AspClassic-Guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:39:21