将图片保存到硬盘
本文关键字:硬盘 保存 | 更新日期: 2023-09-27 18:27:33
我正在尝试调整图片的大小并保护图片的安全。我已经做了一些研究,并试图让一些东西发挥作用。几乎所有的方法都有效,但保存给了我一个无效的参数例外。这就是我所拥有的:
private void ResizeImage(Image image)
{
int maxWidth = 100;
int maxHeight = 100;
int imageWidth = image.Size.Width;
int imageHeight = image.Size.Height;
double maxRatio = (double)maxWidth / (double)maxHeight;
double picRatio = (double)imageWidth / (double)imageHeight;
Image newImage = null;
if (maxRatio > picRatio && imageWidth > maxWidth)
{
newImage = new Bitmap(image, new System.Drawing.Size(Convert.ToInt32(maxWidth / picRatio), maxHeight));
}
else if (maxRatio < picRatio && imageHeight > maxHeight)
{
newImage = new Bitmap(image, new System.Drawing.Size(maxWidth, Convert.ToInt32(maxHeight / picRatio)));
}
// Encoder parameter for image quality
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,1);
// Jpeg image codec
ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");
if(jpegCodec != null){
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
newImage.Save(@".'temp'pdf'photos'test.jpg",jpegCodec,encoderParams);
}
}
private ImageCodecInfo getEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
{
if (codecs[i].MimeType == mimeType)
{
return codecs[i];
}
}
return null;
}
但当我尝试运行它时,它在newImage.save()上给了我一个无效的参数异常
根据MSDN,编码器质量参数应该是64位(长)值。更改此行:
var qualityParam = new EncoderParameter(Encoder.Quality, 1);
至
var qualityParam = new EncoderParameter(Encoder.Quality, 1L);