首页 > 其他 > 详细

C# 缩略图算法

时间:2014-02-01 13:16:40      阅读:519      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
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(); } } }
bubuko.com,布布扣

C# 缩略图算法

原文:http://www.cnblogs.com/joysoy/p/3536870.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!