C# 缩略图算法

自己一直使用的一段缩略图算法。放在ashx文件当中,使用十分方便。对付一般网站程序已经足够了。

C# 缩略图算法
using (var stream = new FileStream(physicalPath, FileMode.Open, FileAccess.Read))
{
    Bitmap target = null;
    int targetWidth, targetHeight;
    try
    {
        using (var bitmap = new Bitmap(stream))
        {
            var size = bitmap.PhysicalDimension; 
            if (size.Width > size.Height)
            {
                if (size.Width > _maximumWidth)
                {
                    targetWidth = _maximumWidth;
                    targetHeight = (int)size.Height * _maximumWidth / (int)size.Width;
                }
                else
                {
                    targetWidth = (int)size.Width;
                    targetHeight = (int)size.Height;
                }

                if (targetHeight >= _maximumHeight)
                {
                    targetWidth = targetWidth * _maximumHeight / targetHeight;
                    targetHeight = _maximumHeight;
                }
            }
            else
            {
                if (size.Height > _maximumHeight)
                {
                    targetHeight = _maximumHeight;
                    targetWidth = (int)size.Width * _maximumHeight / (int)size.Height;
                }
                else
                {
                    targetHeight = (int)size.Height;
                    targetWidth = (int)size.Width;
                }

                if (targetWidth >= _maximumWidth)
                {
                    targetHeight = targetHeight * _maximumWidth / targetWidth;
                    targetWidth = _maximumWidth;
                }
            }

            SizeF targetSize = SizeF.Empty;

            targetSize = new SizeF(targetWidth, targetHeight);

            target = new Bitmap(targetWidth, targetHeight);
using (var graphics = Graphics.FromImage(target)) { graphics.CompositingQuality = compositingQuality; graphics.InterpolationMode = interpolationMode; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.DrawImage(bitmap, 0, 0, targetSize.Width, targetSize.Height); } } context.Response.ContentType = "image/jpg"; using (MemoryStream memoryStream = new MemoryStream()) { target.Save(memoryStream, ImageFormat.Jpeg); memoryStream.WriteTo(context.Response.OutputStream); } } finally { if (target != null) { target.Dispose(); } } }
C# 缩略图算法

C# 缩略图算法

上一篇:公司管理中人员流失的情况分析


下一篇:选择排序法-java详解案例