C\#jpg 미리 보기 함수 코드

 
/// <summary>
/// jpg , , ,
/// , ^_^
/// </summary>
/// <param name="originalImagePath"> </param>
/// <param name="quality"> 0-100</param>
/// <param name="width"> </param>
/// <param name="height"> </param>
/// <param name="mode"> :HW,W,H,Cut</param>
/// <returns></returns>
public static byte[] MakeJPGThumbnailBytes(string originalImagePath, long quality, int width, int height, string mode)
{
Image originalImage = Image.FromFile(originalImagePath);
MemoryStream s = new MemoryStream();
int towidth = width;
int toheight = height;

int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case "HW":// ( )
break;
case "W":// ,
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H":// ,
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut":// ( )
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}

// bmp
Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

//
Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

// ,
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//
g.Clear(Color.Transparent);

//
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);

try
{
// jpg
EncoderParameters eps = new EncoderParameters(1);
EncoderParameter ep = new EncoderParameter(Encoder.Quality,quality);
eps.Param[0] = ep;
bitmap.Save(s, GetCodecInfo("image/jpeg"), eps);
return s.GetBuffer();
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
s.Dispose();
g.Dispose();
}
}

/**/
/// <summary>
/// JPG
/// </summary>
/// <param name="mimeType"></param>
/// <returns> mimeType ImageCodecInfo</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
}

좋은 웹페이지 즐겨찾기