Ink to memorystream problem - c#

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

Related

How To Save Background Image On Form Close In C#

I am making a desktop app in c# in which when the user selects specific name of background from the menu strip, then the background shall turn to that required background. The problem is that i cannot save the user input, i tried settings but i cannot find "system.drawing.image" in settings so is there any way i can save the user changed background ? No external backgrounds a user is allowed to change, just the ones in the resource folder. Here is my code which shows error that system.drawing.color cannot take place of drawing.image.
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;
namespace TAC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.Location = new Point(165, 157);
panel2.Location = new Point(289, 158);
panel3.Location = new Point(47, 275);
panel4.Location = new Point(47, 402);
this.BackgroundImage = Properties.Settings.Default.FormImage;
}
private void bLUEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex1;
}
private void gREENToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex2;
}
private void oRANGEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex3;
}
private void rEDToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex4;
}
private void pURPLEToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackgroundImage = TAC.Properties.Resources.tex5;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.FormImage = this.BackgroundImage;
}
}
}
Use Save method to save settings
Properties.Settings.Default.Save();
If you want add an image to settings :
Add new setting with type string and use like this:
Save an image to setting ( when you close form)
MemoryStream ms = new MemoryStream();
Propertis.Resources.MyImage.Save(ms,ImageFormat.Jpeg);
Properties.Settings.Default.BackImg = Convert.ToBase64String(ms.ToArray());
Properties.Settings.Default.Save();
And read image from setting and set to background(in form load)
string img = Properties.Settings.Default.BackImg ;
byte[] i = Convert.FromBase64String(img);
this.BackgroundImage = Image.FromStream(new MemoryStream(i));
How add custom settings ?
http://www.codeproject.com/Articles/29130/Windows-Forms-Creating-and-Persisting-Custom-User

Image not saving SQLite Database with C# Desktop Application

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.

The process cannot access the file because it is being used by another process

The code that I got was from naudio record sound from microphone then save and many thanks to Corey
This is the error message that I get when I run the code for the second or subsequent times.
The first time it runs, it runs with no issues what so ever.
If I change the file name it works perfectly.
Unable to copy file "obj\Debug\Basque.exe" to "bin\Debug\Basque.exe". The process cannot access the file 'bin\Debug\Basque.exe' because it is being used by another process. Basque
Could someone gave me some guidance to where I'm making my error
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 NAudio.Wave;
namespace Basque
{
public partial class FlashCard : Form
{
public WaveIn waveSource = null;
public WaveFileWriter waveFile = null;
public FlashCard()
{
InitializeComponent();
StopBtn.Enabled = false;
StartBtn.Enabled = true;
}
private void StartBtn_Click(object sender, EventArgs e)
{
StartBtn.Enabled = false;
StopBtn.Enabled = true;
waveSource = new WaveIn();
waveSource.WaveFormat = new WaveFormat(44100, 1);
waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable);
waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped);
waveFile = new WaveFileWriter(#"C:\Temp\bas0001.wav", waveSource.WaveFormat);
waveSource.StartRecording();
}
private void StopBtn_Click(object sender, EventArgs e)
{
StopBtn.Enabled = false;
waveSource.StopRecording();
}
void waveSource_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveFile != null)
{
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
}
}
void waveSource_RecordingStopped(object sender, StoppedEventArgs e)
{
if (waveSource != null)
{
waveSource.Dispose();
waveSource = null;
}
if (waveFile != null)
{
waveFile.Dispose();
waveFile = null;
}
StartBtn.Enabled = true;
}
private void PlayBtn_Click(object sender, EventArgs e)
{
}
private void ExitBtn_Click(object sender, EventArgs e)
{
}
}
}
It might help to put a Formclosing method with Application.Exit(); in it. If it only works on the first try, it might be because the application isn't fully closing.
You can check if this will fix it when you check task manager. Just make sure that your application isn't still there. Even if it isn't still there, the Application.Exit(); might help.

Trying to REopen Sytem.IO Objects

I am making a program that allows you to roll five different types of multi sided "dice", and when you roll a number I want it to store it in a text file. There is a menu strip item at the top of my form that you click, it closes the StreamWriter and FileStream and opens a second form showing what numbers were rolled and by what die they were rolled ( I'm having it be just the numbers rolled now for simplicity's sake) and it displays fine. But when I close the Reader, Stream, and second form and go back to the first form, I try to Reopen the Writer and Stream and it tells me that is already in use.
My First Form's Code:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Random ran = new Random();
static FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
private int ranNum;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 21);
Display();
}
private void button2_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 13);
Display();
}
private void button3_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 5);
Display();
}
private void button4_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 9);
Display();
}
private void button5_Click(object sender, EventArgs e)
{
ranNum = ran.Next(1, 11);
Display();
}
private void Display()
{
lblNum.Text = String.Format("{0}", ranNum);
lblNum.Visible = true;
writer.WriteLine(ranNum);
}
private void historyToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl1.SelectedIndex = 1;
writer.Close();
outFile.Close();
History history = new History();
history.ShowDialog();
}
private void button1_Click_1(object sender, EventArgs e)
{
FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
}
}
My Second Form's Code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class History : Form
{
public History()
{
InitializeComponent();
}
static private FileStream inFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.Open, FileAccess.Read);
private StreamReader reader = new StreamReader(inFile);
private void History_Load(object sender, EventArgs e)
{
string item;
item = reader.ReadLine();
try
{
lstHistory.Items.Add(item);
}
catch (Exception)
{
lstHistory.Font = new Font(lstHistory.Font.Name, 12, lstHistory.Font.Unit);
lstHistory.Items.Add("You have not rolled any numbers");
}
}
}
}
You need to release the unmanaged resources (in your case the file) properly once done with it. Call the Dispose() function on the stream once done with it:
if(inFile != null){
inFile.Dispose();
}
And even better, wrap it in a using() like this:
using(FileStream outFile = new FileStream(#"H:\C#\Independant Projects\VirtualDice\History.txt", FileMode.OpenOrCreate, FileAccess.Write)){
StreamWriter writer = new StreamWriter(outFile);
tabControl1.SelectedIndex = 0;
}
using will automatically call Dispose() for you at the right time in the proper way (i.e. it checks if the object is null first before calling Dispose() on it to avoid a `null exception). Check this link for more details about the using statement.
However, if you have the same code in so many places, it is probably worth it to wrap it in a singleton pattern. Check this Microsoft article on how to write a singleton pattern in C#.

Aforge for webcam

I wrote a code for acessing the webcam with two buttons and a picture box
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 AForge.Imaging;
using AForge.Imaging.Filters;
using AForge.Video;
using AForge.Video.DirectShow;
namespace cam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
Bitmap bitmap;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
}
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = bitmap;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Image = bitmap;
}
}
}
The code build up successfully. but on debugging the picture box is not working. start and stop is working properly. Can anyone help?
you have to delete first
Bitmap bitmap;
because its null and that what you show in picture box
not the picture that come from camera
a long time ago i had problems too with aforge but got it working
see my code inhere : How initialize AForge webcam

Categories

Resources