当前位置: 首页 > 建站教程

c#图片压缩到固定大小怎么实现

时间:2026-01-31 10:59:21

你可以使用C#中的System.Drawing命名空间来实现图片的压缩。下面是一个简单的示例代码,演示如何将图片压缩到指定的大小:

using System;using System.Drawing;using System.Drawing.Imaging;using System.IO;public class ImageCompressor{public void CompressImage(string sourcePath, string outputPath, int maxWidth, int maxHeight){using (Image sourceImage = Image.FromFile(sourcePath)){double aspectRatio = (double)sourceImage.Width / sourceImage.Height;int newWidth = maxWidth;int newHeight = (int)(maxWidth / aspectRatio);if (newHeight > maxHeight){newHeight = maxHeight;newWidth = (int)(maxHeight * aspectRatio);}using (Bitmap compressedImage = new Bitmap(newWidth, newHeight)){using (Graphics graphics = Graphics.FromImage(compressedImage)){graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;graphics.DrawImage(sourceImage, 0, 0, newWidth, newHeight);}compressedImage.Save(outputPath, ImageFormat.Jpeg);}}}}class Program{static void Main(){ImageCompressor compressor = new ImageCompressor();compressor.CompressImage("source.jpg", "compressed.jpg", 800, 600);}}

在上面的示例代码中,CompressImage方法接受源图片的路径、输出路径以及目标宽度和高度作为参数。算法会计算出适合目标宽度和高度的图片尺寸,并将源图片按照这个尺寸进行压缩保存为JPEG格式。您可以根据需要调整压缩质量和输出格式。


上一篇:hibernate自动生成表怎么实现
下一篇:SpringBoot中怎么实现邮件发送功能
C
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素