2015-08-10 6 views
3

Я хочу сжать фотографии в asp.net, но код я использую те, которые не полностью сжимают файлы, как только они все еще очень огромны. Как я могу уменьшить размер?Сжатие изображений в asp.net

string directory = Server.MapPath("~/listingImages/" + date + filename); 

// Create a bitmap of the conten t of the fileUpload control in memory 
Bitmap originalBMP = new Bitmap(AsyncFileUpload1.FileContent); 

// Calculate the new image dimensions 
decimal origWidth = originalBMP.Width; 
decimal origHeight = originalBMP.Height; 
decimal sngRatio = origHeight/origWidth; 
int newHeight = 300; //hight in pixels 
decimal newWidth_temp = newHeight/sngRatio; 
int newWidth = Convert.ToInt16(newWidth_temp); 

// Create a new bitmap which will hold the previous resized bitmap 
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight); 
// Create a graphic based on the new bitmap 
Graphics oGraphics = Graphics.FromImage(newBMP); 

// Set the properties for the new graphic file 
oGraphics.SmoothingMode = SmoothingMode.AntiAlias; 
oGraphics.InterpolationMode = InterpolationMode.Bicubic; 
// Draw the new graphic based on the resized bitmap 
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); 

// Save the new graphic file to the server 
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename)); 
+0

Прочтите это http://www.c-sharpcorner.com/uploadfile/rahuldebray/compress-image-to-a-given-size/ – Nalaka

+0

Ваш код ничего не сжимает, он сохраняет несжатое растровое изображение. Вы должны установить формат изображения, который хотите использовать при вызове –

ответ

1

Может быть, вы должны указать image-format:

newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), System.Drawing.Imaging.ImageFormat.Png); 
2

Попробуйте установить compressipn с помощью этого:

public static ImageCodecInfo GetEncoderInfo(String mimeType) 
    { 
     int j; 
     ImageCodecInfo[] encoders; 
     encoders = ImageCodecInfo.GetImageEncoders(); 
     for (j = 0; j < encoders.Length; ++j) 
     { 
      if (encoders[j].MimeType == mimeType) 
       return encoders[j]; 
     } return null; 
    } 

EncoderParameters ep = new EncoderParameters(1); 
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)70); 
ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); 

newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), ici, ep); 

Проверить эту ссылку для получения более подробной информации: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoder.quality%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396.

Смежные вопросы