在C#中如何将byte[] 类型转换为图片类型

2025-02-25 07:59:50
推荐回答(4个)
回答1:

在C#中

图片到byte[]再到base64string的转换:

Bitmap bmp = new Bitmap(filepath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string pic = Convert.ToBase64String(arr);

base64string到byte[]再到图片的转换:

byte[] imageBytes = Convert.FromBase64String(pic);
//读入MemoryStream对象
MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
memoryStream.Write(imageBytes, 0, imageBytes.Length);
//转成图片
Image image = Image.FromStream(memoryStream);

现在的数据库开发中:图片的存放方式一般有CLOB:存放base64string

BLOB:存放byte[]

一般推荐使用byte[]。因为图片可以直接转换为byte[]存放到数据库中

若使用base64string 还需要从byte[]转换成base64string 。更浪费性能。

回答2:

我是做.NET开发的人员。。看看我以前的代码吧,希望对你有帮助。。希望采纳。。
public void SevaPhoto(string photoFile)//路径 //添加照片
{
FileStream fs = new FileStream(photoFile,FileMode.Open,FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
byte[] photo = reader.ReadBytes((int)fs.Length);
reader.Close();
fs.Close();

string sql = "update Student set Photo=@photo where Sid='2'";
com = new SqlCommand(sql, conn);
SqlParameter sp = new SqlParameter("@photo",photo);
com.Parameters.Add(sp);
try
{
conn.Open();
com.ExecuteNonQuery();
}
catch (SqlException e)
{

}
finally
{
conn.Close();
}

}
public void ReadPhoto(string photoFile)
{
string sql = "select Photo from Student where Sid='2'";
com = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
byte[] photo = reader[0] as byte[];
FileStream fs = new FileStream(photoFile,FileMode.CreateNew);
fs.Write(photo,0,photo.Length);
fs.Close();
}
reader.Close();
//com.ExecuteNonQuery();
}
catch (SqlException e)
{

}
finally
{
conn.Close();
}
}

回答3:

byte[] b = (byte[])photo(photo是二进制数据)
if (b.Length != 0)
{
image1.ImageUrl= Response.OutputStream.Write(b, 0, b.Length);
}

回答4:

///


/// 将数据转化为24bit图偈,以BGR形式传入数组
///

/// BGR顺序的24bit图像像素数组,byte[0][]为B维,byte[1][]为G维,byte[2]为R维
///
///
/// 图像
unsafe public static Bitmap ReAssemble(byte[][] source, long w, long h) {
if (source == null || source[0].LongLength != w * h || source[1].LongLength != w * h || source[2].LongLength != w * h) return null;
Bitmap bmp=new Bitmap((int)w,(int)h,PixelFormat.Format24bppRgb);
BitmapData bd = bmp.LockBits(new Rectangle(0, 0, (int)w, (int)h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
byte* lp = (byte*)bd.Scan0;
for (long j = 0; j < h; j++)
{
for (long i = 0; i < w; i++)
{
long index = i + j * w;
*lp=source[0][index];
*(lp + 1)=source[1][index];
*(lp + 2) = source[2][index];
lp += 3;
}
lp += bd.Stride - 3 * w;
}
bmp.UnlockBits(bd);
return bmp;
}

请注意,编译这个函数需要在项目-》设置中允许不安全代码,因为这行代码用到了指针