Asp.Net:动态图像调整大小

时间:2013-05-07 08:38:54

标签: c# asp.net image-resizing timthumb

我想为我的Asp.Net网站项目创建图像大小调整机制,如timthumb。我想这样做:

  • 上传图片
  • 设置尺寸
  • 如果我需要此图片的其他尺寸,我可以提供“仅”尺寸,而无需再次上传。

我怎么能这样做,你有什么建议吗?

这是我的调整大小功能:

 public Bitmap Resize(Bitmap image, int newWidth, int newHeight, string message)
    {
        try
        {
            Bitmap newImage = new Bitmap(newWidth, Calculations(image.Width, image.Height, newWidth));

            using (Graphics gr = Graphics.FromImage(newImage))
            {

                gr.SmoothingMode = SmoothingMode.AntiAlias;
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
                gr.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height));

                var myBrush = new SolidBrush(Color.FromArgb(64, 205, 205, 205));

                double diagonal = Math.Sqrt(newImage.Width * newImage.Width + newImage.Height * newImage.Height);

                var containerBox = new Rectangle();

                containerBox.X = (int)(diagonal / 10);
                var messageLength = (float)(diagonal / message.Length * 1);
                containerBox.Y = -(int)(messageLength / 1.6);

                var stringFont = new Font("verdana", messageLength);

                var sf = new StringFormat();

                var slope = (float)(Math.Atan2(newImage.Height, newImage.Width) * 180 / Math.PI);

                gr.RotateTransform(slope);
                gr.DrawString(message, stringFont, myBrush, containerBox, sf);
                return newImage;
            }
        }
        catch (Exception exc)
        {
            throw exc;
        }
    }


    public int Calculations(decimal orjWidth, decimal orjHeight, int newWidth)
    {
        decimal height = 0;
        decimal ratio = 0;


        if (newWidth < orjWidth)
        {
            ratio = orjWidth / newWidth;
            height = orjHeight / ratio;

            return height.To<int>();
        }

        if (orjWidth <= newWidth)
        {
            ratio = newWidth / orjWidth;
            height = orjHeight * ratio;
            return height.To<int>();
        }

        return height.To<int>();
    }

2 个答案:

答案 0 :(得分:2)

这是用jQuery脚本完成的。

通过使用一些可用的jQuery插件,您可以实现相同的背景图像动态调整大小效果。例如:http://srobbin.com/jquery-plugins/backstretch/

此外,这可以通过使用纯CSS3来完成: https://css-tricks.com/perfect-full-page-background-image/ 最好的问候,templateMonster加盟团队!

答案 1 :(得分:0)

您正在寻找ImageResizer library & httpmodule

如果你使用NuGet,你可以Install-Package ImageResizer.MvcWebConfig