我希望将图片尺寸减小到不超过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。影响我网站性能的图像大小。
答案 0 :(得分:2)
你也可以使用Thumbnailimagemethod ......它似乎正是你想要的。 (我没有测试压缩,但它绝对会影响图像)
Image FinalImage = Image.FromFile(@"yourPath").GetThumbnailImage(X, Y, () => false, IntPtr.Zero);
您也可以使用较低的InterpolationMode
,CompositingQuality
和SmoothingMode
。
答案 1 :(得分:0)
降低图像分辨率可能会导致生成低尺寸图像,
更改scaleFactor值< 0.5,在您现有的代码中。
var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);