在上传时减小图像的大小

本文关键字:图像 | 更新日期: 2023-09-27 18:01:58

在下面的代码中,我正在上传一个文档,我的目标是,如果它是一个图像文档,我必须将其大小减少到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);
                       }

在上传时减小图像的大小

图像大小取决于几个因素(大小,分辨率,格式,压缩等),并且不能保证您可以在不损失质量的情况下将其缩小到恰好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;
}

此示例适用于。net 4.5+,并一次上传多个图像。还可以根据变量MaxWidthHeight的值动态调整图像的大小。请原谅我英语不好。

例子
private void  UploadResizeImage()
    {
        string codigo = "";
        string dano = "";
        string nav = "";
        string nombreArchivo = "";
        string extension = "";
        int cont = 0;
        int MaxWidthHeight = 1024; // This is the maximum size that the width or height file should have
        int factorConversion = 0;
        int newWidth = 0;
        int newHeight = 0;
        int porcExcesoImg = 0;
        Bitmap newImage = null;
        string directory = "dano";
        System.Drawing.Image image = null;
        string targetPath = "";
        try
        {
            if (!String.IsNullOrEmpty(Request.QueryString["codigo"]) && !String.IsNullOrEmpty(Request.QueryString["dano"]) && !String.IsNullOrEmpty(Request.QueryString["nav"]))
            {
                codigo = Request.QueryString["codigo"].ToString();
                dano = Request.QueryString["dano"].ToString();
                nav = Request.QueryString["nav"].ToString();
                Directory.CreateDirectory(Server.MapPath(directory));
                Directory.CreateDirectory(Server.MapPath(directory + "/" + nav));
                string fechaHora = DateTime.Now.ToString("yyyyMMdd-HHmmss");
                nombreArchivo = codigo + "-" + dano + "-" + fechaHora;

                string html = "<h4>Se cargaron con éxito estos archivos al servidor:</h4>";
                if (UploadImages.HasFiles)
                {
                    html += "<ul>";
                    foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
                    {
                        cont++;
                        extension = System.IO.Path.GetExtension(UploadImages.FileName);
                        targetPath = Server.MapPath("~/" + directory + "/" + nav + "/").ToString() + nombreArchivo + "-" + cont.ToString() + extension;
                        if (extension.ToLower() == ".png" || extension.ToLower() == ".jpg")
                        {
                            Stream strm = null;
                            strm = uploadedFile.InputStream;
                            //strm = UploadImages.PostedFile.InputStream;
                            using (image = System.Drawing.Image.FromStream(strm))
                            {
                                string size = image.Size.ToString();
                                int width = image.Width;
                                int height = image.Height;
                                if (width > MaxWidthHeight || height > MaxWidthHeight)
                                {
                                    porcExcesoImg = (width * 100) / MaxWidthHeight; // excessive size in percentage
                                    factorConversion = porcExcesoImg / 100;
                                    newWidth = width / factorConversion;
                                    newHeight = height / factorConversion;
                                    newImage = new Bitmap(newWidth, newHeight);
                                    var graphImage = Graphics.FromImage(newImage);
                                    graphImage.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                                    graphImage.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                    graphImage.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                    var imgRectangle = new Rectangle(0, 0, newWidth, newHeight);
                                    graphImage.DrawImage(image, imgRectangle);
                                    newImage.Save(targetPath, image.RawFormat);
                                }
                                else
                                {
                                    uploadedFile.SaveAs(targetPath);
                                }

                                html += "<li>" + String.Format("{0}", uploadedFile.FileName) + "</li>";
                            }
                        }
                    }
                    html += "</ul>";
                    listofuploadedfiles.Text = html;
                }
                else
                {
                    listofuploadedfiles.Text = "No se ha selecionado ninguna imagen!";
                }
            }
            else
            {
                listofuploadedfiles.Text = "No se recibieron los parámetros para poder cargar las imágenes!";
            }
        }
        catch (Exception ex)
        {
            listofuploadedfiles.Text = ex.Message.ToString();
        }
    }