gpt4 book ai didi

c# - 使用 .Net Framework 4.5 压缩图像

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:09 25 4
gpt4 key购买 nike

我有下一个代码:

class Program
{
const string ImagePath = @"C:\mypath\36";
private const int Quality = 50;

static void Main()
{
Console.WriteLine("Inicio: " + DateTime.Now);
var images = Directory.GetFiles(ImagePath);

foreach (var name in images)
{
var bitmap = new Bitmap(name);
var tname = name.Split('\\')[5].Split('.')[0];
VariousQuality(bitmap, tname);
}
Console.WriteLine("Finalizacion: " + DateTime.Now);
Console.ReadLine();
}

static void VariousQuality(Image original, string name)
{
var codecs = ImageCodecInfo.GetImageEncoders();
var jpgEncoder = codecs.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);

if (jpgEncoder == null) return;

var encoder = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);

var encoderParameter = new EncoderParameter(encoder, Quality);
encoderParameters.Param[0] = encoderParameter;

var fileOut = Path.Combine(ImagePath, "__" + name + ".jpg");
var ms = new FileStream(fileOut, FileMode.Create, FileAccess.Write);
original.Save(ms, jpgEncoder, encoderParameters);

ms.Flush();
ms.Close();

}

static void DefaultCompressionPng(Image original)
{
var ms = new MemoryStream();
original.Save(ms, ImageFormat.Png);
var compressed = new Bitmap(ms);
ms.Close();

var fileOutPng = Path.Combine(ImagePath, "default.png");
compressed.Save(fileOutPng, ImageFormat.Png);
}

static void DefaultCompressionJpeg(Image original)
{
var ms = new MemoryStream();
original.Save(ms, ImageFormat.Jpeg);
var compressed = new Bitmap(ms);
ms.Close();

var fileOutPng = Path.Combine(ImagePath, "default.jpg");
compressed.Save(fileOutPng, ImageFormat.Jpeg);
}

}

该代码适用于 .Net 4.0 版,但现在我将代码更新到 4.5 版,我收到下一个错误:

original.Save(ms, jpgEncoder, encoderParameters);

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll {System.Collections.ListDictionaryInternal} The parameter is invalid. System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
ImageCompression.Program.VariousQuality(Image original, String name 2012\Projects\ImageCompression\ImageCompression\Program.cs:line 44

关于如何修复此错误的一些想法?

最佳答案

Quality 类型更改为 long

private const long Quality = 50;

附言

MSDN Encoder.Quality示例:

 myEncoderParameter = new EncoderParameter(myEncoder, 50L);

关于c# - 使用 .Net Framework 4.5 压缩图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43459185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com