把图片文件转换成指定大小尺寸格式的文件

介绍了一个C#静态类ImageTransUtility,提供了TranslateByEqualRatio方法用于等比例转换图片大小,确保图片不会被裁剪,同时保持高质量的图像输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace Test.Common
{
    /// <summary>
    /// 提供图片转换工具
    /// </summary>
    public static class ImageTransUtility
    {

        /// <summary>
        /// 该函数提供等比转换功能、图片仅进行压缩,不进行裁切.
        /// </summary>
        /// <param name="sourceFileName"></param>
        /// <param name="targetFileName"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        public static void TranslateByEqualRatio(string sourceFileName, string targetFileName, int maxWidth, int maxHeight)
        {
            if (maxWidth <= 0 || maxHeight <= 0)
            {
                throw new ArgumentException("Width And Height Must More than zero");
            }

            Bitmap fullSizeImg = new Bitmap(sourceFileName);
            int width = fullSizeImg.Width;
            int height = fullSizeImg.Height;

            if (width > maxWidth || height > maxHeight)
            {
                if (maxWidth - width < maxHeight - height)
                {
                    decimal ratio = (decimal)height / width;
                    width = maxWidth;
                    height = (int)Decimal.Round(Convert.ToDecimal((decimal)maxWidth * (decimal)ratio));
                }
                else
                {
                    decimal ratio = (decimal)width / height;
                    height = maxHeight;
                    width = (int)Decimal.Round(Convert.ToDecimal((decimal)maxHeight * (decimal)ratio));
                }
            }

            var thumbnailBitmap = new Bitmap(width, height);
            var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);

            thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var imageRectangle = new Rectangle(0, 0, width, height);
            thumbnailGraph.DrawImage(fullSizeImg, imageRectangle);

            thumbnailBitmap.Save(targetFileName, ImageFormat.Jpeg);

            fullSizeImg.Dispose();
            thumbnailGraph.Dispose();
            thumbnailBitmap.Dispose();
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值