Compressing images in asp.net
I want to compress photos in asp.net, but the code I am using does not fully compress the files once they are still very huge. How can I reduce the size?
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));
+3
source to share
2 answers
Try configuring compressipn using this:
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);
Check out this link for more details: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.encoder.quality%28v=vs.110%29.aspx?f=255&MSPPError=- 2147217396 .
+2
source to share
Perhaps you should specify the image format :
newBMP.Save(Server.MapPath("~/listingImages/" + date + filename), System.Drawing.Imaging.ImageFormat.Png);
+1
source to share