C# Bitmap 转为位图、 ImageSource 转为Bitmap、Bitmap 转 BitmapImage、BitmapImage 转为byte[]、图片压缩
作者:野牛程序员:2023-12-25 12:50:53C#阅读 2353
C#中,可以使用以下代码进行操作:
Bitmap 转为位图:
using System.Drawing; Bitmap bitmap = new Bitmap("path/to/your/image.jpg");
ImageSource 转为 Bitmap:
// 假设 imageSource 是你的 ImageSource 对象 Bitmap bitmap = new Bitmap(new System.Drawing.Bitmap(new System.Windows.Media.Imaging.BitmapImage(new Uri(imageSource.ToString()))));
Bitmap 转 BitmapImage:
using System.Windows.Media.Imaging; Bitmap bitmap = new Bitmap("path/to/your/image.jpg"); BitmapImage bitmapImage = new BitmapImage(); using (MemoryStream memory = new MemoryStream()) { bitmap.Save(memory, ImageFormat.Png); memory.Position = 0; bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); } // 现在 bitmapImage 包含了 Bitmap 转换后的图像
BitmapImage 转为 byte[]:
BitmapImage bitmapImage = new BitmapImage(new Uri("path/to/your/image.jpg")); byte[] imageBytes; using (MemoryStream memoryStream = new MemoryStream()) { JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapImage)); encoder.Save(memoryStream); imageBytes = memoryStream.ToArray(); }
图片压缩:
private byte[] CompressImage(string imagePath, long quality) { using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) { using (MemoryStream ms = new MemoryStream()) { System.Drawing.Image image = System.Drawing.Image.FromStream(fs); EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; image.Save(ms, jpegCodec, encoderParams); return ms.ToArray(); } } } private ImageCodecInfo GetEncoderInfo(string mimeType) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType == mimeType) { return codec; } } return null; }
上述代码提供了一些常见的图片处理操作,包括将 Bitmap 转为位图、ImageSource 转为 Bitmap、Bitmap 转 BitmapImage、BitmapImage 转为 byte[] 以及图片压缩。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892