优化Web应用程序的图像

时间:2014-05-22 12:10:14

标签: image optimization

http://themeforest.nethttp://photodune.net/https://www.flickr.com和其他影像网站等网站会显示以优化其图片。例如,Photodune在用户点击产品之前将图像显示为缩略图,然后将您带到主销售页面。然后你可以选择购买Extra Small,Small,Medium等。这也适用于Flickr,你可以选择查看同一张照片的不同分辨率。所以,我的问题是:

当Web应用程序用户上传图像时,Web应用程序是否会自动优化同一图像的多个分辨率(例如,缩略图用于显示在Feed中,而大型版本用于其自己的博客帖子)。如果确实如此,你会怎么做? (代码示例会很棒)它是一种显示不同尺寸图像的流行方法吗?

1 个答案:

答案 0 :(得分:1)

几年前我在VB中编写了一个ASPX脚本来重新调整图像大小。原始图像文件存储在服务器上。当您请求图像时,您可以指定所需的大小,并在服务器上重新调整图像大小,然后将其发送到客户端。

所以有了一张图片,我可以要求任何我想要的尺寸。我不确定Flickr和其他人是如何做到这一点的,但是它适用于分配了很小空间的主机上的低流量站点。

这段代码非常陈旧,可能不是最好的方法,但它确实有效。

' Open the file specified in the request.
Dim sSrc As String = Request.QueryString("SRC")
Dim oImg As System.Drawing.Image
oImg = System.Drawing.Image.FromFile(Server.MapPath(sSrc))

' Get the requested width.
Dim iWidth As Integer
iWidth = Request.QueryString("W")

' Get the requested height.
Dim iHeight As Integer
iHeight = Request.QueryString("H")

' Calculate the aspect ratio if either H or W are zero.
If iWidth > 0 And iHeight = 0 Then
    iHeight = oImg.Height / (oImg.Width / iWidth)
End If
If iWidth = 0 And iHeight > 0 Then
    iWidth = oImg.Width / (oImg.Height / iHeight)
End If

' Resize the image.
Dim iQuality As Integer = 100
Dim oThumb As New System.Drawing.Bitmap(iWidth, iHeight)
Dim oGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(oThumb)
oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
oGraphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality
oGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
oGraphics.DrawImage(oImg, 0, 0, iWidth, iHeight)

' Load the JPEG encoder and set the quality parameter.
Dim oEncoder As System.Drawing.Imaging.ImageCodecInfo
oEncoder = GetImageEncoder("JPEG")
Dim oParameters As New System.Drawing.Imaging.EncoderParameters(1)
Dim oParameter As New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, iQuality)
oParameters.Param(0) = oParameter

' Save the new image to the response stream.
Response.Clear
Response.ContentType = oEncoder.MimeType
oThumb.Save(Response.OutputStream, oEncoder, oParameters)

' Release the resources used by the image objects.
oParameter.Dispose()
oParameters.Dispose()
oGraphics.Dispose()
oThumb.Dispose()
oImg.Dispose()

Private Shared Function GetImageEncoder(ByVal FormatDescription As String) As System.Drawing.Imaging.ImageCodecInfo
    Dim oEncoders() As System.Drawing.Imaging.ImageCodecInfo
    Dim oEncoder As System.Drawing.Imaging.ImageCodecInfo
    oEncoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
    For Each oEncoder in oEncoders
        If oEncoder.FormatDescription = FormatDescription Then
            Return oEncoder
        End If
    Next
    Return Nothing
End Function

这没有任何错误处理,我只将有用位复制到此。此外,这仅用于从服务器请求图像,它不会将图像放在服务器上。