2012-09-11 34 views
0

我想使图像尺寸小于原始尺寸。我使用以下代码压缩尺寸图像,但它将图像尺寸从1MB增加到1.5MB
任何其他解决方案可以在不改变图像原始高度,宽度的情况下压缩大尺寸图像。少质量较小的输出文件将是 -
如何在不改变原始高度的情况下压缩图像,在c#中的图像宽度

public static byte[] CompressImage(Image img) { 

      int originalwidth = img.Width, originalheight = img.Height; 

      Bitmap bmpimage = new Bitmap(originalwidth, originalheight); 

      Graphics gf = Graphics.FromImage(bmpimage); 
      gf.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; 
      gf.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.AssumeLinear; 
      gf.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; 

      Rectangle rect = new Rectangle(0, 0, originalwidth, originalheight); 
      gf.DrawImage(img, rect, 0, 0, originalwidth, originalheight, GraphicsUnit.Pixel); 

      byte[] imagearray; 

      using (MemoryStream ms = new MemoryStream()) 
      { 
       bmpimage.Save(ms, ImageFormat.Jpeg); 
       imagearray= ms.ToArray(); 
      } 

      return imagearray; 
     } 
+0

你能改写你的问题吗?这听起来像是你在使用“压缩”的时候,你的意思是“缩小”,同时你也在讨论JPEG文件格式的实际文件压缩问题。 – Dai

+0

我想让图像尺寸变小而不会损失quality.this是我的问题。 –

回答

3

当您将文件保存为JPEG,这主要也直接将文件大小相关,您可以将质量级别。

另参见How to: Set JPEG Compression Level,例如参见this SO answer

+0

我也尝试这个和工作,但是当我将它转换为字节数组保存在数据库中时,它会引发异常“不允许大于max_allowed_pa​​cket的数据包”。当我使用我的代码,那么它工作正常。任何想法会是什么问题? –

+0

@AskQuestion:这听起来像一个与你的位图问题无关的MySql错误 - 确保你将压缩设置为一个实际降低输出文件大小的值 - 我相信默认质量是50 - 但是RTFM :-) – BrokenGlass

+0

After转换我得到这个异常,所以我问它可以告诉我它是什么类型的编码我不知道这个功能:) –

0

正如@BrokenGlass所说,您可以指定EncoderParameter中的压缩级别。这里有一个片段,如果你想尝试改变质量:

public static void SaveJpeg(string path, Image image, int quality) 
{ 
    //ensure the quality is within the correct range 
    if ((quality < 0) || (quality > 100)) 
    { 
     //create the error message 
     string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality); 
     //throw a helpful exception 
     throw new ArgumentOutOfRangeException(error); 
    } 

    //create an encoder parameter for the image quality 
    EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); 
    //get the jpeg codec 
    ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); 

    //create a collection of all parameters that we will pass to the encoder 
    EncoderParameters encoderParams = new EncoderParameters(1); 
    //set the quality parameter for the codec 
    encoderParams.Param[0] = qualityParam; 
    //save the image using the codec and the parameters 
    image.Save(path, jpegCodec, encoderParams); 
} 
+0

我也尝试这个,但它会抛出异常“大于max_allowed_pa​​cket大包不被允许。” –

相关问题