现有图像的裸数据 ,一个byte[],想要将这个存储像素数据byte数组保存到本地文件中
/// <summary>
/// 像素点阵转换为bitmap
/// </summary>
/// <param name="rawValues">byte[]数组</param>
/// <param name="width">图片的宽度</param>
/// <param name="height">图片的高度</param>
/// <returns>bitmap图片</returns>
public Bitmap ToGrayBitmap(byte[] rawValues, int width, int height)
{
Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
//获取图像参数
bmpData.Stride = width;
int stride = bmpData.Stride; // 扫描线的宽度
int offset = stride - width; // 显示宽度与扫描线宽度的间隙
IntPtr iptr = bmpData.Scan0; // 获取bmpData的内存起始位置
int scanBytes = stride * height;// 用stride宽度,表示这是内存区域的大小
//下面把原始的显示大小字节数组转换为内存中实际存放的字节数组
int posScan = 0, posReal = 0;// 分别设置两个位置指针,指向源数组和目标数组
byte[] pixelValues = new byte[scanBytes]; //为目标数组分配内存
for (int x = 0; x < height; x++)
{
// 下面的循环节是模拟行扫描
for (int y = 0; y < width; y++)
{
pixelValues[posScan++] = rawValues[posReal++];
}
posScan += offset; //行扫描结束,要将目标位置指针移过那段“间隙”
}
System.Runtime.InteropServices.Marshal.Copy(pixelValues, 0, iptr, scanBytes);
bmp.UnlockBits(bmpData); // 解锁内存区域
// 下面的代码是为了修改生成位图的索引表,从伪彩修改为灰度
ColorPalette tempPalette;
using (Bitmap tempBmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format8bppIndexed))
{
tempPalette = tempBmp.Palette;
}
for (int i = 0; i < 256; i++)
{
tempPalette.Entries[i] = System.Drawing.Color.FromArgb(i, i, i);
}
bmp.Palette = tempPalette;
// 算法到此结束,返回结果
return bmp;
}
FileStream fs1 = new FileStream(@”E:\360Downloads\ni.txt”, FileMode.Open, FileAccess.Read, FileShare.Read);
FileStream fs2 = new FileStream(@”E:\360Downloads\ni.txt”, FileMode.Create, FileAccess.Write, FileShare.None);
byte []new_b = new byte[1024];
const int rbuffer=1024;
//fs1.ReadByte(); //读取单个字节,返回-1表示读完
while (fs1.Read(new_b, 0, rbuffer)!=0) //返回0表示读完
{
fs2.Write(new_b, 0, rbuffer);
}
fs1.Close();
fs2.Close();
————————————————
版权声明:本文为CSDN博主「wx910011408」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wx910011408/article/details/80956877
这是拷贝文件的。您可以直接用您的byte数组替换
System.IO.File.WriteAllBytes(
@"D:\test.jpg"
, bytes);//bytes为图片裸数据的byte[]
这个是提取像素区数据的方式
Bitmap bmp = new Bitmap(@"D:\mlstest\67-2.bmp");
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmp.Width * bmp.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
bmp.UnlockBits(bmpData);
有兴趣的朋友可以拿这个rgbValues做一下测试,我这个是黑白图像
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream memorys = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(memorys);
return returnImage;
}