我將圖像存儲在數據庫中,並希望將它們從字節數組轉換爲圖像。我沒有任何問題將對象轉換爲字節數組,但當嘗試從字節數組轉換爲圖像時,出現「參數無效」的錯誤。我傳遞給我的方法的對象來自數據集行。將字節數組轉換爲圖像:參數無效
存儲過程
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;
}
任何想法都會有所幫助。
http://stackoverflow.com/a/6712677/284240二進制數據保存到文件中,看到的圖像編輯器如何響應其 – 2012-01-13 15:57:51