GDI+ 中发生一般错误。在保存压缩的img时,Microsoft的代码片段是否有问题



我正在努力压缩图像,但我不断得到:

System.Runtime.InteropServices.ExternalException:"GDI+ 中发生一般错误。

在这些行上:

cloneImage.Save(saveImagePath, typeOfImageEncoder, cirarEncoderParameters);
image.Save(saveImagePath, typeOfImageEncoder, cirarEncoderParameters);

我尝试在我的代码中克隆位图图像,但结果仍然相同。我已经阅读了一些可能是用户权限的阅读,但我已经检查了路径文件夹,并且我拥有读取和执行所需的所有类型。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
namespace CompressImages
{
class Program
{
static void Main(string[] args)
{
var small = @"C:TempDev areaimageCompressOriginal Imagespotato-small.jpg";
var medium = @"C:TempDev areaimageCompressOriginal Imagespotato-medium.jpg";
var large = @"C:TempDev areaimageCompressOriginal Imagespotato-large.jpg";
var savePath = @"C:TempDev areaimageCompressCompressed images";
CompressImage(small, savePath);
}
public static void CompressImage(string imagePath, string saveImagePath)
{
ImageCodecInfo typeOfImageEncoder;
using (Bitmap image = new Bitmap(imagePath))
{
if (imagePath.Contains(".jpg"))
{
typeOfImageEncoder = GetEncoder(ImageFormat.Jpeg);
}
else if (imagePath.Contains(".png"))
{
typeOfImageEncoder = GetEncoder(ImageFormat.Png);
}
else
{
throw new NullReferenceException();
}
System.Drawing.Imaging.Encoder cirarEncoder =
System.Drawing.Imaging.Encoder.Quality;
EncoderParameters cirarEncoderParameters = new EncoderParameters(1);
EncoderParameter cirarEncoderParameter = new EncoderParameter(cirarEncoder, 50L);
cirarEncoderParameters.Param[0] = cirarEncoderParameter;
//Bitmap cloneImage = (Bitmap) image.Clone();
//cloneImage.Save(saveImagePath, typeOfImageEncoder, cirarEncoderParameters);
image.Save(saveImagePath, typeOfImageEncoder, cirarEncoderParameters);
}
}     
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
// GDI+ is the portion of the Windows operating system that provides two-dimensional vector graphics, imaging, and typography
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
// Global Unique IDentifier === Guid
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
} 

大部分代码都可以在这里找到。

如何:设置 JPEG 压缩级别

在 @jimi 和 @Canton7 的帮助下,我注意到我需要将保存路径更改为文件,而不是使用包含目录路径的变量。

image.Save(saveImagePath + "FileName.jpg", typeOfImageEncoder, cirarEncoderParameters);

最新更新