草庐IT

php - asp.net 版本的 timthumb php 类

coder 2024-04-10 原文

有人知道著名的 PHP 类“timthumb”的 ASP.Net 版本吗?只需要一个脚本,它将在“timthumb”的同一行中工作,并为任何大小的图像生成质量好的基于方形或比例的缩略图。

这是指向 php 类的链接:http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/

最佳答案

我专门为你写了这篇文章 :) ... 我通过尝试 http://www.binarymoon.co.uk/demo/timthumb-basic/ 中的所有案例对其进行了测试并将其与我的代码并排进行视觉比较。据我所知,它基本上是相同的。话虽如此,它不支持“zc”标志。

我将其编写为通用处理程序(ashx 文件),以便它运行得更快。支持图像缓存,但我将其注释掉,因为它使测试修复变得非常困难。从长远来看,可以随意取消注释以提高性能(一个 block 在开头,一个 block 在将其写入内存流时接近结尾)。

---代码---

<%@ WebHandler Language="VB" Class="Thumb" %>

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

    Public Class Thumb : Implements IHttpHandler
        Private Shared _DefaultWidth As Integer = 100
        Private Shared _DefaultHeight As Integer = 100
        Private Shared _DefaultQuality As Integer = 90

        Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            ''check the cache for the image first
            'Dim cacheObj As Object = context.Cache("Thumb-" + context.Request.Url.ToString().ToLower())
            'If cacheObj IsNot Nothing Then
            '    Dim msCache As MemoryStream = DirectCast(cacheObj, MemoryStream)

            '    WriteImage(msCache, context)

            '    Exit Sub
            'End If

            'process request (since it wasn't in the cache)
            Dim imgPath As String = context.Request.QueryString("src")

            If String.IsNullOrEmpty(imgPath) Then
                context.Response.End()
            End If

            'get image path on server
            Dim serverPath As String = context.Server.MapPath(imgPath)
            If Not File.Exists(serverPath) Then
                context.Response.End()
            End If

            'load image from file path
            Dim img As Image = Bitmap.FromFile(serverPath)
            Dim origRatio As Double = (Math.Min(img.Width, img.Height) / Math.Max(img.Width, img.Height))

            '---Calculate thumbnail sizes---
            Dim destWidth As Integer = 0
            Dim destHeight As Integer = 0
            Dim destRatio As Double = 0

            Dim qW As String = context.Request.QueryString("w")
            Dim qH As String = context.Request.QueryString("h")

            If Not String.IsNullOrEmpty(qW) Then
                Int32.TryParse(qW, destWidth)
                If destWidth < 0 Then
                    destWidth = 0
                End If
            End If

            If Not String.IsNullOrEmpty(qH) Then
                Int32.TryParse(qH, destHeight)
                If destHeight < 0 Then
                    destHeight = 0
                End If
            End If

            'if both width and height are 0 then use defaults (100x100)
            If destWidth = 0 And destHeight = 0 Then
                destWidth = _DefaultWidth
                destHeight = _DefaultHeight

                'else, if the width is specified, calculate an appropriate height
            ElseIf destWidth > 0 And destHeight > 0 Then
                'do nothing, we have both sizes already
            ElseIf destWidth > 0 Then
                destHeight = Math.Floor(img.Height * (destWidth / img.Width))
            ElseIf destHeight > 0 Then
                destWidth = Math.Floor(img.Width * (destHeight / img.Height))
            End If

            destRatio = (Math.Min(destWidth, destHeight) / Math.Max(destWidth, destHeight))

            'calculate source image sizes (rectangle) to get pixel data from        
            Dim sourceWidth As Integer = img.Width
            Dim sourceHeight As Integer = img.Height

            Dim sourceX As Integer = 0
            Dim sourceY As Integer = 0

            Dim cmpx As Integer = img.Width / destWidth
            Dim cmpy As Integer = img.Height / destHeight

            'selection is based on the smallest dimension
            If cmpx > cmpy Then
                sourceWidth = img.Width / cmpx * cmpy
                sourceX = ((img.Width - (img.Width / cmpx * cmpy)) / 2)
            ElseIf cmpy > cmpx Then
                sourceHeight = img.Height / cmpy * cmpx
                sourceY = ((img.Height - (img.Height / cmpy * cmpx)) / 2)
            End If

            '---create the new thumbnail image---
            Dim bmpThumb As New Bitmap(destWidth, destHeight)
            Dim g = Graphics.FromImage(bmpThumb)
            g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
            g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
            g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias

            g.DrawImage(img, _
                        New Rectangle(0, 0, destWidth, destHeight), _
                        New Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel)

            '-----write out Thumbnail to the output stream------        
            'get jpeg image coded info so we can use it when saving
            Dim ici As Imaging.ImageCodecInfo = Imaging.ImageCodecInfo.GetImageEncoders().Where(Function(c) c.MimeType = "image/jpeg").First()

            'save image to memory stream
            Dim ms As New MemoryStream()
            bmpThumb.Save(ms, ici, BuildQualityParams(context))

            ''save image to cache for future use
            'context.Cache("Thumb-" + context.Request.Url.ToString().ToLower()) = ms

            'write the image out
            WriteImage(ms, context)
        End Sub

        Private Sub WriteImage(ByVal ms As MemoryStream, ByVal context As HttpContext)
            'clear the response stream
            context.Response.Clear()

            'set output content type to jpeg
            context.Response.ContentType = "image/jpeg"

            'write memory stream out
            ms.WriteTo(context.Response.OutputStream)

            'flush the stream and end the response
            context.Response.Flush()
            context.Response.End()
        End Sub

        'for adjusting quality setting if needed, otherwise 90 will be used
        Private Function BuildQualityParams(ByVal context As HttpContext) As Imaging.EncoderParameters
            Dim epParams As New Imaging.EncoderParameters(1)

            Dim q As Integer = _DefaultQuality

            Dim strQ As String = context.Request.QueryString("q")
            If Not String.IsNullOrEmpty(strQ) Then
                Int32.TryParse(strQ, q)
            End If

            epParams.Param(0) = New Imaging.EncoderParameter(Imaging.Encoder.Quality, q)

            Return epParams
        End Function

        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property
    End Class

