Datareader not reading image value - c#

i am using datareader at page load to read and store database values in variables, my table includes both nvarchar and image type columns. At page load my 5 images value in database is not read by reader but others are perfectly read.
Byte[] img1 = null;
Byte[] img2 = null;
Byte[] img3 = null;
Byte[] img4 = null;
Byte[] img5 = null;
SqlConnection con = new SqlConnection("Data Source=RAJ-PC\\SQLEXPRESS;Initial Catalog=Finder;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadad();
}
}
protected void loadad()
{
SqlCommand cmd = new SqlCommand("sps_addetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ad_id", ad_id);
cmd.Parameters.AddWithValue("#useremail", ses);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
rd_iam.SelectedValue = reader["iam"].ToString();
dd_category.SelectedValue = reader["category"].ToString();
c = Convert.ToInt16(reader["category"].ToString());
dd_subcategory.SelectedValue = reader["subcategory"].ToString();
txt_title.Text = reader["title"].ToString();
txt_description.Text = reader["description"].ToString();
txt_pername.Text = reader["contactname"].ToString();
txt_mobile1.Text = reader["mobile1"].ToString();
txt_mobile2.Text = reader["mobile2"].ToString();
txt_landline1.Text = reader["landline1"].ToString();
txt_landline2.Text = reader["landline2"].ToString();
txt_email1.Text = reader["email1"].ToString();
txt_email2.Text = reader["email2"].ToString();
txt_website.Text = reader["website"].ToString();
dd_country.Text = reader["country"].ToString();
d = Convert.ToInt16(reader["country"].ToString());
dd_state.Text = reader["state"].ToString();
txt_pincode.Text = reader["pincode"].ToString();
txt_address.Text = reader["address"].ToString();
txt_lat.Text = reader["latitude"].ToString();
txt_lon.Text = reader["longitude"].ToString();
img1 = (byte[])reader["image1"];
img2 = (byte[])reader["image2"];
img3 = (byte[])reader["image3"];
img4 = (byte[])reader["image4"];
img5 = (byte[])reader["image5"];
}
con.Close();
}
And stored procedure sps_addetails is
ALTER PROCEDURE [dbo].[sps_addetails]
#ad_id int,
#useremail nvarchar(100)
AS
BEGIN
select * from dbo.tbl_adregister where useremail=#useremail and ad_id=#ad_id
END
aspx
<asp:FileUpload ID="FileUpload1" runat="server" />
update button functionality is (aspx.cs)
Byte[] imgbytes1 = null;
if (FileUpload1.HasFile)
{
HttpPostedFile file1 = FileUpload1.PostedFile;
imgbytes1 = new Byte[file1.ContentLength];
file1.InputStream.Read(imgbytes1, 0, file1.ContentLength);
}
else
{
imgbytes1 = img1;
}
con.Open();
SqlCommand cmd = new SqlCommand("sps_uploadphoto", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#imagedata1", imgbytes1);
cmd.ExecuteNonQuery();
con.Close();

Try first determining the image size, then instantiating the variables, and then use the GetBytes() method:
int index = reader.GetOrdinal("image1");
Int64 size = 0;
try { size = reader.GetBytes(index , 0, null, 0, int.MaxValue); }
catch { size = reader.GetBytes(index, 0, img1, 0, 1); }
img1 = new Byte[size];
reader.GetBytes(index, 0, img1, 0, img1.Length);
... rinse and repeat for images 2 through 5 ...
Let us know if that gets it for you.

Reading image value is different from others...
<img runat="server" id="image1" alt="" src="" height="100" width="100" />
protected void LoadImage1()
{
SqlCommand cmd = new SqlCommand("sps_getimage", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#flag", 1);
cmd.Parameters.AddWithValue("#ad_id", ad_id);
con.Open();
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
if (reader.HasRows)
{
reader.Read();
MemoryStream memory = new MemoryStream();
long startIndex = 0;
const int ChunkSize = 256;
while (true)
{
byte[] buffer = new byte[ChunkSize];
long retrievedBytes = reader.GetBytes(0, startIndex, buffer, 0, ChunkSize);
memory.Write(buffer, 0, (int)retrievedBytes);
startIndex += retrievedBytes;
if (retrievedBytes != ChunkSize)
break;
}
byte[] data = memory.ToArray();
img1 = data;
memory.Dispose();
image1.Src = "data:image/png;base64," + Convert.ToBase64String(data);
}
con.Close();
}

Related

Values from textBox not getting inserted into database C#

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/losefound/{0}.png", imageName);
string ItemName = txtItemName.Text;
string Place = txtPlace.Text;
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(#ItemName, #FoundAt, #TimeIn, #ImageName, #ContentType, #Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#ItemName", ItemName);
cmd.Parameters.AddWithValue("#FoundAt", Place);
cmd.Parameters.AddWithValue("#TimeIn", DateTime.Now);
cmd.Parameters.AddWithValue("#ImageName", imageName);
cmd.Parameters.AddWithValue("#ContentType", "image/png");
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
}
private static byte[] ConvertHexToBytes(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
[WebMethod(EnableSession = true)]
public static string GetCapturedImage()
{
string url = string.Empty;
int imageId = Convert.ToInt32(HttpContext.Current.Session["CapturedImageId"]);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Data FROM LostFound WHERE Id = #Id";
cmd.Parameters.AddWithValue("#Id", imageId);
cmd.Connection = con;
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
url = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
con.Close();
}
}
HttpContext.Current.Session["CapturedImageId"] = null;
return url;
}
protected void btnCapture_Click(object sender, EventArgs e)
{
}
}
The values form the textbox never inserted into the database. only
datetime.now, imageName, contentType and data can be inserted.
should the insert textbox query at btncapture?
Can someone guide me where am I going wrong?
This code should at least be in a button click.
By the time the page_load event is called in the asp.net page event life cycle the TextBoxes will have been cleared.
You're only submitting to DB if it's not a postback.
if (!this.IsPostBack)
Since you're only running this in Page_Load, the textfields will probably not have any user inputs, and is therefore blank. Either you can do it on PostBack.
if (this.IsPostBack)
{
// Do stuff
}
Or, even better, do as Jeremy Thompson suggested and assign an event handler when the user clicks a button. Doing this kind of logic in Page_Load often come back and haunt you later. What happens when some other developer adds an UpdatePanel, or another postback event? Then this code will run at every postback. It will not scale very good. It seems as you already got an event handler for this - btnCapture_Click, I suggest that you use it.
Example:
In your HTML:
<asp:Button ID="Button1" runat="server" onclick="btnCapture_Click" Text="Button" />
And in your CS:
protected void btnCapture_Click(object sender, EventArgs e)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/losefound/{0}.png", imageName);
string ItemName = txtItemName.Text;
string Place = txtPlace.Text;
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
string query = "INSERT INTO LostFound (ItemName, FoundAt, TimeIn, ImageName, ContentType, Data) VALUES(#ItemName, #FoundAt, #TimeIn, #ImageName, #ContentType, #Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#ItemName", ItemName);
cmd.Parameters.AddWithValue("#FoundAt", Place);
cmd.Parameters.AddWithValue("#TimeIn", DateTime.Now);
cmd.Parameters.AddWithValue("#ImageName", imageName);
cmd.Parameters.AddWithValue("#ContentType", "image/png");
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
If you're having trouble binding the button you can take a look at this question.
First, check if you have AutoEventWireup="true" in the declaration of your aspx.
You can also try to manually assigning the delegate.
btnCapture += new EventHandler(btnCapture_Click);

