2016-08-24 4 views
0

이것은 내 이미지 코드를 추가 한 것입니다.asp.net에 저장하기 전에 이미지를 압축하는 방법은 무엇입니까?

protected void SubmitButton_Click(object sender, EventArgs e) 
     { 
      ProductImages productImage = new ProductImages(); 
      productImage.ProductID = Convert.ToInt32(ProductDropDownList.SelectedValue.ToString()); 

      if (!FileUpload1.HasFile) 
      { 
       MessageLabel1.Text = "Please Select Image File"; //checking if file uploader has no file selected 
      } 
      else 
      { 
       int length = FileUpload1.PostedFile.ContentLength; 
       productImage.ProductImage = new byte[length]; 

       FileUpload1.PostedFile.InputStream.Read(productImage.ProductImage, 0, length); 

       try 
       { 
        ProductImageBL.AddProductImages(productImage); 
        MessageLabel1.Text = "Product Image has been successfully added!"; 
       } 
       catch (Exception ex) 
       { 
        MessageLabel1.Text = "Some error occured while processing the request. Error Description <br/>" + ex.Message; 
       } 
      } 
     } 
+1

표시 하시겠습니까? – ChrisBint

+0

여기에 추가하려고합니다. 또한 디스플레이 용 – Orion

답변

2

이미지 압축은 이미지 유형과 이미지에 따라 다릅니다. 실물 사진의 사진은 일반적으로 .jpg로되어있어 눈에 띄는 품질 손실없이 사진을 많이 압축 할 수는 없습니다.

아마 당신이 원하는 것일 것입니다. 아마 당신의 필요에 따라 충분할 것입니다. 500 * 500 같은 작은 크기로 이미지 크기를 조정하십시오. 크기 조정 중에 이미지 종횡비를 저장하는 것이 좋습니다.

관련 SO 질문 : Resize an Image C#

1

dlxeon에 의해 게시 한 SO link이 우수합니다. 나는 그곳에서 본보기를 사용한다. 그러나이 모든 예제는 이미지의 크기를 조정하지만 jpeg 파일의 압축률을 높이거나 \를 낮추거나 DPI를 낮출 수도 있습니다.

다음은 jpeg의 크기를 조정하고 압축하는 방법에 대한 전체 예제입니다. 또한 휴대 전화가 수직으로 고정 된 경우 이미지가 회전해야하는지 확인합니다. 이미지를 정사각형으로 만들려면 패딩을 추가 할 수 있습니다.

이 예제를 그대로 사용하면 .png 및 .gif 파일의 투명도가 jpg로 변환되므로 손실됩니다.

