在C#中,可以使用System.Drawing
命名空间中的类(特别是Bitmap
类和Image
类)来处理图像,并将其转换为不同的格式,如JPG、BMP、PNG、GIF等。
转换为JPG
using System.Drawing;
using System.Drawing.Imaging;
// 加载Bitmap对象
Bitmap bitmap = new Bitmap("input.png");
// 保存为JPG
bitmap.Save("output.jpg", ImageFormat.Jpeg);
转换为BMP
// 直接保存为BMP,无需指定ImageFormat,因为Bitmap的默认格式就是BMP
bitmap.Save("output.bmp");
转换为PNG
// 保存为PNG
bitmap.Save("output.png", ImageFormat.Png);
转换为GIF
// 注意:转换为GIF时,如果Bitmap包含的颜色超出了GIF格式的色彩限制,可能会导致颜色损失
bitmap.Save("output.gif", ImageFormat.Gif);
Bitmap转换为jpg、bmp、png、gif图片
调用接口的参数filename(图像路径),后缀带有对应的图片后缀即可
public void SaveBitmapImage(Bitmap bitmap, string filename)
{
try
{
string folder = filename.Substring(0, filename.LastIndexOf("\\"));
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
switch (filename.Substring(filename.LastIndexOf('.')))
{
case ".jpg":
bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".bmp":
bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case ".png":
bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
break;
case ".gif":
bitmap.Save(filename, System.Drawing.Imaging.ImageFormat.Gif);
break;
default:
break;
}
}
Bitmap转换为JPG图片
using System.Drawing;
using System.Drawing.Imaging;
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
return codec;
}
return null;
}
public string GetCurrentSelectImagePath(Bitmap bitmap)
{
string imagePath = string.Empty;
try
{
//转成jpg
var eps = new EncoderParameters(1);
var ep = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L);
eps.Param[0] = ep;
var jpsEncodeer = GetEncoder(ImageFormat.Jpeg);
//保存图片
string dicomDestinationPath = folder + string.Format(CultureInfo.InvariantCulture, "{0:yyyyMMddHHmmssfff}", new object[] { DateTime.Now }) + ".jpg";
bitmap.Save(dicomDestinationPath, jpsEncodeer, eps);
//释放资源
bitmap.Dispose();
ep.Dispose();
eps.Dispose();
imagePath = dicomDestinationPath;
}
catch (Exception ex)
{
//
}
return imagePath;
}
在以上示例中,首先通过Bitmap
构造函数或从文件加载等方式创建一个Bitmap
对象。然后,使用Save
方法并传入目标文件路径及对应的ImageFormat
枚举值来保存图像为不同的格式。
请注意,转换过程可能会有信息丢失(如颜色深度减少或透明度信息丢失),尤其是从高彩色或包含透明度信息的格式转换到低彩色或不支持透明度的格式时。因此,在选择输出格式时,要考虑到这些因素对最终图像效果的影响。