How to convert string to image? - c#

private void btnread_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT imagecol FROM imgtable WHERE id = 17";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);`enter code here`
DataTable dt = new DataTable();
adap.Fill(dt);
string b = dt.Rows[0]["imagecol"].ToString();
byte[] storedImage = System.Text.Encoding.ASCII.GetBytes(b);
byte[] ss = (byte[])dt.Rows[0]["imagecol"];
Image newImage;
using (MemoryStream stream = new MemoryStream(storedImage))
{
newImage = Image.FromStream(stream);
}
//// Display to make sure code works
picbox.Image = newImage;
connection.Close();
}

You don't need to convert to byte[] to string then back to byte[] using ASCII.GetBytes.
This should solve your problem.
using (MemoryStream stream = new MemoryStream(ss))
{
newImage = Image.FromStream(stream);
}
Side note: Give proper names for members even when you write a sample application. ss is not meaningful.

Related

Is there any shortest way to retrieve and upload image from database using c# wpf?

I have this code below that works fine. I am trying to upload and retrieve image from my database from tutorial but when I modify it with data from my database, it keeps showing Argument exception to this part
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
with an error of for system.drawing dll
It can upload but can't show the image uploaded
DataSet ds;
string strName, imageName;
string constr = "Data Source=192.168.0.102;Initial Catalog=db_RVManzan;User ID=RVMserver;Password=rvmadmin";
public sample()
{
InitializeComponent();
BindImageList();
}
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
try
{
FileDialog fldlg = new OpenFileDialog();
fldlg.InitialDirectory = Environment.SpecialFolder.MyPictures.ToString();
fldlg.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
fldlg.ShowDialog();
{
strName = fldlg.SafeFileName;
imageName = fldlg.FileName;
ImageSourceConverter isc = new ImageSourceConverter();
image1.SetValue(Image.SourceProperty, isc.ConvertFromString(imageName));
}
fldlg = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
insertImageData();
}
private void btnShow_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = ds.Tables[0];
foreach (DataRow row in dataTable.Rows)
{
if (row[1].ToString() == cbImages.SelectedItem.ToString())
{
//Store binary data read from the database in a byte array
byte[] blob = (byte[])row[43];
MemoryStream stream = new MemoryStream();
stream.Write(blob, 0, blob.Length);
stream.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
image2.Source = bi;
}
}
}
private void insertImageData()
{
try
{
if (imageName != "")
{
//Initialize a file stream to read the image file
FileStream fs = new FileStream(imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
//Close a file stream
fs.Close();
string sql = "update Employees set Emppic ='" + imgByteArr + "'";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Image added successfully.");
BindImageList();
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BindImageList()
{
try
{
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", conn))
{
ds = new DataSet("myDataSet");
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
cbImages.Items.Clear();
foreach (DataRow dr in dt.Rows)
cbImages.Items.Add(dr["Empid"].ToString());
cbImages.SelectedIndex = 0;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Please let me know if I am unable to explain the questions. Thanks
The intermediate System.Drawing.Image is redundant. You could directly load a BitmapImage from blob by
BitmapImage bi = new BitmapImage();
using (var stream = new MemoryStream(blob))
{
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = stream;
bi.EndInit();
}
image2.Source = bi;

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);

Getting error after updating image in Sql server 2008 database

I am developing a winform application in VS 2010 C#.
I have developed a form to insert and update the user details in this.
My Update user form is as below image
![Update User Screen][1]
http://i.stack.imgur.com/iZaAJ.png
And coding to update is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Drawing.Imaging;
using System.IO;
namespace SampleApplication
{
public partial class UserUpdate : Form
{
public UserUpdate()
{
InitializeComponent();
}
SqlDataAdapter da;
SqlConnection con = new SqlConnection("user id=sa; password=123;initial catalog=Inventory;data source=Aniket-PC");
SqlCommand cmd;
MemoryStream ms;
byte[] photo_array;
DataSet ds;
int rno = 0;
string str;
private void nameTxt_Validating(object sender, CancelEventArgs e)
{
if (nameTxt.Text.Trim().Length == 0)
{
namewarning.Visible = true;
}
else
{
namewarning.Visible = false;
}
}
private void Update_Load(object sender, EventArgs e)
{
contTxt.MaxLength = 10;
retriveData();
retriveImg();
}
void retriveImg()
{
con.Open();
cmd = new SqlCommand("Select Logo from Register where UserName='" + uNameTxt.Text + "'", con);
da = new SqlDataAdapter(cmd);
ds = new DataSet("MyImage");
da.Fill(ds, "MyImage");
DataRow myRow;
myRow = ds.Tables["MyImage"].Rows[0];
photo_array = (byte[])myRow["Logo"];
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
con.Close();
}
void retriveData()
{
con.Open();
cmd = new SqlCommand("Select * from Register where UserName='"+uNameTxt.Text+"'",con);
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
nameTxt.Text = (read["Name"].ToString());
passTxt.Text = (read["Password"].ToString());
conPassTxt.Text = (read["Password"].ToString());
emailTxt.Text = (read["EmailId"].ToString());
addTxt.Text = (read["Address"].ToString());
contTxt.Text = (read["ContactNo"].ToString());
DORTxt.Text = (read["DOR"].ToString());
validity.Text = "Account Valid till "+(read["Validity"].ToString());
}
read.Close();
con.Close();
}
private void AttachBtn_Click(object sender, EventArgs e)
{
// Open image by OpenFiledialog and show it in PicturBox.
try
{
//filter only image format files.
openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openFileDialog1.ShowDialog();
if (res == DialogResult.OK)
{
Image img = new Bitmap(openFileDialog1.FileName);
//inserting image in PicturBox
profPic.Image = img.GetThumbnailImage(127, 128, null, new IntPtr());
openFileDialog1.RestoreDirectory = true;
}
}
catch
{
MessageBox.Show("Cannot upload image");
}
}
private void UpdateBtn_Click_1(object sender, EventArgs e)
{
string DOM = dateTimePicker1.Value.ToShortDateString();
if (namewarning.Visible == true || picError.Visible == true || PassError.Visible == true || emailwarningImg.Visible == true)
{
MessageBox.Show("Please correct the marked fields");
}
else
{
//cmd = new SqlCommand("update Register set (Name,Password,EmailId,Address,ContactNo,Logo,DOM) values('" + nameTxt.Text.Trim() + "','" + passTxt.Text.Trim() + "','" + emailTxt.Text.Trim() + "','" + addTxt.Text.Trim() + "','" + contTxt.Text.Trim() + "',#Logo,'" + DOM+ "')", con);
str = string.Format("update Register set Name='{0}', Password='{1}',EmailID='{2}',Address='{3}',ContactNo='{4}',Logo='{5}',DOU='{6}' where UserName='{7}'", nameTxt.Text.Trim(), passTxt.Text.Trim(), emailTxt.Text.Trim(),addTxt.Text.Trim(), contTxt.Text.Trim(), #"Logo" ,DOM,uNameTxt.Text);
con_photo();
//con.Open();
cmd = new SqlCommand(str, con);
int count= cmd.ExecuteNonQuery();
if (count > 0)
MessageBox.Show("Sucsess");
else
MessageBox.Show("need to work");
}
}
void con_photo()
{
if (profPic.Image != null)
{
ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_array = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_array, 0, photo_array.Length);
cmd.Parameters.AddWithValue("#Logo", photo_array);
}
}
when i run the application it executes very well and shows me success message but when i again try to view the update user form it shows below screenshot error
http://i.stack.imgur.com/7z1Rx.png
at retriveImg ()
Please help me with resolution for this..
You're not passing the image bytes to the UPDATE command, but a string containing the word Logo.
Also: PLEASE avoid creating SQL commands using string concatenation or String.Format. Use parameterized queries instead!
Also: Do not use an NVARCHAR field to store the image bytes (unless you create a BASE64 string from them first), but use a VARBINARY or IMAGE column instead.
The problem is in the following line:
str = string.Format("update Register set ... ,Logo='{5}' ...", ..., #"Logo", ...);
As you can see, you're formatting a string, but you don't insert the bytes from the image, but the word "Logo".
Assuming the column Logo was of type IMAGE or VARBINARY, I would write something like this:
byte[] photo_array = null;
if (profPic.Image != null)
{
MemoryStream ms = new MemoryStream();
profPic.Image.Save(ms, ImageFormat.Jpeg);
photo_array = ms.GetBuffer();
}
if (photo_array != null)
{
SqlCommand cmd = new SqlCommand("UPDATE Register SET Logo=#logo", connection);
cmd.Parameters.AddWithValue("#logo", imageBytes);
cmd.ExecuteNonQuery();
}
Maybe I'm wrong but I'll try to do this
photo_array = (byte[])myRow["Logo"];
if photo_array.length.trim()>0
{
ms = new MemoryStream(photo_array);
profPic.Image = Image.FromStream(ms);
}
con.Close();
This error may come when the lenght of the string is 0
Another thing is that you're not saving the image in the database
//C# Code
SqlCommand cmdSelect = new SqlCommand("select ImageValue from table where ID=1", ObjCon);
ObjCon.Open();
byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
ObjCon.Close();
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream("C:\\Temp\\1.txt", FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
// 1.txt file will be created in c:\temp folder

Default profile picture in sql server using varbinary(max)

I have a web application which has a user profile page. That page allows the user to upload its own profile picture. I am finding a way to set a default varbinary(max) value for my profile picture in database (SQL Server 2008). Something like Facebook which has a default profile picture once you sign up. I am able to upload a picture to the database and display it out, but if my profile picture column in database is NULL, I get error decoding the image.
Uploading image code:
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
}
if (contenttype != String.Empty)
{
System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
System.Drawing.Image newImage = new Bitmap(1024, 768);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(uploaded, 0, 0, 1024, 768);
}
byte[] results;
using (MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
newImage.Save(ms, codec, jpegParms);
results = ms.ToArray();
}
Display image code:
string strQuery = "select profilepic from MemberAccount where nric='"+ Session["nric"] +"'";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
if (!dt.Rows[0]["profilepicture"].Equals(DBNull.Value))
{
download(dt);
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
SqlDataAdapter sda = new SqlDataAdapter();
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();
}
}
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Response.BinaryWrite(bytes);
Response.End();
}
Added the if statement in the part when displaying image but having error
if (!dt.Rows[0]["profilepicture"].Equals(DBNull.Value))
This line give error:
Object reference not set to an instance of an object.
Why don't you save the default image in some images folder on your site?
That way you don't have to read the database column, instead use the relative path in the image control.
Try comparing
if(!dt.Rows[0]["profilepicture"].Equals(DBNull.Value))

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