---测试用例---

<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg" /> 
<br />
<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg&q=100" /> 
<br />
<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg&q=10" /> 
<br />
<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg&w=200" /> 
<br />
<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg&h=150" /> 
<br />
<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg&h=180&w=120" /> 
<br />
<img alt="" src="Thumb.ashx?src=~/images/castle1.jpg&h=80&w=210" /> 
<br />

关于php - asp.net 版本的 timthumb php 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4436209/

有关php - asp.net 版本的 timthumb php 类的更多相关文章

  1. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  2. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  3. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  4. ruby-on-rails - 在 ruby​​ .gemspec 文件中,如何指定依赖项的多个版本? - 2

    我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这

  5. ruby-on-rails - 如果我将 ruby​​ 版本 2.5.1 与 rails 版本 2.3.18 一起使用会怎样? - 2

    如果我使用ruby​​版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby​​1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更

  6. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  7. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  8. ruby-on-rails - 如何在发布新的 Ruby 或 Rails 版本时收到通知? - 2

    有人知道在发布新版本的Ruby和Rails时收到电子邮件的方法吗?他们有邮件列表,RubyonRails有一个推特,但我不想听到那些随之而来的喧嚣,我只想知道什么时候发布新版本,尤其是那些有安全修复的版本。 最佳答案 从therailsblog获取提要.http://weblog.rubyonrails.org/feed/atom.xml 关于ruby-on-rails-如何在发布新的Ruby或Rails版本时收到通知?,我们在StackOverflow上找到一个类似的问题:

  9. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  10. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

随机推荐