how to retrieve image from database into picturebox in c#

private void view_Load(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SOFT;Initial Catalog=Dev01;Integrated Security=True";
con.Open();
//Retrieve BLOB from database into DataSet.
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select * from empdetails", con);
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
lbl_fname.Text = myReader["firstname"].ToString();
lbl_mname.Text = myReader["middlename"].ToString();
lbl_lname.Text = myReader["lastname"].ToString();
lbl_gender.Text = myReader["gender"].ToString();
lbl_dob.Text = myReader["dob"].ToString();
lbl_qualification.Text = myReader["qualification"].ToString();
lbl_skills.Text = myReader["skills"].ToString();
lbl_userid.Text = myReader["username"].ToString();
lbl_pwd.Text = myReader["password"].ToString();
lbl_cpwd.Text = myReader["confirmpassword"].ToString();
lbl_mno.Text = myReader["mobilenumber"].ToString();
lbl_altmno.Text = myReader["alternativenumber"].ToString();
lbl_email.Text = myReader["email"].ToString();
lbl_presentadd.Text = myReader["presentaddress"].ToString();
lbl_permanentadd.Text = myReader["permanentaddress"].ToString();
}
myReader.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "empdetails");
int c = ds.Tables["empdetails"].Rows.Count;
if (c > 0)
{
//BLOB is read into Byte array, then used to construct MemoryStream,
//then passed to PictureBox.
//SqlCommand cmd1=new SqlCommand("Select photo from empdetails");
Byte[] bytedata = new Byte[0];
bytedata = (Byte[])(ds.Tables["empdetails"].Rows[c - 1]["photo"]);
MemoryStream ms = new MemoryStream(bytedata);
pictureBox1.Image = Image.FromStream(ms,true); //HERE I AM GETTING ERROR
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I already checked various pages but that didn't solve my problem. I am getting an error only in this part:
"pictureBox1.Image = Image.FromStream(ms,true);"
The data type of your column should be image try
public byte[] ConvertImageToByte(Image image, ImageFormat format)
{
var stream = new MemoryStream();
image.Save(stream, format);
return stream.ToArray();
}
public Image ConvertBytesToImage(object _image)
{
byte[] byteImage = (byte[])(_image);
MemoryStream ms = new MemoryStream(byteImage);
ms.Write(byteImage, 0, byteImage.Length);
Image img = Image.FromStream(ms);
return img;
}
Saving the byte in your database
OpenFileDialog file = new OpenFileDialog();
file.Title = "Please Select the Employee Photo (Dimension 128x128)";
file.Filter = "JPEG Files|*.jpg|Bitmap Files|*.bmp|Gif Files|*.gif|PNG Files|*.png";
file.DefaultExt = "jpg";
file.ShowDialog();
if (!string.IsNullOrEmpty(file.FileName))
{
byte[] bytePhoto = ConvertImageToBytes(Image.FromFile(file.FileName), ImageFormat.Png);
//bytePhoto is the object to save in your database
}
Retrieve the byte and display as image
byte[] bytePhoto = (byte[])ds.Tables["empdetails"].Rows[0]["Photo"];
pictureBox1.Image = ConvertBytesToImage(bytePhoto);

Displaying image from database on an image button in a web form

I am trying to make am image from a database appear on an image button on a web form. There is no error message but the image is not appearing. Only a small small indicating that appears on the image button but not the image from the database....
My handler is here:
public void ProcessRequest (HttpContext context)
{
Int32 Member_No;
if (context.Request.QueryString["id"] != null)
{
Member_No = Convert.ToInt32(context.Request.QueryString["id"]);
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(Member_No);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
else
{
context.Response.Write("No Image Found");
}
}
public bool IsReusable
{
get
{
return false;
}
}
public Stream ShowEmpImage(int Member_No)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("Select Photo from Members where Member_No = #ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", Member_No);
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
con.Close();
}
}
}
I would just return the byte[] from execute scalar and write the bytes to the stream.
public byte[] ShowEmpImage(int Member_No)
{
var settings = ConfigurationManager.ConnectionStrings["MyServer"];
using(var con = new SqlConnection(settings.ConnectionString))
using(var cmd = new SqlCommand("Select Photo from Members where Member_No = #ID", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ID", Member_No);
return (byte[])cmd.ExecuteScalar();
}
}
var image = ShowEmpImage(Member_No);
context.Response.WriteBytes(image);
context.Response.ContentType = "image/jpg";
BTW: I would also wrap your ado.net components in using blocks to prevent memory leaks.

resizeing image . . . .

hi thanks a lot i have one code below in this code ill upload one image . convert it into
byte code and store it in database .. and retrive it in gridview .. the thing is before
converting it into byte code i want to resize it could u plz tell me what code i should insert here ... thanks a lot .. ...
protected void btnUpload_Click(object sender, EventArgs e)
{
string strID= txtid.Text.ToString();
string strImageName = txtName.Text.ToString();
if (FileUpload1.PostedFile != null &&
FileUpload1.PostedFile.FileName != "")
{
byte[] imageSize = new byte
[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read
(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection con = new SqlConnection("user id=sa;password=Zoomin#123;database=salary_db;server=192.168.1.100");
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO image1(ID,ImageName,Image)" +
" VALUES (#ID,#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ID = new SqlParameter
("#ID", SqlDbType.VarChar, 50);
ID.Value = strID.ToString();
cmd.Parameters.Add(ID);
SqlParameter ImageName = new SqlParameter
("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter
("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
GridView1.DataBind();
}}
You could use the following function:
public void ResizeImage(double scaleFactor, Stream fromStream, Stream toStream)
{
using (var image = Image.FromStream(fromStream))
{
var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);
using (var thumbnailBitmap = new Bitmap(newWidth, newHeight))
using (var thumbnailGraph = Graphics.FromImage(thumbnailBitmap))
{
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
thumbnailBitmap.Save(toStream, image.RawFormat);
}
}
}
The name of the parameters should be pretty self-explanatory.
Have a look at
Resize an Image C#

How to display images with fixed dimensions in ASP.NET after retrieving them from a MySQL database

Following are the links which describe connection to MySQL:
http://www.codeproject.com/KB/aspnet/asp_net_and_mysql.aspx
http://www.codeproject.com/KB/aspnet/image_asp.aspx
Here is the code to display image from mysql database:
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
// string commantext = "select img_id,img_file,img_type,img_name from image";
// DataSet ds = MySqlHelper.ExecuteDataset(conn, commantext);
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
// DataTable dt = ds.Tables[0];
DataTable dt = GetData(cmd);
while(dt !=null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
// Byte[] bytes = (Byte[])dt.Rows[1][] ;
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["img_type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["img_name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
conn.Close();
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
My code to upload image file to mysql database is as below.
protected void Button1_Click(object sender, EventArgs e)
{
Stream img_strm = File1.PostedFile.InputStream;
int img_len = File1.PostedFile.ContentLength;
string strtype = File1.PostedFile.ContentType;
//code snippet to determine image height and width.
System.Drawing.Image i = System.Drawing.Image.FromStream(img_strm);
int fileheight = int.Parse(i.Width.ToString());
int filewidth = int.Parse(i.Height.ToString());
strname = Text1.Value;
//Session["t"] = strname;
byte[] imgData = new byte[img_len];
int n = img_strm.Read(imgData, 0, img_len);
int result = saveToDb(strname, imgData, strtype);
}
private int saveToDb(string imgName, byte[] imgbin, string imgContenttype)
{
string db = "server=localhost;database=test;uid=root;password=techsoft";
MySqlConnection conn = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand("insert into image(img_name,img_file,img_type) values(?img_name,?img_file,?img_type)", conn);
//MySqlParameter param0 = new MySqlParameter("?img_id", MySqlDbType.Int16, 20);
//param0.Value = ;
//cmd.Parameters.Add(param0);
MySqlParameter param0 = new MySqlParameter("?img_name", MySqlDbType.VarChar, 45);
param0.Value = imgName;
cmd.Parameters.Add(param0);
// MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.VarChar, 45);
MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.LongBlob, 10);
param1.Value = imgbin;
cmd.Parameters.Add(param1);
MySqlParameter param2 = new MySqlParameter("?img_type", MySqlDbType.VarChar, 45);
param2.Value = imgContenttype;
cmd.Parameters.Add(param2);
conn.Open();
int num = cmd.ExecuteNonQuery();
conn.Close();
return num;
}
I have used binary writer to display. Can anybody suggest how to display images in fixed dimensions?
I would resize the images on the page being used to display them. Where are they being displayed?
or
I would resize the images at the time they are saved
Assuming your only challenge is to only scale the images(either before uploading or when retrieving them)...here is some code i use to get scaled dimensions for an image (to fit specific fixed dimensions)...you can stick this somewhere in an imaging class
Note that there are many approaches...
public static Size getScaledDimensions( Image img, Int32 maxW, Int32 maxH)
{
//check if image is already within desired dimensions
if (img.Height <= maxH & img.Width <= maxW)
{
Size orgsize = new Size(img.Width, img.Height);
return orgsize; // no need to rescale
}
else //proceed with rescaling
{
int finalH;
int finalW;
//use height/width ratio to determine our new dimensions
double hwRatio = (double)img.Height / (double)img.Width;
int newW = (int) (maxH/ hwRatio);
int newH = (int) (hwRatio * maxW);
//make sure we scale the right dimension
if (newW <= maxW) // scale width
{
finalH = maxH;
finalW = newW;
}
else
{ // scale height
finalH = newH;
finalW = maxW;
}//end if
Size newsize = new Size(finalW, finalH);
return newsize;
}
Thanks for all the support from rip and The_AlienCoder for their answers. I have found out answer to my own query.
We need to use streams to convert binary data from mysql database. Later graphic library should be used to load the streams. In the meantime we need to resize the image according to our need.
protected void Page_Load(object sender, EventArgs e){
//Create connection to mysql database.
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
//create datatable. GetData is a method to fetch the data.
DataTable dt = GetData(cmd);
//Get data from database to bytes.
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
//Defining the size to display data.
int outputSize = 100;
if (bytes.Length > 0)
{
// Open a stream for the image and write the bytes into it
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes, true);
stream.Write(bytes, 0, bytes.Length);
Bitmap bmp = new Bitmap(stream);
Size new_size = new Size();
//resize based on the longer dimension
if (bmp.Width > bmp.Height)
{
new_size.Width = outputSize;
new_size.Height = (int)(((double)outputSize / (double)bmp.Width) * (double)bmp.Height);
}
else
{
new_size.Width = (int)(((double)outputSize / (double)bmp.Height) * (double)bmp.Width);
new_size.Height = outputSize;
}
Bitmap bitmap = new Bitmap(new_size.Width, new_size.Height, bmp.PixelFormat);
Graphics new_g = Graphics.FromImage(bitmap);
new_g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
new_g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
new_g.DrawImage(bmp, -1, -1, bitmap.Width + 1, bitmap.Height + 1);
bmp.Dispose();
bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
new_g.Dispose();
stream.Close();
}
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager .ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
}

Categories