一、读取图像为位图
C# 从指定路径读取图片源、Bitmap与ImageSource互转、Bitmap与BitmapImage互转、BitmapImage转为byte[]、图片压缩_c# imagesource bitmap-CSDN博客
二、Bitmap图像通过内存保存为raw图像
在C#中,将Bitmap
图像保存为RAW格式通常涉及到直接访问图像的像素数据并将其写入到一个二进制流中,因为.NET Framework或.NET Core/Standard库本身并不直接支持RAW图像格式的保存。下面是一个基本示例,说明如何从Bitmap
中提取原始像素数据并保存为简单的RAW格式文件。请注意,RAW格式没有统一的标准,实际应用中可能需要根据具体需求调整格式。
System.Drawing.Bitmap bitBufferRGB = new System.Drawing.Bitmap("Bitmap.jpg");
System.Drawing.Imaging.BitmapData data = bitBufferRGB.LockBits(
new System.Drawing.Rectangle(System.Drawing.Point.Empty, bitBufferRGB.Size),
System.Drawing.Imaging.ImageLockMode.ReadWrite, bitBufferRGB.PixelFormat);
//获取内存
IntPtr pData = data.Scan0;
int width = bitBufferRGB.Width;
int height = bitBufferRGB.Height;
if (bitBufferRGB.PixelFormat == PixelFormat.Format8bppIndexed)
{
byte[] laterData = new byte[width * height];
System.Runtime.InteropServices.Marshal.Copy(pData, laterData, 0, width * height);
File.WriteAllBytes("D:\\DICOM\\" + string.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now) + "image.raw", laterData);
}
else if (bitBufferRGB.PixelFormat == PixelFormat.Format24bppRgb)
{
byte[] laterData = new byte[width * height * 3]; // 注意这里,我们按照每个像素3字节来计算数组的大小
System.Runtime.InteropServices.Marshal.Copy(pData, laterData, 0, width * height * 3); // 注意这里,我们按照每个像素3字节来复制数据
File.WriteAllBytes("D:\\DICOM\\" + string.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now) + "image.raw", laterData);
}
//解锁及释放资源
bitBufferRGB.UnlockBits(data);
bitBufferRGB.Dispose();
三、完整示例
using System;
using System.Drawing;
using System.Drawing.Imaging;
public class BitmapToRaw
{
public static void SaveBitmapAsRaw(Bitmap bitmap, string fileName)
{
// 获取Bitmap的像素格式
PixelFormat format = bitmap.PixelFormat;
// 锁定Bitmap以便直接访问其像素数据
BitmapData data = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly,
format);
// 计算每一行像素数据的字节数(注意可能会有字节对齐)
int bytesPerPixel = Image.GetPixelFormatSize(format) / 8;
int stride = data.Stride;
// 创建一个新的字节数组来保存像素数据
byte[] pixels = new byte[stride * bitmap.Height];
// 将像素数据复制到新数组中
Marshal.Copy(data.Scan0, pixels, 0, pixels.Length);
// 解锁Bitmap
bitmap.UnlockBits(data);
// 写入RAW文件
using (var stream = new FileStream(fileName, FileMode.Create))
{
// 直接写入像素数据
stream.Write(pixels, 0, pixels.Length);
}
}
public static void Main()
{
// 示例:从Bitmap对象保存为RAW文件
Bitmap bitmap = new Bitmap("path_to_your_image.jpg");
SaveBitmapAsRaw(bitmap, "output.raw");
Console.WriteLine("Bitmap已保存为RAW格式.");
}
}