SoFunction
Updated on 2025-03-07

C# jpg thumbnail function code


/// <summary>
/// Generate jpg thumbnail bytes, a function that I need to use in my small software, so I made a function myself to share with you
/// Why do you need to generate bytes instead of files? This is for the convenience of subsequent processing^_^
/// </summary>
/// <param name="originalImagePath">original path</param>
/// <param name="quality">Quality 0-100</param>
/// <param name="width">width</param>
/// <param name="height">height</param>
/// <param name="mode">Mode: HW,W,H,Cut</param>
/// <returns></returns>
public static byte[] MakeJPGThumbnailBytes(string originalImagePath, long quality, int width, int height, string mode)
{
Image originalImage = (originalImagePath);
MemoryStream s = new MemoryStream();
int towidth = width;
int toheight = height;

int x = 0;
int y = 0;
int ow = ;
int oh = ;

switch (mode)
{
case "HW"://Specify high-width scaling (may be deformed)
break;
case "W"://Specify width, height according to proportion
toheight = * width / ;
break;
case "H"://Specify height, width according to proportion
towidth = * height / ;
break;
case "Cut"://Specify the height and width cut (no deformation)
if ((double) / (double) > (double)towidth / (double)toheight)
{
oh = ;
ow = * towidth / toheight;
y = 0;
x = ( - ow) / 2;
}
else
{
ow = ;
oh = * height / towidth;
x = 0;
y = ( - oh) / 2;
}
break;
default:
break;
}

// Create a new bmp image
Image bitmap = new (towidth, toheight);

// Create a new drawing board
Graphics g = (bitmap);

//Set high-quality interpolation method
= .;

//Set high quality and low speed to show smoothness
= .;

//Clear the canvas and fill it with transparent background color
();

//Draw the specified part of the original picture at the specified position and according to the specified size
(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
);

try
{
//Save thumbnails in jpg format
EncoderParameters eps = new EncoderParameters(1);
EncoderParameter ep = new EncoderParameter(,quality);
[0] = ep;
(s, GetCodecInfo("image/jpeg"), eps);
return ();
}
catch ( e)
{
throw e;
}
finally
{
();
();
();
();
}
}

/**/
/// <summary>
/// Use when saving JPG
/// </summary>
/// <param name="mimeType"></param>
/// <returns>Get ImageCodecInfo for the specified mimeType</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ();
foreach (ImageCodecInfo ici in CodecInfo)
{
if ( == mimeType) return ici;
}
return null;
}