protected void SubmitButton_Click(object sender, EventArgs e) 
    { 
     if (FileUpload1.HasFile == true) 
     { 
      using (Bitmap postedImage = new Bitmap(FileUpload1.PostedFile.InputStream)) 
      { 
       byte [] bin = Common.scaleImage(postedImage, 400, 400, false); 
       Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bin); 
      } 
     } 
    } 


    public static byte[] scaleImage(Image image, int maxWidth, int maxHeight, bool padImage) 
    { 
     try 
     { 
      int newWidth; 
      int newHeight; 
      byte[] returnArray; 

      //check if the image needs rotating (eg phone held vertical when taking a picture for example) 
      foreach (var prop in image.PropertyItems) 
      { 
       if (prop.Id == 0x0112) 
       { 
        int rotateValue = image.GetPropertyItem(prop.Id).Value[0]; 
        RotateFlipType flipType = getRotateFlipType(rotateValue); 
        image.RotateFlip(flipType); 
        break; 
       } 
      } 

      //apply padding if needed 
      if (padImage == true) 
      { 
       image = applyPaddingToImage(image); 
      } 

      //check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions 
      if (image.Width > maxWidth || image.Height > maxHeight) 
      { 
       var ratioX = (double)maxWidth/image.Width; 
       var ratioY = (double)maxHeight/image.Height; 
       var ratio = Math.Min(ratioX, ratioY); 

       newWidth = (int)(image.Width * ratio); 
       newHeight = (int)(image.Height * ratio); 
      } 
      else 
      { 
       newWidth = image.Width; 
       newHeight = image.Height; 
      } 

      //start with a new image 
      var newImage = new Bitmap(newWidth, newHeight); 

      //set the new resolution, 72 is usually good enough for displaying images on monitors 
      newImage.SetResolution(72, 72); 
      //or use the original resolution 
      //newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); 

      //resize the image 
      using (var graphics = Graphics.FromImage(newImage)) 
      { 
       graphics.CompositingMode = CompositingMode.SourceCopy; 
       graphics.CompositingQuality = CompositingQuality.HighQuality; 
       graphics.SmoothingMode = SmoothingMode.HighQuality; 
       graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 
       graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; 

       graphics.DrawImage(image, 0, 0, newWidth, newHeight); 
      } 
      image = newImage; 

      //save the image to a memorystream to apply the compression level, higher compression = better quality = bigger images 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       EncoderParameters encoderParameters = new EncoderParameters(1); 
       encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L); 
       image.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters); 

       //save the stream as byte array 
       returnArray = ms.ToArray(); 
      } 

      //cleanup 
      image.Dispose(); 
      newImage.Dispose(); 

      return returnArray; 
     } 
     catch (Exception ex) 
     { 
      //there was an error: ex.Message 
      return null; 
     } 
    } 


    private static ImageCodecInfo getEncoderInfo(string mimeType) 
    { 
     ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); 
     for (int j = 0; j < encoders.Length; ++j) 
     { 
      if (encoders[j].MimeType.ToLower() == mimeType.ToLower()) 
       return encoders[j]; 
     } 
     return null; 
    } 


    private static Image applyPaddingToImage(Image image) 
    { 
     //get the maximum size of the image dimensions 
     int maxSize = Math.Max(image.Height, image.Width); 
     Size squareSize = new Size(maxSize, maxSize); 

     //create a new square image 
     Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height); 

     using (Graphics graphics = Graphics.FromImage(squareImage)) 
     { 
      //fill the new square with a color 
      graphics.FillRectangle(Brushes.Red, 0, 0, squareSize.Width, squareSize.Height); 

      graphics.CompositingMode = CompositingMode.SourceCopy; 
      graphics.CompositingQuality = CompositingQuality.HighQuality; 
      graphics.SmoothingMode = SmoothingMode.HighQuality; 
      graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 
      graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; 

      //put the original image on top of the new square 
      graphics.DrawImage(image, (squareSize.Width/2) - (image.Width/2), (squareSize.Height/2) - (image.Height/2), image.Width, image.Height); 
     } 

     return squareImage; 
    } 


    private static RotateFlipType getRotateFlipType(int rotateValue) 
    { 
     RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone; 

     switch (rotateValue) 
     { 
      case 1: 
       flipType = RotateFlipType.RotateNoneFlipNone; 
       break; 
      case 2: 
       flipType = RotateFlipType.RotateNoneFlipX; 
       break; 
      case 3: 
       flipType = RotateFlipType.Rotate180FlipNone; 
       break; 
      case 4: 
       flipType = RotateFlipType.Rotate180FlipX; 
       break; 
      case 5: 
       flipType = RotateFlipType.Rotate90FlipX; 
       break; 
      case 6: 
       flipType = RotateFlipType.Rotate90FlipNone; 
       break; 
      case 7: 
       flipType = RotateFlipType.Rotate270FlipX; 
       break; 
      case 8: 
       flipType = RotateFlipType.Rotate270FlipNone; 
       break; 
      default: 
       flipType = RotateFlipType.RotateNoneFlipNone; 
       break; 
     } 

     return flipType; 
    } 
관련 문제