C# 需要压缩服务器上的映像大小
我在优化代码以上载最小大小的图像时遇到问题 以下是我正在使用的代码:C# 需要压缩服务器上的映像大小,c#,asp.net,image,C#,Asp.net,Image,我在优化代码以上载最小大小的图像时遇到问题 以下是我正在使用的代码: public bool GenerateThumbnail(Stream inputStream, string filePath, int targetWidth, int targetHeight, bool fixedWidthImage) { bool success = false; try { using (var image = Im
public bool GenerateThumbnail(Stream inputStream, string filePath, int targetWidth, int targetHeight, bool fixedWidthImage)
{
bool success = false;
try
{
using (var image = Image.FromStream(inputStream))
{
FileInfo file = new FileInfo(filePath);
var extension = file.Extension;
float targetRatio = targetWidth / (float)targetHeight;
int width = image.Width;
int height = image.Height;
float imageRatio = width / (float)height;
int newWidth;
int newHeight;
if (targetRatio > imageRatio && !fixedWidthImage)
{
newHeight = targetHeight;
newWidth = (int)Math.Floor(imageRatio * targetHeight);
}
else
{
newHeight = (int)Math.Floor(targetWidth / imageRatio);
newWidth = targetWidth;
}
var thumbnailImg = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
var graphics = Graphics.FromImage(thumbnailImg);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
graphics.DrawImage(image, imageRectangle);
//thumbnailImg.Save(filePath, image.RawFormat);
// Get an ImageCodecInfo object that represents the JPEG codec.
ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == image.RawFormat.Guid);
// Create an Encoder object for the Quality parameter.
Encoder encoder = Encoder.Quality;
// Create an EncoderParameters object.
EncoderParameters encoderParameters = new EncoderParameters(1);
// Save the image as a JPEG file with quality level.
EncoderParameter encoderParameter = new EncoderParameter(encoder, 25L);
encoderParameters.Param[0] = encoderParameter;
thumbnailImg.Save(filePath, imageCodecInfo, encoderParameters);
success = true;
}
}
catch (Exception)
{
success = false;
}
return success;
}
另外,当我使用低尺寸图像上传20KB时,它会转换为相同尺寸的>36KB
所以,基本上,我需要优化我的代码,以获得目标图像尺寸的最小sizeKb图像。我的首要任务是获得最小尺寸的图像和尽可能好的图像质量
谢谢。有没有想过使用ImageMagick?什么叫“遇到问题”?问题是什么?嗯@Lorek,我的问题是我没有得到预期压缩大小的图像。