0

我想将图片大小减小到 50 kb 以下。

在这里,我给出了我在我的应用程序中使用的代码。

byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize(int)FileUpload1.PostedFile.ContentLength);
var fileLength1 = (FileUpload1.FileContent.Length.ToString());
byte[] ImageData = GenerateThumbnails(0.005, uploadedImage.InputStream);

private byte[] GenerateThumbnails(double scaleFactor, Stream sourcePath) {
  var image = System.Drawing.Image.FromStream(sourcePath);
  var newWidth = (int)(image.Width * scaleFactor);
  var newHeight = (int)(image.Height * scaleFactor);
  var thumbnailImg = new Bitmap(newWidth, newHeight);
  var thumbGraph = Graphics.FromImage(thumbnailImg);
  thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
  thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
  thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
  var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
  thumbGraph.DrawImage(image, imageRectangle);
  MemoryStream ms = new MemoryStream();
  image.Save(ms, ImageFormat.Jpeg);
  return ms.ToArray();    
}

这里的功能GenerateThumbnails减少了图片的实际大小,但它非常小。假设我上传的图片大小为 800kb,该功能只会从 800kb 减少 40kb。影响我网站性能的图像大小。

4

2 回答 2

2

您也可以使用 Thumbnailimage 方法......这似乎正是您想要的。(我没有测试压缩,但它肯定会压缩图像)

Image FinalImage = Image.FromFile(@"yourPath").GetThumbnailImage(X, Y, () => false, IntPtr.Zero);

您也可以使用较低InterpolationModeCompositingQuality, 和SmoothingMode.

于 2013-09-25T12:26:23.617 回答
0

Reducing the Resolution of the Image can result in producing low size Images,

Change the scaleFactor value < 0.5, in your existing code.

var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);
于 2013-09-25T12:22:26.237 回答