将字节数组转换为图像:参数无效
我将图像存储在数据库中,并希望将它们从字节数组转换为图像。将对象转换为字节数组没有问题,但在尝试从字节数组转换为图像时出现“参数无效”错误。我传递给方法的对象来自数据集行。
存储过程
USE [----------------]
GO
/****** Object: StoredProcedure [dbo].[usp_imageloader_add_test] Script Date: 01/16/2012 09:19:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[usp_imageloader_add_test]
@p_Image Image
as
INSERT into Test_Images VALUES(@p_Image)
上传文件控件 /将图像文件转换为字节数组并将数据保存到数据库
protected void btnUpload_Click(object sender, EventArgs e)
{
if (ctrlUpload.PostedFile != null)
{
if (ctrlUpload.PostedFile.ContentLength > 0)
{
// Get Posted File
HttpPostedFile objHttpPostedFile = ctrlUpload.PostedFile;
// Find its length and convert it to byte array
int ContentLength = objHttpPostedFile.ContentLength;
// Create Byte Array
byte[] bytImg = new byte[ContentLength];
// Read Uploaded file in Byte Array
objHttpPostedFile.InputStream.Read(bytImg, 0, ContentLength);
using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
{
try
{
string sql = "usp_imageloader_add_test";
SqlCommand cmd = new SqlCommand(sql, dbConnection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@p_Image", bytImg).SqlDbType = SqlDbType.Image;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
}
}
将对象转换为字节数组并转换为图像
private System.Drawing.Image ObjToImg(object obj)
{
byte[] byteArray;
if (obj == null)
return null;
else
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
byteArray = ms.ToArray(); // Byte Array
ms.Close();
ms = new MemoryStream(byteArray, 0, byteArray.Length);
ms.Seek(0, SeekOrigin.Begin);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
return returnImage;
}
任何想法都可以有帮助。
I am storing images in a database and would like to convert them from byte array to image. I have no problem converting an object to byte array but I get an error of "Parameter is not valid" when trying to convert from byte array to image. The object I am passing to my method is from a dataset row.
Stored procedure
USE [----------------]
GO
/****** Object: StoredProcedure [dbo].[usp_imageloader_add_test] Script Date: 01/16/2012 09:19:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[usp_imageloader_add_test]
@p_Image Image
as
INSERT into Test_Images VALUES(@p_Image)
Upload File control /convert Image file to byte array and save data to database
protected void btnUpload_Click(object sender, EventArgs e)
{
if (ctrlUpload.PostedFile != null)
{
if (ctrlUpload.PostedFile.ContentLength > 0)
{
// Get Posted File
HttpPostedFile objHttpPostedFile = ctrlUpload.PostedFile;
// Find its length and convert it to byte array
int ContentLength = objHttpPostedFile.ContentLength;
// Create Byte Array
byte[] bytImg = new byte[ContentLength];
// Read Uploaded file in Byte Array
objHttpPostedFile.InputStream.Read(bytImg, 0, ContentLength);
using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
{
try
{
string sql = "usp_imageloader_add_test";
SqlCommand cmd = new SqlCommand(sql, dbConnection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@p_Image", bytImg).SqlDbType = SqlDbType.Image;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
}
}
}
Convert object to byte array and to image
private System.Drawing.Image ObjToImg(object obj)
{
byte[] byteArray;
if (obj == null)
return null;
else
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
byteArray = ms.ToArray(); // Byte Array
ms.Close();
ms = new MemoryStream(byteArray, 0, byteArray.Length);
ms.Seek(0, SeekOrigin.Begin);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
return returnImage;
}
Any ideas would be helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请尝试以下操作,您的流可能未从头开始初始化:
它是什么类型的图像?您确定存储的图像有效吗?
另外,只是对使用情况的评论(不会影响您的问题),在处理流时使用
using
语句是一个很好的做法。例如:Try the following, your stream may not be initialized to the beginning:
What type of image is it? Are you sure the image that is stored is valid?
Also just a comment on usage (won't affect your issue), it is good practice to use a
using
statement when working with streams. Eg:凯尔西的解决方案应该有效。这是因为,当您从 byteArray 读取数据到内存流时,指针被放置在流的末尾,现在当您尝试从该内存流读取数据时,它会尝试读取该指针的头部,如下所示此后没有数据,您会收到错误。现在,如果执行
ms.Seek(0, SeekOrigin.Begin);
,则读取器指针将放置在内存流的开头。使用完内存流后将其释放ms.Dispose()
。希望这有帮助。The solution by Kelsey should work. This is because, when you read data from byteArray to memory stream, the pointer is placed at the end of the stream, and now when you try to read data from this memory stream, it tries to read head of this pointer, and as there is no data after this, you get an error. Now if you do
ms.Seek(0, SeekOrigin.Begin);
, the reader pointer is placed at the beginning of the memory stream. And dispose the memory stream when you are done using itms.Dispose()
. Hope this helps.您不需要二进制格式化程序,这会扰乱您的数据,它实际上是用于序列化对象的。
需要注意的关键是该对象已经是一个字节数组,因此您可以直接转换它并使用它。
试试这个:-
You don't need the binary formatter, that's what's messing with your data, it's for serializing objects really.
The key thing to note is that the object is a byte array already so you can just cast it and use that.
Try this:-
Image.FromStream
可能会抛出ArgumentException
因为图像格式无效。期望将随机序列化对象格式化为有效图像是不合理的。Image.FromStream
is probably throwing anArgumentException
because the image format is invalid. Expecting a random serialized object to be formatted as a valid image is not reasonable.您使用的数据是原始 RGB 数据吗?如果是这样,FromStream() 的文档中有一条用户评论,其中提到如果流包含原始 RGB 数据,该方法将抛出异常: http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx(请参见页面底部);它建议使用位图(http://msdn.microsoft.com/en- us/library/zy1a2d14.aspx)。
Is the data you're using raw RGB data? If so, there's a user comment in the docs for FromStream() that mentions that the method will throw if the stream contains raw RGB data: http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx (see the bottom of the page); it recommends using a Bitmap instead (http://msdn.microsoft.com/en-us/library/zy1a2d14.aspx).