[英]Retrieve decoded binary image from SQL and insert into PDF via iTextsharp asp.net c#
[英]How to retrieve binary image from database using C# in ASP.NET
我需要從數據庫中檢索二進制圖像。
我的疑問如下。
SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyGames;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select blueBallImage from CorrespondingBall WHERE objective = Default Ball", con);
我不知道如何檢索作為二進制圖像的blueBallImage。
成功檢索后,我需要使用包含文本的下拉列表在圖像上添加文本。 代碼如下。
Bitmap bmp = new Bitmap(@"C:\Users\apr13mpsip\Documents\Visual Studio 2012\WebSites\CorrespondingBallWebSite\Images\blueBallDefault.png");
目前,我不知道如何檢索圖像。 因此,我硬編碼了我不想要的東西。 我想從數據庫中檢索它。
Graphics gra = Graphics.FromImage(bmp);
gra.DrawString(ddlCharacter.Text, new Font("Verdana", 18), Brushes.Black, new PointF(4, 6));
MemoryStream ms1 = new MemoryStream();
bmp.Save(ms1, ImageFormat.Png);
var base64Data = Convert.ToBase64String(ms1.ToArray());
imgImage.ImageUrl = "data:image/png;base64," + base64Data;
這是從數據庫快速加載圖像並加載到ASP中的html圖像源的基本示例。 請告訴我它是否適合你;-)
//Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);
foreach (DataRow row in dt.Rows)
{
// Get the byte array from image file
byte[] imgBytes = (byte[]) row["logo"];
// If you want convert to a bitmap file
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes);
string imgString = Convert.ToBase64String(imgBytes);
//Set the source with data:image/bmp
imgLogoCompany.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);
}
你需要創建一個ASP.NET處理程序(* .ASHX)來提供圖像的字節
<img src="ImageHandler.ashx?id=<%=id%>" />
在圖像處理程序中,您需要像這樣編碼
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Load the image (see previous code sample)
byte[] data = Convert.FromBase64String(encodedString);
// Display the image
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.ContentType = "image/JPEG";
}
}
請參閱此以獲取更多信息來自數據庫的圖像
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Connect();
}
try
{
cm = new SqlCommand("select profile_pic from TblNewMemberRegistration where user_name='sudhanshu@mailbox.com'", cn);
byte[] b = (byte[])cm.ExecuteScalar();
stream.Write(b, 0, b.Length);
Bitmap bm = new Bitmap(stream);
Response.ContentType = "image/gif";
bm.Save(Response.OutputStream, ImageFormat.Gif);
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cn.Close();
stream.Close();
}
}
protected void Connect()
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
cn.Open();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.