C#创建缩略图的操作类源码

将代码过程中经常用的一些代码片段收藏起来,如下的代码段是关于C#创建缩略图的操作类的代码,应该对小伙伴有一些用。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace HtmlSnap
{
public static class ImageHelper
{

public static Image GetThumbnailImage(Image image, int width, int height)
{
if (image == null || width < 1 || height < 1)
return null;

Image bitmap = new System.Drawing.Bitmap(width, height);

using (Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

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

g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

g.Clear(Color.Transparent);

g.DrawImage(image, new Rectangle(0, 0, width, height),
new Rectangle(0, 0, image.Width, image.Height),
GraphicsUnit.Pixel);

return bitmap;
}
}

public static Image GetThumbnailImageKeepRatio(Image image, int width, int height)
{
Size imageSize = GetImageSize(image, width, height);
return GetThumbnailImage(image, imageSize.Width, imageSize.Height);
}

public static Size GetImageSize(Image picture, int percent)
{
if (picture == null || percent < 1)
return Size.Empty;


return GetImageSize(picture, width, height);
}

public static Size GetImageSize(Image picture, int width, int height)
{
if (picture == null || width < 1 || height < 1)
return Size.Empty;

Size imageSize;

imageSize = new Size(width, height);

double heightRatio = (double)picture.Height / picture.Width;
double widthRatio = (double)picture.Width / picture.Height;

int desiredHeight = imageSize.Height;
int desiredWidth = imageSize.Width;


imageSize.Height = desiredHeight;
if (widthRatio > 0)

if (imageSize.Width > desiredWidth)
{
imageSize.Width = desiredWidth;
}

return imageSize;
}


public static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
}

public static ImageCodecInfo GetImageCodecInfo(ImageFormat format)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

foreach (ImageCodecInfo icf in encoders)
{
if (icf.FormatID == format.Guid)
{
return icf;
}
}

return null;
}

public static void SaveImage(Image image, string savePath, ImageFormat format)
{
SaveImage(image, savePath, GetImageCodecInfo(format));
}

private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
{
EncoderParameters parms = new EncoderParameters(1);
EncoderParameter parm = new EncoderParameter(Encoder.Quality, ((long)95));
parms.Param[0] = parm;

image.Save(savePath, ici, parms);
parms.Dispose();
}

}
}




 

posted @ 2021-11-25 15:11  lpyg  阅读(50)  评论(0编辑  收藏  举报