I am trying to Save image from picture box to Sqlite & retrieve Image on picturebox from SqliteDB with C#.
what it is saving in Database you can see here in the picture in database data type for image is blob
When i am trying to retrieve and show image in picture box it is showing following error.
Here is the Code:
using Finisar.SQLite;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SQLiteDb
{
public partial class ImageForm : Form
{
public ImageForm()
{
InitializeComponent();
}
SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source=database.db;Version=3;New=False;Compress=True;");
private void button2_Click(object sender, EventArgs e)
{
//To convert immage into bytes
Image img = pictureBox1.Image;
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] dataByte = ms.ToArray();
// Saving into database. .
sqlite_conn.Open();
SQLiteCommand cmd_Insert = new SQLiteCommand("Insert into ForImage(ID,FileImage) values ('"+12+"','" + dataByte + "')", sqlite_conn);
cmd_Insert.ExecuteNonQuery();
}
// To Show/load Image in Picturebox 1.
private void button1_Click(object sender, EventArgs e)
{
DialogResult = openFileDialog1.ShowDialog();
if (DialogResult == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
}
}
private void button3_Click(object sender, EventArgs e)
{
sqlite_conn.Open();
SQLiteCommand cmd = new SQLiteCommand("Select FileImage from ForImage where ID=12", sqlite_conn);
byte[] imageBytes = (byte[])cmd.ExecuteScalar();
MemoryStream mm = new MemoryStream(imageBytes);
Image img = Image.FromStream(mm);
pictureBox2.Image = img;
}
}
}
Please tell me what is the problem in the code.
Here is the Solution and Working Code for the above mention problem:
using Finisar.SQLite;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SQLiteDb
{
public partial class Final_Form : Form
{
public Final_Form()
{
InitializeComponent();
}
SQLiteConnection con = new SQLiteConnection("Data Source=database.db;Version=3;New=False;Compress=True;");
Image image;
private void Upload_image_Click(object sender, EventArgs e)
{
DialogResult = openFileDialog1.ShowDialog();
if (DialogResult == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
image = pictureBox1.Image;
}
}
private void Save_Click(object sender, EventArgs e)
{
byte[] imagesBytes = Image2Byte(pictureBox1.Image);
SaveImage(imagesBytes);
}
private void Show_Click(object sender, EventArgs e)
{
LoadImageFromDb();
}
//Retrive Image Code. .
private void LoadImageFromDb()
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand("Select FileImage from ForImage where ID='86';", con);
byte[] arrayFromDb = (byte[])cmd.ExecuteScalar();
con.Close();
pictureBox2.Image = ByteToImage(arrayFromDb);
}
private Image ByteToImage(byte[] toConvert)
{
MemoryStream toImage = new MemoryStream(toConvert);
Image imageFromBytes = Image.FromStream(toImage);
return imageFromBytes;
}
//Picture Save Methods Define Here. .
#region
private void SaveImage(byte[] imageBytes2Save)
{
string Query_ = "INSERT INTO ForImage (ID,FileImage) VALUES (86,#0);";
SQLiteParameter PicParam = new SQLiteParameter("#0", DbType.Binary);
PicParam.Value = imageBytes2Save;
con.Open();
SQLiteCommand cmd = new SQLiteCommand(Query_,con);
cmd.Parameters.Add(PicParam);
cmd.ExecuteNonQuery();
con.Close();
}
private byte[] Image2Byte(Image imageToconvert)
{
MemoryStream memoryStream = new MemoryStream();
imageToconvert.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bytesOfImage = memoryStream.ToArray();
return bytesOfImage;
}
#endregion
}
}
// Here is the output
Upload a picture to Image box
Save picture to Database(SQLITE)
Retrieve from database to show in Picturebox
How I solved the Problem?
Ans : By putting Parameter in Query for saving Image in Database.
Related
Was following a tutorial on YouTube and tried to get my program to display the live video feed from my webcam into the forms picture box but for some reason the webcam comes on but the picture box isn't displaying anything
I have tried checking if the Mat class was returning null.
but it isn't this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.UI;
namespace FaceRecognitionAttandanceSystem
{
public partial class StudentAdd : Form
{
public string fileName { get; set; }
VideoCapture capture;
public StudentAdd()
{
InitializeComponent();
}
//Open Folder
private void metroButton3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false };
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//open file explorer
fileName = openFileDialog.FileName;
//pick image from file
Image img = Image.FromFile(fileName);
//Rotates Image by 90degrees
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox2.Image = img;
}
}
}
//Capture Image
private void metroButton4_Click(object sender, EventArgs e)
{
//If capture is empty start new video capture
if(capture == null)
{
capture = new Emgu.CV.VideoCapture(0);
}
capture.ImageGrabbed += Capture_ImageGrabbed;
capture.Start();
}
private void Capture_ImageGrabbed(object sender, EventArgs e)
{
try
{
Mat mat = new Mat();
if(mat == null)
{
Console.WriteLine("Here you Go");
}
capture.Retrieve(mat);
pictureBox1.Image = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
}
catch(Exception)
{
}
}
private void metroButton5_Click(object sender, EventArgs e)
{
}
}
}
The problem is very likely that the Capture_ImageGrabbed event is raised on a background thread. And you can only update the UI on the UI thread. You can place a break point in the event-handler and check the thread-debug window to confirm. To fix this you need to move execution to the UI thread. Try:
capture.Retrieve(mat);
var bitmap = mat.ToImage<Bgr, Byte>().ToBitmap<Bgr, Byte>();
pictureBox1.Invoke(() => pictureBox1.Image = bitmap );
You might need to write Invoke((Action)(() => pictureBox1.Image = bitmap) ), since I think there is some issues with the overload resolution of lambdas with the invoke-method.
With the following code I am recording and saving video from the webcam to the disk. But even a 3 second video saves with a file size of roughly 50 MB. I assume I am misusing the VideoWriter class. Any suggestions?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
namespace EmguCV_Webcam
{
public partial class Form1 : Form
{
#region Private variables
private Capture currentDevice;
private VideoWriter videoWriter;
private bool recording;
private int videoWidth;
private int videoHeight;
#endregion
#region Constructors
public Form1()
{
InitializeComponent();
InitializeVariables();
AttachButtonMacros();
StartVideoFeed();
}
#endregion
#region Methods
private void InitializeVariables()
{
currentDevice = new Capture(0);
recording = false;
videoWidth = currentDevice.Width;
videoHeight = currentDevice.Height;
}
private void StartVideoFeed()
{
currentDevice.Start();
currentDevice.ImageGrabbed += CurrentDevice_ImageGrabbed;
}
private void AttachButtonMacros()
{
StartRecordingButton.Click += StartRecordingButton_Click;
StopRecordingButton.Click += StopRecordingButton_Click;
}
private void CurrentDevice_ImageGrabbed(object sender, EventArgs e)
{
Mat m = new Mat();
currentDevice.Retrieve(m);
VideoPictureBox.Image = m.ToImage<Bgr, byte>().Bitmap;
if (recording && videoWriter != null)
{
videoWriter.Write(m);
}
}
private void StartRecordingButton_Click(object sender, EventArgs e)
{
recording = true;
SaveFileDialog dialog = new SaveFileDialog();
dialog.DefaultExt = ".avi";
dialog.AddExtension = true;
dialog.FileName = DateTime.Now.ToString();
DialogResult dialogResult = dialog.ShowDialog();
if(dialogResult != DialogResult.OK)
{
return;
}
videoWriter = new VideoWriter(dialog.FileName, 30, new Size(videoWidth, videoHeight), true);
}
private void StopRecordingButton_Click(object sender, EventArgs e)
{
recording = false;
if(videoWriter != null)
{
videoWriter.Dispose();
}
}
#endregion
}
}
You should use compression. Try this
VideoWriter.Fourcc('M', 'P', '4', 'V')
So change
videoWriter = new VideoWriter(dialog.FileName, 30, new Size(videoWidth, videoHeight), true);
with
videoWriter = new VideoWriter(dialog.FileName, VideoWriter.Fourcc('M', 'P', '4', 'V'), 30, new Size(videoWidth, videoHeight), true);
I'm trying to add images already used to an imageList named "Images1".
I'm not really good in coding programs but I know that the rest of my program is working except the fact that "Images1" does not exist for the two last voids. I searched to resolve this problem but I have difficulty to find an answer for this specific case.
How can I make my image list "Images1" available for all my private voids?
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using System.Globalization;
using System.Resources;
using System.Reflection;
namespace Booster_pack_2
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
List<Image> Images1 = new List<Image>();
ResourceManager rm = Booster_pack_2.Properties.Resources.ResourceManager;
string index1 = textBox1.Text;
Bitmap image1 = (Bitmap)rm.GetObject(index1);
pictureBox1.Image = image1;
Images1.Add((Image)Booster_pack_2.Properties.Resources.ResourceManager.GetObject(index1));
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
ResourceManager rm = Booster_pack_2.Properties.Resources.ResourceManager;
string index2 = textBox2.Text;
Bitmap image2 = (Bitmap)rm.GetObject(index2);
pictureBox2.Image = image2;
Images1.Add((Image)Booster_pack_2.Properties.Resources.ResourceManager.GetObject(index2));
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
ResourceManager rm = Booster_pack_2.Properties.Resources.ResourceManager;
string index3 = textBox3.Text;
Bitmap image3 = (Bitmap)rm.GetObject(index3);
pictureBox3.Image = image3;
Images1.Add((Image)Booster_pack_2.Properties.Resources.ResourceManager.GetObject(index3));
}
}
}
Put it in the proper scope. If you need to access it in all your event handlers, make it a class member:
namespace Booster_pack_2
{
public partial class Form3 : Form
{
List<Image> Images1;
public Form3()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Images1 = new List<Image>();
ResourceManager rm = Booster_pack_2.Properties.Resources.ResourceManager;
string index1 = textBox1.Text;
Bitmap image1 = (Bitmap)rm.GetObject(index1);
pictureBox1.Image = image1;
Images1.Add((Image)Booster_pack_2.Properties.Resources.ResourceManager.GetObject(index1));
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
ResourceManager rm = Booster_pack_2.Properties.Resources.ResourceManager;
string index2 = textBox2.Text;
Bitmap image2 = (Bitmap)rm.GetObject(index2);
pictureBox2.Image = image2;
Images1.Add((Image)Booster_pack_2.Properties.Resources.ResourceManager.GetObject(index2));
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
ResourceManager rm = Booster_pack_2.Properties.Resources.ResourceManager;
string index3 = textBox3.Text;
Bitmap image3 = (Bitmap)rm.GetObject(index3);
pictureBox3.Image = image3;
Images1.Add((Image)Booster_pack_2.Properties.Resources.ResourceManager.GetObject(index3));
}
}
}
I'd advise moving this line: Images1 = new List();
to the constructor instead, just in case textBox1 isn't edited first.
I am adding records to my database via a windows form. But when ever I add a new record it doesnt update until I close the app and then start again. Even though I think I am telling it to update (Im obv not!!)
Do I need a new varibale to update the database? Im a little stuck.
EDIT: All code on this..
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.OleDb;
namespace MediaManagementSystem
{
public partial class AddMedia : Form
{
//database var
OleDbConnection m_cnADONetConnection = new OleDbConnection();
OleDbDataAdapter m_daDataAdapter;
OleDbDataAdapter m_cbCommandBuilder;
DataTable m_dtMedia = new DataTable();
int m_rowPosition = 0;
public AddMedia()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, EventArgs e)
{
//load up file dialog and find media
if (addFileDialog.ShowDialog() == DialogResult.OK)
{
//add media file name to file path text box
txtFilePath.Text = addFileDialog.FileName;
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void AddButton_Click(object sender, EventArgs e)
{
//add the new record to the database
DataRow drNewRow = m_dtMedia.NewRow();
drNewRow["FilePath"] = txtFilePath.Text;
drNewRow["Subject"] = txtSubject.Text;
drNewRow["Title"] = txtTitle.Text;
drNewRow["Keywords"] = txtKeywords.Text;
drNewRow["MediaType"] = AddComboBox.Text;
m_dtMedia.Rows.Add(drNewRow);
m_daDataAdapter.Update(m_dtMedia);
m_rowPosition = m_dtMedia.Rows.Count - 1;
this.ShowCurrentRecord();
this.Close();
}
private void AddMedia_Load(object sender, EventArgs e)
{
//link to the database and conect to database
m_cnADONetConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Max\Documents\Visual Studio 2010\Projects\MediaManagementSystem\MediaManagementSystem\bin\Debug\MediaDB.mdb";
m_cnADONetConnection.Open();
OleDbConnection objConnection = new OleDbConnection(m_cnADONetConnection.ConnectionString);
m_daDataAdapter = new OleDbDataAdapter("Select * From Media", m_cnADONetConnection);
OleDbCommandBuilder m_cbCommandBuilder = new OleDbCommandBuilder(m_daDataAdapter);
m_daDataAdapter.Fill(m_dtMedia);
m_daDataAdapter.Update(m_dtMedia);
}
public void ShowCurrentRecord()
{
m_daDataAdapter.Update(m_dtMedia);
if (m_dtMedia.Rows.Count == 0)
{
txtFilePath.Text = "";
txtSubject.Text = "";
txtTitle.Text = "";
txtKeywords.Text = "";
AddComboBox.Text = "";
return;
}
txtFilePath.Text = m_dtMedia.Rows[m_rowPosition]["FilePath"].ToString();
txtSubject.Text = m_dtMedia.Rows[m_rowPosition]["Subject"].ToString();
txtTitle.Text = m_dtMedia.Rows[m_rowPosition]["Title"].ToString();
txtKeywords.Text = m_dtMedia.Rows[m_rowPosition]["Keywords"].ToString();
AddComboBox.Text = m_dtMedia.Rows[m_rowPosition]["MediaType"].ToString();
}
}
}
It would best if you use DataSet and then update the records in it. Finally you need to call AcceptChanges() after the update() command to commit the changes with dataset something as below also reload the data after to enter to get the recent data info:
dataset.AcceptChanges()
After you open AddMedia form from your MAIN form, you need to RALOAD all your records again. Look how the form is doing it when it opens and do the same AFTER you open your AddMedia form ;)
I was trying to convert an ink from Microsoft.Ink namespace to memorystream, so to convert it to image, but I don't understand why it's getting an error in the memorystream. I kind of felt that it was an error from Convert.FromBase64String()
But I don't know what other choices I have to convert it to image.
Please help me
Here is my code:
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.IO;
using Microsoft.Ink;
namespace testPaint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
InkCollector ink;
private void Form1_Load(object sender, EventArgs e)
{
ink = new InkCollector(pictureBox1);
ink.Enabled = true;
ink.AutoRedraw = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
UTF8Encoding utf8 = new UTF8Encoding();
ink.Enabled = false;
string strInk = Convert.ToBase64String(ink.Ink.Save(PersistenceFormat.Base64InkSerializedFormat, CompressionMode.Maximum));
textBox1.Text = strInk;
ink.Enabled = true;
}
private void btnClr_Click(object sender, EventArgs e)
{
ink.Enabled = false;
ink.Ink = new Microsoft.Ink.Ink();
ink.Enabled = true;
pictureBox1.Invalidate();
}
private void btnExport_Click(object sender, EventArgs e)
{
byte[] byImage = Convert.FromBase64String(textBox1.Text);
MemoryStream ms = new MemoryStream();
ms.Write(byImage, 0, byImage.Length);
Image img = Image.FromStream(ms);
img.Save("test.gif", System.Drawing.Imaging.ImageFormat.Gif);
ink.Enabled = true;
}
}
}
The documentation is very preliminary but I think you are probably using the wrong PersistenceFormat tag: you are using Base64 as the output format but you clearly want PersistenceFormat.Gif.
Apart from that, your conversion to and from a string is really not at all meaningful. Just use a private byte[] variable to store the ink data. Furthermore, your detour via a MemoryStream and a System.Graphics.Image makes no sense either.
// using System.IO;
private byte[] inkData;
private void btnSave_Click(object sender, EventArgs e)
{
inkData = ink.Ink.Save(PersistenceFormat.Gif, CompressionMode.Maximum);
}
private void btnExport_Click(object sender, EventArgs e)
{
// Data is already in GIF format, write directly to file!
using (var stream = new FileStream("filename", FileMode.Create, FileAccess.Write))
stream.Write(inkData, 0, inkData.Length);
}