【问题标题】:To reduce the size of image when uploading上传时缩小图片大小
【发布时间】:2014-06-22 19:56:48
【问题描述】:

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

【问题讨论】:

标签: c# asp.net


【解决方案1】:

图像大小取决于几个因素(大小、分辨率、格式、压缩等),并且不能保证您可以将其缩小到 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;
}

希望这会有所帮助。

【讨论】:

  • 在目标保存中它会在 newName “当前上下文中不存在”中引发错误
  • 是否适用于所有图片格式jpg,gif,png
  • newName 是保存此图像的文件的名称msdn.microsoft.com/de-de/library/ytz20d80(v=vs.110).aspx 它适用于所有图像,但如您所见,它以 JPEG 格式保存目标
【解决方案2】:

此示例适用于 .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();
        }
    }

【讨论】: