High-quality Image Compression
Last Update:2018-12-05
Source: Internet
Author: User
# Region using directives
Using system;
Using system. Web;
Using system. drawing;
Using system. Drawing. imaging;
Using system. Drawing. drawing2d;
# Endregion using directives
Public class imageresizer
{
# Region Fields
Static httpserverutility Server = httpcontext. Current. server;
# Endregion Fields
# Region get Encoder
Public static imagecodecinfo getencoder (string mimetype)
{
Foreach (imagecodecinfo Codec in imagecodecinfo. getimageencoders ())
{
If (codec. mimetype = mimetype)
{
Return codec;
}
}
Return NULL;
}
# Endregion get Encoder
# Region resize Image
Public static void resizeimage (string originalimagelocation,
Int width, int height, string newimagelocation)
{
Image originalimage = image. fromfile (
Server. mappath (originalimagelocation. Replace ("//","/")));
Resizeimage (originalimage, width, height, newimagelocation );
}
Public static void resizeimage (image originalimage,
Int width, int height, string newimagelocation)
{
//
// Scale the image depending on whether it is portrait or landscape.
Decimal newwidth;
Decimal newheight;
If (originalimage. width/width)> (originalimage. width/height ))
{
Newwidth = width;
Newheight = (int32) math. Ceiling (convert. todecimal ((
Originalimage. Height * newwidth)/originalimage. width ));
If (newheight> height)
{
Newwidth = newwidth * (height/newheight );
Newheight = height;
}
}
Else
{
Newheight = height;
Newwidth = math. Ceiling (convert. todecimal ((
Originalimage. Width * newheight)/originalimage. Height ));
If (newwidth> width)
{
Newheight = newheight * (width/newwidth );
Newwidth = width;
}
}
//
// Create the new image as a bitmap
Bitmap newbitmap = new Bitmap (convert. toint32 (newwidth ),
Convert. toint32 (newheight), pixelformat. format16bpprgb565 );
Graphics G = graphics. fromimage (newbitmap );
G. interpolationmode = interpolationmode. highqualitybicubic;
G. smoothingmode = smoothingmode. antialias;
G. smoothingmode = smoothingmode. highquality;
G. drawimage (originalimage, 0, 0, convert. toint32 (newwidth ),
Convert. toint32 (newheight ));
//
// Save the image using the appropriate encoder with a quality of 98%
Imagecodecinfo codecencoder = imageresizer. getencoder ("image/JPEG ");
Int Quality = 98;
Encoderparameters encodeparams = new encoderparameters (1 );
Encoderparameter qualityparam = new encoderparameter (encoder. quality, quality );
Encodeparams. Param [0] = qualityparam;
Newbitmap. setresolution (72, 72 );
Newbitmap. Save (server. mappath (newimagelocation), codecencoder, encodeparams );
//
// Clean up
G. Dispose ();
Newbitmap. Dispose ();
Originalimage. Dispose ();
}
# Endregion resize Image
}