在下面的代码中,我正在上传文档我的目标是,如果它是图像文档,我必须将其大小减小到20 kb。请帮助我这样做。
string Uploadpath = ConfigurationManager.AppSettings["SearchFolder"];
string strUploadpath = Uploadpath.TrimEnd("\\".ToCharArray()) + "\\" + strClientName + "\\" + strDocumentFolder + "\\";
DirectoryInfo dInfo = new DirectoryInfo(strUploadpath);
if (!dInfo.Exists)
{
dInfo.Create();
}
if (DocumentsUpload.FileName != null && DocumentsUpload.FileName != string.Empty)
{
DocumentsUpload.SaveAs((strUploadpath) + DocumentsUpload.FileName);
}
答案 0 :(得分:0)
图像尺寸取决于几个因素(尺寸,分辨率,格式,压缩等),并且无法保证您可以在不损失质量的情况下将其减少到20 kb。为了更改文件的大小,您可以尝试保存新图像,以调整其属性,例如CompositingQuality,InterpolationMode以及质量和压缩。例如,CompositingQuality可以设置为“HighSpeed”值,InterpolationMode设置为“Low”等等。这完全取决于您拥有的图像类型,并且需要进行测试。
实施例
//DocumentsUpload.SaveAs((strUploadpath) + DocumentsUpload.FileName);
Stream stream = DocumentsUpload.PostedFile.InputStream;
Bitmap source = new Bitmap(stream);
Bitmap target = new Bitmap(source.Width, source.Height);
Graphics g = Graphics.FromImage(target);
EncoderParameters e;
g.CompositingQuality = CompositingQuality.HighSpeed; <-- here
g.InterpolationMode = InterpolationMode.Low; <-- here
Rectangle recCompression = new Rectangle(0, 0, source.Width, source.Height);
g.DrawImage(source, recCompression);
e = new EncoderParameters(2);
e.Param[0] = new EncoderParameter(Encoder.Quality, 70); <-- here 70% quality
e.Param[1] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); <-- here
target.Save(newName, GetEncoderInfo("image/jpeg"), e);
g.Dispose();
target.Dispose();
public static ImageCodecInfo GetEncoderInfo(string sMime)
{
ImageCodecInfo[] objEncoders;
objEncoders = ImageCodecInfo.GetImageEncoders();
for (int iLoop = 0; iLoop <= (objEncoders.Length - 1); iLoop++)
{
if (objEncoders[iLoop].MimeType == sMime)
return objEncoders[iLoop];
}
return null;
}
希望这有帮助。
答案 1 :(得分:0)
此示例适用于.Net 4.5+,并可以一次上传多个图像。还根据变量MaxWidthHeight的值动态调整图像的大小。对不起,我的英语不好。
示例
MediaStore