Hi I have used the code below to save images to my database,
but now I want to know how I can get the picture from the database to a PictureBox
can you please help me.
private void button1_Click(object sender, EventArgs e)
{
ofdFoto.ShowDialog();
string i = ofdFoto.FileName.ToString();
pbxFoto.ImageLocation = i;
}
private void button2_Click(object sender, EventArgs e)
{
dbConn.Open();
string querys = "INSERT INTO Fruits (Name, Picture) VALUES ('" + txtName.Text + "','" + ImageToByte(pbxFoto.Image) + "')";
OleDbCommand cd = new OleDbCommand(querys, dbConn);
cd.ExecuteNonQuery();
dbConn.Close();
MessageBox.Show("Picture saved", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
private void button1_Click(object sender, EventArgs e)
{
PictureBox p =new PictureBox();
p.ImageLocation = ofdFoto.FileName.ToString();
p.Location = new Point(100, 100);
this.Controls.Add(p);
}
See if this helps you!!
Try this code:
public static Bitmap BytesToBitmap(byte[] byteArray)
{
using (var ms = new MemoryStream(byteArray))
{
var img = (Bitmap)Image.FromStream(ms);
return img;
}
}
and set to PictureBox.Image property:
pictureBox1.Image = BytesToBitmap(byteArray);
Related
I have a program which user can input some data and the data will be storaged into a database (i use Ms Access). But, the program also can do some search of existing data from database. User can input a keyword from textbox and the program will show the data from database.
Like this:
User will input a keyword or a text to "Kd. Dosen" textbox then it will show the data from database contains that keyword. Here is the database:
Can anybody help me how to do this?
Anyway, here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//stri
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryInsert = "insert into MstDosen (KdDosen, NaDosen, Alamat, NoTelp, NoHP)values (#kddosen, #namadosen, #alamat, #notelp, #nohp)";
OleDbCommand vinsert = new OleDbCommand(queryInsert, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil dimasukkan!");
}
catch
{
MessageBox.Show("Gagal memasukkan data");
}
finally
{
vconnect.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryDelete = "update MstDosen set NaDosen = #namadosen, Alamat = #alamat, NoTelp = #notelp, NoHP = #nohp where KdDosen = #kddosen";
OleDbCommand vinsert = new OleDbCommand(queryDelete, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil diubah!");
}
catch
{
MessageBox.Show("Gagal mengubah data");
}
finally
{
vconnect.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryDelete = "delete from MstDosen where KdDosen = #kddosen";
OleDbCommand vinsert = new OleDbCommand(queryDelete, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
//vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
//vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
//vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
//vinsert.Parameters.AddWithValue("#nohp", textBox2.Text);
try
{
vconnect.Open();
OleDbDataReader vdr = vinsert.ExecuteReader();
MessageBox.Show("Data berhasil dihapus!");
}
catch
{
MessageBox.Show("Gagal menghapus data");
}
finally
{
vconnect.Close();
}
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
DataList dat = new DataList();
dat.Show();
}
public void insert()
{
if(textBox1.Text != "" && textBox2.Text != "")
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\3rd Term\\VisualProgramming\\Projects\\PendataanDosen\\mhs.accdb";
OleDbConnection vconnect = new OleDbConnection(connect);
string queryinsert = "insert into MstDosen (KdDosen, NaDosen, Alamat, NoTelp, NoHP) values (#kddosen, #namadosen, #alamat, #notelp, #nohp)";
OleDbCommand vinsert = new OleDbCommand(queryinsert, vconnect);
vinsert.Parameters.AddWithValue("#kddosen", textBox1.Text);
vinsert.Parameters.AddWithValue("#namadosen", textBox2.Text);
vinsert.Parameters.AddWithValue("#alamat", textBox3.Text);
vinsert.Parameters.AddWithValue("#notelp", textBox4.Text);
vinsert.Parameters.AddWithValue("#nohp", textBox5.Text);
}
else
{
MessageBox.Show("Data Belum Dimasukkan");
}
}
}
You have to add textbook_change option to double click textbook which you want to write text and filter.
private void txtCariKodu_TextChanged(object sender, EventArgs e)
{
FilterByName();
}
your method is contains a variable which is your db query like (SELECT * FROM YOUTRABLE WHERE NAME LIKE % ).
and now you can show filtered values on your Datagridview.
public void FilterByName()
{
var result = YOURSQLQUERY.ToList();
dataGridView1.DataSource = result;
}
namespace dota2
{
public partial class Form1 : Form
{
private SqlConnection cn = new SqlConnection();
private SqlCommand cmd = new SqlCommand();
private SqlDataReader dr;
private SqlParameter picture;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::dota2.Properties.Settings.Default.Database1ConnectionString);
cmd.Connection = cn;
picture = new SqlParameter("#picture", SqlDbType.Image);
}
private void button1_Click(object sender, EventArgs e)
{
open();
}
private void button2_Click(object sender, EventArgs e)
{
savepicture();
}
private void savepicture()
{
if (pictureBox1.Image != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#picture", a);
cmd.CommandText = "insert into pictures (name,picture) values ('" + textBox1.Text.ToString() + "',#picture)";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
textBox1.Text = "";
pictureBox1.Image = null;
MessageBox.Show("Image Saved", "Programming At Kstark");
}
}
private void open()
{
try
{
OpenFileDialog f = new OpenFileDialog();
f.InitialDirectory = "C:/Picture/";
f.Filter = "All Files|*.*|JPEGs|*.jpg|Bitmaps|*.bmp|GIFs|*.gif";
f.FilterIndex = 0;
if (f.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(f.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BorderStyle = BorderStyle.Fixed3D;
textBox1.Text = f.SafeFileName.ToString();
}
}
catch { }
}
}
}
My form has a picturebox and Open and Save buttons. I'm trying to insert the picture from my picturebox into database using the code below. Picture opens as it should and shows up in the picturebox, but pressing the save button isn't working. It says either cn. Open is an error or the executenonquery.
I need some help to display images from my datagridview to my picturebox, can someone please help me? I'm very new to this. To this site as well.
I've used this to save the images
private void button1_Click(object sender, EventArgs e)
{
byte[] imageBt = null;
FileStream fstream = new FileStream(this.afbeelding_txt.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
string constring = "datasource=localhost;port=3306;username=username;password=password";
string Query = "INSERT INTO project.auto (kenteken, merk, type, kleur, deuren, prijscategorie, afbeelding) VALUES('" + this.kenteken_txt.Text + "','" + this.merk_txt.Text + "','" + this.type_txt.Text + "','" + this.kleur_txt.Text + "','" + this.deuren_txt.Text + "','" + this.prijscategorie_txt.Text + "',#IMG) ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
cmdDataBase.Parameters.Add(new MySqlParameter("#IMG", imageBt));
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Opgeslagen");
while (myReader.Read())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
load_table();
}
And the following is to show the datagridview
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
kenteken_txt.Text = row.Cells["kenteken"].Value.ToString();
merk_txt.Text = row.Cells["merk"].Value.ToString();
type_txt.Text = row.Cells["type"].Value.ToString();
kleur_txt.Text = row.Cells["kleur"].Value.ToString();
deuren_txt.Text = row.Cells["deuren"].Value.ToString();
prijscategorie_txt.Text = row.Cells["prijscategorie"].Value.ToString();
afbeelding_txt.Text = row.Cells["afbeelding"].Value.ToString();
}
}
Besides this code the picturebox isn't mentioned.
private void button6_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "PNG Files(*.png)|*.png|JPG Files(*.jpg)|*.jpg|All Files(*.*)|*.*";
dlg.Title = "Selecteer auto afbeelding.";
if (dlg.ShowDialog() == DialogResult.OK)
{
string picPath = dlg.FileName.ToString();
afbeelding_txt.Text = picPath;
pictureBox1.ImageLocation = picPath;
}
}
The image is shown in the datagridview in this column:
afbeelding_txt.Text = row.Cells["afbeelding"].Value.ToString();
I tried :
pictureBox1.Image = Image.FromFile(row.Cells["afbeelding"].Value.ToString());
And got the following error :
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in System.Drawing.dll
Additional information: System.Byte[]
If in the column there is the file path of the image, use the Image.FromFile method:
pictureBox1.Image = Image.FromFile(row.Cells["afbeelding"].Value.ToString());
Else, if in the column there is directly the image value you can use the FromStream method as described here, in your case:
var data = (Byte[])(row.Cells["afbeelding"].Value);
var stream = new MemoryStream(data);
pictureBox1.Image= Image.FromStream(stream);
I want to resize Profile picture before storing it into a folder in asp.net .What will be technique to resize it ?? Here is my code for image upload.
Any help will be appreciated..Thanks!
protected void btnUpload_Click(object sender, EventArgs e)
{
StartUpLoad();
}
private void StartUpLoad()
{
//get the file name of the posted image
string imgName = fileuploadImage.FileName.ToString();
//sets the image path
string imgPath = "ImageStorage/" + imgName;
fileuploadImage.SaveAs(Server.MapPath(imgPath));
//get the size in bytes that
int imgSize = fileuploadImage.PostedFile.ContentLength;
//validates the posted file before saving
if (fileuploadImage.PostedFile != null && fileuploadImage.PostedFile.FileName != "")
{
if (fileuploadImage.PostedFile.ContentLength > 102400)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
//save the file
//Call the method to execute Insertion of data to the Database
ExecuteInsert(imgName, imgSize, imgPath);
Response.Write("Save Successfully!");
}
}
}
private string GetConnectionString()
{
//sets the connection string from your web config file. "DBConnection" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ParkingProjectConnectionString"].ConnectionString;
}
private void ExecuteInsert(string name, int size, string path)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO ImageInfo (ImageName, ImageSize, ImagePath) VALUES "
+ " (#imgName,#imgSize,#imgPath)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#imgName", SqlDbType.NVarChar, 50);
param[1] = new SqlParameter("#imgSize", SqlDbType.BigInt, 9999);
param[2] = new SqlParameter("#imgPath", SqlDbType.VarChar, 50);
param[0].Value = name;
param[1].Value = size;
param[2].Value = path;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
This Code works for me.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Test/") + "test.jpg");
string pth = Server.MapPath("~/Test/test.jpg");
resizeImageAndSave(pth);
}
}
private string resizeImageAndSave(string imagePath)
{
System.Drawing.Image fullSizeImg
= System.Drawing.Image.FromFile(imagePath);
var thumbnailImg = new Bitmap(150, 130);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
thumbGraph.InterpolationMode =System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, 150, 130);
thumbGraph.DrawImage(fullSizeImg, imageRectangle);
string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
thumbnailImg.Save(targetPath, System.Drawing.Imaging.ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
thumbnailImg.Dispose();
return targetPath;
}
Try this code:
private Image resizeImageAndSave(string imagePath)
{
Size wantedSize = new Size(250, 180);
Image fullImg = Image.FromFile(imagePath);
Bitmap resizedImg = new Bitmap(fullImg, wantedSize);
return (Image)resizedImg;
}
I have a problem regarding with add an image URL within a database.I'm using fileupload method within formview in ASP.Net.And I have a table called duyurular
which can be record a image URL.BTW,I'm using SQL Server Database.
My question is;I'm doing the process update,delete and to make an announcement in the FormView.I can upload those images within folder called "img" with FileUpload.
However,I want to record it within database as well.when to add within database another those infos,there are no the image URL.
Finally,I can't add the image URL within database.
Here is my code;
public partial class panel_yoneticipaneli : System.Web.UI.Page
{
FileUpload dosya, dosya1;
//TextBox t1, t2, t3;
//Button btn;
SqlConnection con;
static string str = "Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True";
string yol = "";
protected void Page_Load(object sender, EventArgs e)
{
dosya = (FileUpload)FormView2.FindControl("FileUpload1");
dosya1 = (FileUpload)FormView2.FindControl("FileUpload2");
// btn = (Button)FormView2.FindControl("ResimKaydetButonu");
//t1 = (TextBox)FormView2.FindControl("DuyuruBaslikTextBox");
//t2 = (TextBox)FormView2.FindControl("DuyuruIcerikTextBox");
//t3 = (TextBox)FormView2.FindControl("DuyuruTarihiTextBox");
Label1.Visible = false;
if (Session["KullaniciID"]!=null)
{
con = new SqlConnection(str);
SqlCommand sorgu = new SqlCommand("SELECT * FROM Kullanici WHERE KullaniciAdi=#KullaniciAdi", con);
sorgu.Parameters.Add("#KullaniciAdi", SqlDbType.VarChar).Value = Session["KullaniciAdi"];
con.Open();
SqlDataReader oku = sorgu.ExecuteReader(CommandBehavior.CloseConnection);
Label1.Visible = true;
while (oku.Read())
{
Label1.Text = oku["KullaniciAdi"].ToString();
}
}
else {
Response.Redirect("error.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
Response.Redirect("giris.aspx");
}
protected void btn_Click(object sender,EventArgs e) {
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
System.Drawing.Image resim = System.Drawing.Image.FromFile(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
resim.Dispose();
DbUpload();
}
}
catch (Exception ex)
{
}
}
public void DbUpload() {
try {
SqlConnection sc = new SqlConnection("Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True");
SqlCommand scom = new SqlCommand("insert into Duyuru(DuyuruResmi) values(#DuyuruResmi)", sc);
scom.Parameters.AddWithValue("#DuyuruResmi", dosya.FileName);
scom.ExecuteNonQuery();
sc.Close();
}catch(Exception p){
p.Message.ToString();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
Response.Write("Fileupload çalışıyor...");
DbUpload();
}
}
catch (Exception ex)
{
}
}
thanks in advance for all comments you can share.
I suggest that you just upload the image name without specifying the full URL, and you can save the image base path in the web.config like '<add key="ImagesBasePath" value="/img" />' so you can change the path were you have your images and you can control the view of this image by concatenating the Image name to ConfigurationManager.AppSettings["ImagesBasePath"] so this will be better.
You have to use Formview ItemInserting Event, where you can pass in the built URL.
protected void frmAsset_ItemInserting(object sender, FormViewInsertEventArgs e)
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
e.NewValues["URL"] = "img/" + dosya.FileName;
}
}