2012-09-11 2 views
0

이미지 크기를 원래 크기보다 작게 만들려고합니다. 다음 코드를 사용하여 크기 이미지를 압축하지만 이미지 크기를 1MB에서 1.5MB로 늘립니다.
기타 원본 이미지의 높이, 너비를 변경하지 않고 큰 크기의 이미지를 압축하는 다른 솔루션. 작은 출력 파일이있을 것입니다 덜 품질 - 당신은 대부분 직접 파일 크기와 상관 관계 것 JPEG 등의 파일을 저장할 때
이미지를 원래의 높이, 너비를 변경하지 않고 압축하는 방법 #

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

나는 품질을 잃지 않고 이미지 크기를 작게 만들고 싶습니다. 이것은 제 질문입니다. –

답변

3

당신은 품질 수준을 설정할 수 있습니다.

How to: Set JPEG Compression Level을 참조하십시오 (예 : this SO answer 참조).

+0

나는 또한이 시도하고 작동하지만 데이터베이스에 저장하기 위해 바이트 배열로 변환 할 때 예외를 throw합니다 "max_allowed_packet보다 큰 패킷은 허용되지 않습니다." 내 코드를 사용할 때 잘 작동합니다. 어떤 아이디어가 문제일까요? –

+0

@AskQuestion : 비트 맵 질문과 관련없는 MySql 오류처럼 들리지만 압축률을 출력 파일 크기를 실제로 낮추는 값으로 설정하십시오 - 기본 품질은 50이라고 생각하지만 RTFM :-) – BrokenGlass

+0

변환 그래서 나는 그것에 대해 물어 그래서이 예외가있어. 어떤 유형의 인코딩이 나는이 함수에 대해 전혀 모른다. –

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

나는 또한 이것을 시도하지만 예외를 throw합니다 "max_allowed_packet보다 큰 패킷은 허용되지 않습니다." –

관련 문제