c# 如果image过大,就缩小到300k一下
时间: 2023-08-02 09:17:29 浏览: 269
你可以使用C#中的System.Drawing命名空间中的类来实现图片的缩小。具体步骤如下:
1. 使用Bitmap类打开要缩小的图片。
2. 获取图片的大小,计算当前图片的大小是否超过300k。
3. 如果图片大小超过300k,就计算需要缩小的比例,同时修改图片的大小。
4. 使用Graphics类的DrawImage方法,将原始图片绘制到新的Bitmap对象中。
5. 使用ImageFormat类将新的Bitmap对象保存为图片文件。
下面是一个简单的示例代码:
```
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public static void SaveImage(string imagePath)
{
Bitmap original = new Bitmap(imagePath);
int maxSize = 300 * 1024; // 最大尺寸300k
int currentSize = 0;
using (var ms = new MemoryStream())
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
original.Save(ms, jpgEncoder, encoderParams);
currentSize = (int)ms.Length;
}
if (currentSize > maxSize)
{
float ratio = (float)maxSize / currentSize;
int targetWidth = (int)(original.Width * ratio);
int targetHeight = (int)(original.Height * ratio);
Bitmap resized = new Bitmap(targetWidth, targetHeight);
Graphics g = Graphics.FromImage(resized);
g.DrawImage(original, new Rectangle(0, 0, targetWidth, targetHeight));
resized.Save("output.jpg", ImageFormat.Jpeg);
}
else
{
original.Save("output.jpg", ImageFormat.Jpeg);
}
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
```
在上面的示例代码中,我们首先使用MemoryStream将原始图片转换为JPEG格式,并计算当前图片的大小。如果图片大小超过300k,我们就根据需要缩小图片,并将缩小后的图片保存为output.jpg文件。如果图片大小未超过300k,则直接将原始图片保存为output.jpg文件。你可以根据需要修改maxSize参数和保存文件名。
阅读全文
相关推荐














