C# assignment, Binary file types - c#

I am a starting student in C# and I can't find the answer for the following question:
"Write a program to open a text file and save the individual high and low 4 bit nibbles of each byte and in a binary file. Write a program to do the reerse, i.e reads two bytes from a binary file, combines them and writes them as a text file."
I can read code, and understand it. But since i'm new to this field, it's hard for me to actually come up on it completely on my own.
I've already wrote the code to open a .txt file and to save it as an .txt file.
Image of form1: Since I lack the "reputation" I can't post images. :(
And this is the code I wrote:
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.IO;
namespace _9._3_menustripAndFiledialog
{
public partial class Form1 : Form
{
private System.Drawing.Printing.PrintDocument docToPrint =
new System.Drawing.Printing.PrintDocument();
public Form1()
{
InitializeComponent();
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
//Clear rich text box
richTextBox1.Clear();
//Set open file dialog initial directory and title
openFileDialog1.InitialDirectory = #"C:\"; //Hier zeg je welke directory drive hij moet openen
openFileDialog1.Title = "Please select a file";
openFileDialog1.Filter= "Text files(*.TXT)|*.txt";
MessageBox.Show("Only .txt files can be opened.");
//Open the dialog and check for cancel
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
// niet gecanceled - lees bestand
richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
else
{
MessageBox.Show("Gosh darn it! You pressed cancel!");
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
// niet gecanceld - schrijf het bestand
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
} else {
MessageBox.Show("You pressed cancel!");
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// Display a message box asking users if they
// want to exit the application.
if (MessageBox.Show("Do you want to exit?", "My Application",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
Application.Exit();
}
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout = new AboutBox1();
frmAbout.Show();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Cut();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Paste();
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Undo();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Copy();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Redo();
}
private void findTextToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Find("Text", RichTextBoxFinds.MatchCase);
richTextBox1.SelectionFont = new Font("Verdana", 12, FontStyle.Italic);
richTextBox1.SelectionColor = Color.Blue;
}
public void replaceTextToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Text = richTextBox1.Text.Replace("Text", "newText");
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
printDialog1.AllowSomePages = true;
printDialog1.ShowHelp = true;
printDialog1.Document = docToPrint;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
docToPrint.Print();
}
}
//Code starting from here are added from user: Xanatos
public static void ReadSplitWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096];
byte[] outputBuffer = new byte[inputBuffer.Length * 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i++, j += 2)
{
outputBuffer[j] = (byte)(inputBuffer[i] & 0x0F);
outputBuffer[j + 1] = (byte)(inputBuffer[i] & 0xF0);
}
sw.Write(outputBuffer, 0, read * 2);
}
}
}
public static void ReadMergeWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096 * 2];
byte[] outputBuffer = new byte[inputBuffer.Length / 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i += 2, j++)
{
outputBuffer[j] = inputBuffer[i];
outputBuffer[j] |= inputBuffer[i + 1];
}
sw.Write(outputBuffer, 0, read / 2);
}
}
}
//I made a custom button to support the read and write method and to have it inside my form
private void openAndSaveAsBinaryToolStripMenuItem_Click(object sender, EventArgs e)
{
ReadSplitWrite("inputfile.txt", "output.dat");
ReadMergeWrite("output.dat", "inputfile2.txt");
}
}
}
I would really appreciate some help on this matter! :)
Thanks in advance!

I tried something and this is what I came up with as sollution to the question.
private void openAndSaveAsBinaryToolStripMenuItem_Click(object sender, EventArgs e)
{
string dirPath = #"C:\";
//read from folder: C:\
//create directory if it doesn't exist
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string fileName = #dirPath + "/TestFile.bin";
//Create binary file if it doesn't exist
if (!File.Exists(fileName))
{
//File doesn't exist - create file
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
byte[] byteArray = { 0x48, 0x45, 0x4C, 0x4C, 0x4F }; //HELLO!
for (int i = 0; i < byteArray.Length; i++)
{
bw.Write(byteArray[i]);
}
bw.Close();
fs.Close();
}
// reads back
FileStream fsRead = new FileStream(fileName, FileMode.Open);
BinaryReader br = new BinaryReader(fsRead);
for (int i = 0; i < fsRead.Length; i++)
{
MessageBox.Show(br.ReadByte().ToString());
}
br.Close();
fsRead.Close();
}
What it does: It creates a new directory if it doesn't exists. Also, it writes the .bin file now and returns it to me in a MessageBox as Binary. (Converted .ToString()). After that it saved it in the directory,and it converts it in the .bin to readable text.
I think this is what the assignment asked from me.
I want to thank you folks for the help, without it I couldn't have done it :)

Here there are two methods, the first one splits, the second one merges. Note that your assignment isn't clear if you have to shift the second nibble after splitting it or not... To make it clear:
0xFF
should I split it to:
0x0F 0xF0
or to
0x0F 0x0F
I choose the first one.
public static void ReadSplitWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096];
byte[] outputBuffer = new byte[inputBuffer.Length * 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i++, j += 2)
{
outputBuffer[j] = (byte)(inputBuffer[i] & 0x0F);
outputBuffer[j + 1] = (byte)(inputBuffer[i] & 0xF0);
}
sw.Write(outputBuffer, 0, read * 2);
}
}
}
public static void ReadMergeWrite(string inputFile, string outputFile)
{
using (var sr = File.OpenRead(inputFile))
using (var sw = File.Create(outputFile))
{
int read;
byte[] inputBuffer = new byte[4096 * 2];
byte[] outputBuffer = new byte[inputBuffer.Length / 2];
while ((read = sr.Read(inputBuffer, 0, inputBuffer.Length)) != 0)
{
for (int i = 0, j = 0; i < read; i += 2, j++)
{
outputBuffer[j] = inputBuffer[i];
outputBuffer[j] |= inputBuffer[i + 1];
}
sw.Write(outputBuffer, 0, read / 2);
}
}
}
Use it like:
ReadSplitWrite("inputfile.txt", "output.dat");
ReadMergeWrite("output.dat", "inputfile2.txt");
If you look at the example, you will see that I read the file at blocks of 4096/8192 bytes at a time (inputBuffer), and then I have a second buffer where I put the splitted/merged bytes that I then write.

Related

C# CSCore. Can't write pcm-wav from microphone correctly

I am trying to record audio stream from a microphone to file (wav format).
By default, the file is recorded in stereo, the IEEE Float codec, but I need to record audio in PCM-format (16 kHz, Mono)
Where should this format be used in this program code?
(variable need_wave_format)
The project uses NuGet CSCore.
Link to this sample project:
https://github.com/LordKmon/CsCoreRecordProblem
Code from winform:
public partial class Form1 : Form
{
private WasapiCapture m_SoundKeeper;
private IWriteable m_Writer;
private IWaveSource m_FinalSource;
public Form1()
{
InitializeComponent();
}
private void btn_StartRecord_Click(object sender, EventArgs event_args)
{
//Find and set Device (microphone)
MMDevice selected_device = null;
using (var deviceEnumerator = new MMDeviceEnumerator())
using (var deviceCollection = deviceEnumerator.EnumAudioEndpoints(DataFlow.Capture, DeviceState.Active))
{
selected_device = deviceCollection[0];
}
// Format that I needed
WaveFormat need_wave_format = new WaveFormat(16000, 16, 1, AudioEncoding.Pcm);
// Start record
m_SoundKeeper = new WasapiCapture();
m_SoundKeeper.Device = selected_device;
m_SoundKeeper.Initialize();
var soundInSource = new SoundInSource(m_SoundKeeper);
var singleBlockNotificationStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource());
m_FinalSource = singleBlockNotificationStream.ToWaveSource();
m_Writer = new WaveWriter("output.wav", m_FinalSource.WaveFormat);
byte[] buffer = new byte[m_FinalSource.WaveFormat.BytesPerSecond / 2];
soundInSource.DataAvailable += (s, e) =>
{
int read;
while ((read = m_FinalSource.Read(buffer, 0, buffer.Length)) > 0)
m_Writer.Write(buffer, 0, read);
};
l_Status.Text = "RECORD !!!";
m_SoundKeeper.Start();
}
private void btn_Stop_Click(object sender, EventArgs e)
{
if (m_SoundKeeper == null)
return;
m_SoundKeeper.Stop();
m_SoundKeeper.Dispose();
m_SoundKeeper = null;
m_FinalSource.Dispose();
if (m_Writer is IDisposable)
((IDisposable)m_Writer).Dispose();
l_Status.Text = "...";
}
}
}
Where do I should to use variable "need_wave_format" in this code so that the output is a file of the Wav-PCM format?

how to capture real time stream data in csv or .data file in a windows form Application

I implemented a function in a windows form application to capture and read needed tabular data from a file (sourcedata.data) and save it in another file (result.data ).
How i and by using the application can capture a real time stream data like such available here :https://data.sparkfun.com/streams in csv or .data file to use it.
Or are there any direct waya to read the stream data directly from the website source periodically ?
private void button5_Click(object sender, EventArgs e)
{
List<string[]> rows = new List<string[]>();
int[] indexes = { 0, 1, 3, 5, 6, 7, 8, 9 };
using (var reader = new StreamReader(#"sourcedata.data"))
{
using (StreamWriter writetext = new StreamWriter("result.data"))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.IndexOf(',') == -1)
continue;
string[] values = line.Split(',');
string[] row = new string[indexes.Length];
int insertIndex = 0;
for (int i = 0; i < values.Length; i++)
{
string val = values[i];
if (val.Trim() == "?")
goto BREAK;
if (indexes.Contains(i))
row[insertIndex++] = val;
}
rows.Add(row);
writetext.WriteLine(String.Join(",", row));
BREAK:;
}
}
}
}
You have two split your problem into two separated sub problems:
Write a method public static string DownloadData(...) which will download the data from the source. This can be done by any HTTP client or library you can find like System.Net.Http.HttpClient or System.Net.WebClient.
See How to download a file from a URL in C#?
Add/start a timer which calls this method periodically. You can use classes like System.Windows.Forms.Timer or System.Timers.Timer.
See What is the best way to implement a "timer"?
#Progman
It is the code
public partial class Download : Form
{
public Download()
{
InitializeComponent();
}
WebClient client;
private void btnDownload_Click(object sender, EventArgs e)
{
string url = txtUrl.Text;
if (!string.IsNullOrEmpty(url))
{
Thread thread = new Thread(() =>
{
Uri uri = new Uri(url);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
client.DownloadFileAsync(uri, Application.StartupPath + "/" + filename);
});
thread.Start();
}
}
private void Download_Load(object sender, EventArgs e)
{
client = new WebClient();
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
}
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download Completed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
progressBar.Minimum = 0;
double recieve = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recieve / total * 100;
lblStatus.Text = $"Download {string.Format("{0:0.##}", percentage)}%";
progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}
}

c# Progressbar, Overflow returns negative value

I'm creating a backup application. I have 5 folders in different locations what needs to be copied to one backup folder. (solved via checkbox.checked)
The main issue is that some of the folders are more than 3-4GB in total (with all subfolders) Progressbar is not updated because "maxbyte" returns a negative value. (I assume int32 overflows after 2gb file copy)
(Sorry can't explain it more in details..I'm just a beginner C# programmer)
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using memoQClientBackuTool;
namespace memoQBackupTool
{
public partial class BGWorker : Form
{
public BGWorker()
{
InitializeComponent();
}
BackgroundWorker bw;
string source = "";
string target = "";
bool isfile = false;
int filecount = 0;
int currentFileNr = 1;
string newFilename = "";
int maxbytes = 0;
public void ShowProgress(string from, string to, bool isf)
{
InitializeComponent();
source = from;
target = to;
isfile = isf;
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
GetFileData();
}
private void GetFileData()
{
if (isfile)
{
FileInfo fi = new FileInfo(source);
maxbytes = Convert.ToInt32(fi.Length);
//
//set progress bar length
//
progressBar1.Minimum = 0;
progressBar2.Minimum = 0;
progressBar1.Maximum = maxbytes;
progressBar2.Maximum = 1;
bw.RunWorkerAsync();
}
else
{
GetDirectoryInfo(source);
//
//set progress bar length
//
progressBar1.Minimum = 0;
progressBar2.Minimum = 0;
progressBar1.Maximum = maxbytes;
progressBar2.Maximum = filecount;
bw.RunWorkerAsync();
}
}
private void GetDirectoryInfo(string source)
{
string[] files = Directory.GetFiles(source);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
maxbytes += Convert.ToInt32(fi.Length);
filecount += 1;
}
string[] folders = Directory.GetDirectories(source);
foreach (string folder in folders)
{
GetDirectoryInfo(folder);
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
if (isfile)
{
FileStream fs = new FileStream(source, FileMode.Open);
long FileSize = fs.Length;
FileInfo fi = new FileInfo(source);
byte[] bBuffer = new byte[(int)FileSize];
fs.Read(bBuffer, 0, (int)FileSize);
fs.Close();
UpdateLabels(fi.FullName);
newFilename = fi.Name;
try
{
FileStream fss = new FileStream(target + "\\" + newFilename, FileMode.CreateNew);
BinaryWriter biwr = new BinaryWriter(fss);
for (int i = 0; i < bBuffer.Length; i += 15000)
{
if (i + 15000 < bBuffer.Length)
{
biwr.Write(bBuffer, i, 15000);
bw.ReportProgress(15000);
}
else
{
biwr.Write(bBuffer, i, bBuffer.Length - i);
bw.ReportProgress(bBuffer.Length - i);
}
}
biwr.Close();
fss.Close();
} catch (IOException){
MessageBox.Show("Nincs olyan...");
}
}
else
{
string[] temp = source.Split('\\');
target += "\\" + temp[temp.Count() - 1];
DirectoryInfo s = new DirectoryInfo(source);
DirectoryInfo t = new DirectoryInfo(target);
CopyDirectory(s, t);
}
if (bw.CancellationPending)
{
e.Cancel = true;
return;
}
}
public void CopyDirectory(DirectoryInfo di_source, DirectoryInfo di_target)
{
if (Directory.Exists(di_target.FullName) == false)
{
Directory.CreateDirectory(di_target.FullName);
}
foreach (FileInfo fi in di_source.GetFiles())
{
newFilename = fi.Name;
FileStream fs = new FileStream(fi.FullName, FileMode.Open);
long FileSize = fs.Length;
byte[] bBuffer = new byte[(int)FileSize];
fs.Read(bBuffer, 0, (int)FileSize);
fs.Close();
UpdateLabels(fi.FullName);
if (File.Exists(di_target.ToString() + "\\" + fi.Name))
{
Random rand = new Random();
newFilename = newFilename + "_" + rand.Next(1, 10000);
}
FileStream fss = new FileStream(di_target.ToString() + "\\" + newFilename, FileMode.CreateNew);
BinaryWriter biwr = new BinaryWriter(fss);
for (int i = 0; i < bBuffer.Length; i += 500000)
{
if (i + 500000 < bBuffer.Length)
{
biwr.Write(bBuffer, i, 500000);
bw.ReportProgress(500000);
}
else
{
biwr.Write(bBuffer, i, bBuffer.Length - i);
bw.ReportProgress(bBuffer.Length - i);
}
}
biwr.Close();
fss.Close();
}
foreach (DirectoryInfo di_SourceSubDir in di_source.GetDirectories())
{
DirectoryInfo nextSubDir = di_target.CreateSubdirectory(di_SourceSubDir.Name);
CopyDirectory(di_SourceSubDir, nextSubDir);
}
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value += e.ProgressPercentage;
int copied = progressBar1.Value / 1024;
int total = maxbytes / 1024;
lbl_kbscopied.Text = copied + "/" + total;
}
delegate void UpdateLabelsDelegate(string filename);
void UpdateLabels(string fname)
{
if (!InvokeRequired)
{
lbl_filename.Text = "Copying: " + fname;
lbl_filenr.Text = "File: " + currentFileNr + "/" + filecount;
currentFileNr++;
progressBar2.Value += 1;
}
else
{
Invoke(new UpdateLabelsDelegate(UpdateLabels), new object[] { fname });
}
}
private void button1_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
bw.CancelAsync();
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Cursor.Current = Cursors.Default;
CustomMsgBox.Show("The task has been canceled", "Error", "OK");
this.Close();
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
this.Close();
}
}
}
}
Report progress not in absolute values, but in relative; percentage, for example.
Let say that 1MB file is 100% of progress bar. That means that you have to initialize it with 100: progressBar1.Maximum = 100. Then every 15000 bytes that were copied is a little bit more than 1%. Instead of bw.ReportProgress(15000) do bw.ReportProgress(1).
I will suggest to use long instead of int wherever you are getting total bytes copied/uploaded so far. If I understood your code you are using int in for loop where you call ReportProgress

A generic error occurred in GDI+ ExternalException Was caught cant figure out why

The error is on the line:
for (int x = 0; x < myList.Count(); x++)
The x++is painted with green.
Im using backgroundoworker and I used this code same code in another form before without a backgroundworker and it worked good. Now in the other form im using a click button event to show() this form and I want to use a progressBar1 to show the progress of the backgroundowrker work.
I used now try and catch inside this for loop and it went to the catch point and showed me the error. The full exception message is:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at mws.Animation_Radar_Preview.backGroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Animation_Radar_Preview.cs:line 163
gifImages isnt null.
This is the full code of this form:
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 DannyGeneral;
using unfreez_wrapper;
namespace mws
{
public partial class Animation_Radar_Preview : Form
{
int mtpStart;
int mtpEnd;
Picturebox1_Fullscreen pb1;
string radar_images_download_directory;
string tempRadarPngToGifDirectory;
int numberOfFiles;
UnFreezWrapper unfreez;
string path_exe;
List<string> myList;
string previewDirectory;
int animatedGifSpeed;
bool loop;
string nameOfStartFile;
string nameOfEndFile;
string previewFileName;
BackgroundWorker backGroundWorker1;
Image img;
private MemoryStream _memSt = null;
public Animation_Radar_Preview()
{
InitializeComponent();
mtpStart = Picturebox1_Fullscreen.mtp1Start;
mtpEnd = Picturebox1_Fullscreen.mtp1End;
animatedGifSpeed = Picturebox1_Fullscreen.animatedSpeed;
loop = Picturebox1_Fullscreen.looping;
pb1 = new Picturebox1_Fullscreen();
radar_images_download_directory = Options_DB.Get_Radar_Images_Download_Directory();
path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
previewDirectory = path_exe + "\\" + "previewDirectory";
if (Directory.Exists(previewDirectory))
{
}
else
{
Directory.CreateDirectory(previewDirectory);
}
previewFileName = previewDirectory + "\\" + "preview.gif";
loop = false;
animatedGifSpeed = 0;
unfreez = new UnFreezWrapper();
backGroundWorker1 = new BackgroundWorker();
backGroundWorker1.WorkerSupportsCancellation = true;
this.backGroundWorker1.WorkerReportsProgress = true;
backGroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backGroundWorker1_ProgressChanged);
backGroundWorker1.DoWork += new DoWorkEventHandler(backGroundWorker1_DoWork);
backGroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backGroundWorker1_RunWorkerCompleted);
backGroundWorker1.RunWorkerAsync();
progressBar1.Value = 0;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result1;
result1 = new DialogResult();
SaveFileDialog sd = new SaveFileDialog();
sd.Title = "Select a folder to save the animated gif to";
sd.InitialDirectory = "c:\\";
sd.FileName = null;
sd.Filter = "Gif File|*.gif;*.jpg|Gif|*.gif";
sd.FilterIndex = 1;
sd.RestoreDirectory = true;
result1 = sd.ShowDialog();
string file1 = sd.FileName;
if (result1 == DialogResult.OK)
{
File.Move(previewFileName, file1);
}
}
public void pictureBoxImage(string pbImage)
{
Image img2 = null;
try
{
using (img = Image.FromFile(pbImage))
{
//get the old image thats loaded from the _memSt memorystream
//and dispose it
Image i = this.pictureBox1.Image;
this.pictureBox1.Image = null;
if (i != null)
i.Dispose();
//grab the old stream
MemoryStream m = _memSt;
//save the new image to this stream
_memSt = new MemoryStream();
img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif);
if (m != null)
m.Dispose();
//create our image to display
img2 = Image.FromStream(_memSt);
}
if (img2 != null)
pictureBox1.Image = img2;
label2.Text = numberOfFiles.ToString();
label6.Text = nameOfStartFile.ToString();
label4.Text = nameOfEndFile.ToString();
//File.Delete(pbImage);
}
catch(Exception err)
{
Logger.Write("Animation Error >>> " + err);
}
}
private void backGroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backGroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> myGifList;
Image gifImages = null;
//button1.Enabled = false;
Animation_Radar_Preview ap = new Animation_Radar_Preview();
//ap.FormClosing += new FormClosingEventHandler(ap_FormClosing);
FileInfo[] fi;
DirectoryInfo dir1 = new DirectoryInfo(radar_images_download_directory);
fi = dir1.GetFiles("*.png");
myList = new List<string>();
myGifList = new List<string>();
for (int i = mtpStart; i < mtpEnd; i++)
{
myList.Add(fi[i].FullName);
}
for (int x = 0; x < myList.Count(); x++)
{
try
{
gifImages = Image.FromFile(myList[x]);
gifImages.Save(tempRadarPngToGifDirectory + "\\" + x.ToString("D6") + ".Gif", System.Drawing.Imaging.ImageFormat.Gif);
}
catch (Exception ex)
{
MessageBox.Show(x.ToString() + "\r\n" + (gifImages == null).ToString() + "\r\n" + ex.Message);
}
}
myGifList = new List<string>();
dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
fi = dir1.GetFiles("*.gif");
nameOfStartFile = fi[0].Name;
for (int i = 0; i < fi.Length; i++)
{
myGifList.Add(fi[i].FullName);
//backGroundWorker1.ReportProgress(i);
nameOfEndFile = fi[i].Name.Length.ToString();
}
numberOfFiles = myGifList.Count();
unfreez.MakeGIF(myGifList, previewFileName, animatedGifSpeed, loop);
/*this.Invoke((MethodInvoker)delegate
{
pictureBoxImage(previewFileName);
});*/
}
private void backGroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pictureBoxImage(previewFileName);
}
}
}
I'm not entirely sure what is going wrong, especially as you say this same code worked previously — but it is not clear whether it worked with the same set of images.
Anyhow, the documentation for the Save method says that an ExternalException will be thrown in one of two situations:
Image was saved with the wrong format.
Image is saved to the file it was created from.
It cannot be that you are saving over the file because you are changing its extension, so it must be the wrong format. What this actually means is not clear. Perhaps one of the source images is using capabilities of the PNG format that cannot be converted to GIF, e.g. alpha channel transparency.
If I may take a moment to make some other suggestions too:
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
The empty 'success' case is not required if you invert the logic:
if (!Directory.Exists(tempRadarPngToGifDirectory)
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
Code that manipulates file paths such as the following:
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
You should consider using the Path class as this will handle the edge cases better and make more portable code:
tempRadarPngToGifDirectory = Path.Combine(path_exe, "tempRadarPngToGifDirectory");

Problem with converting image to byte array

For school we have to do a project in stenography, I have chosen to use a bmp and put text into it. It works fine with normal pictures but from the moment on when you have pictures with a same byte sequence for example a white area or the image where I had the problem is this picture.
When I make from the bytearray where the text is in an image and I read it back the bytearray has changed. while the only thing I did was making an image from the bytearray and from the image back a bytearray.
This is my code:
namespace steganografie
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "bmp files (*.bmp)|*.bmp|All files (*.*)|*.*";
dialog.Title = "Select a image";
dialog.InitialDirectory = Application.ExecutablePath;
if (dialog.ShowDialog() == DialogResult.OK)
{
txtText.Enabled = true;
txtFile.Text = dialog.FileName;
byte[] arImage = imageToByteArray(Image.FromFile(txtFile.Text));
txtText.MaxLength = ((arImage.Length -54) /8)-5;
lblCharLeft.Text = txtText.MaxLength+"";
lblCharLeft.Tag = txtText.MaxLength;
picOriginal.Image = Image.FromFile(dialog.FileName);
}
}
private void btnSteganografie_Click(object sender, EventArgs e)
{
byte[] arImage = imageToByteArray(Image.FromFile(txtFile.Text));
string input = txtText.Text;
string inputInBits = GetBits(input);
char[] bits = inputInBits.ToCharArray();
int i = 0;
for (i = 54; (i < arImage.Length & i < bits.Length+54); i++)
{
if ((int)arImage[i] == 0)
{
arImage[i] = (byte)2;
}
if ((int)arImage[i] == 255)
{
byte bBit = new byte();
bBit = 2;
arImage[i] = (byte)(arImage[i]-bBit);
}
int lastBit = ((int)arImage[i]) % 2;
int dataBit = ((int)bits[i - 54])%2;
if (lastBit != dataBit)
{
arImage[i]++;
}
}
arImage[i] = 0;
Image result = byteArrayToImage(arImage);
picEncoded.Image = result;
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
result.Save(sfd.FileName+".bmp",System.Drawing.Imaging.ImageFormat.Bmp);
}
}
public string GetBits(string input)
{
StringBuilder sbBuilder = new StringBuilder();
byte[] bytes = Encoding.Unicode.GetBytes(input);
foreach (byte bByte in Encoding.Unicode.GetBytes(input))
{
int iByte = (int)bByte;
for (int i = 7; i >= 0 & (iByte!=0 | i!=7); i--)
{
if (iByte - Math.Pow(2, i) >= 0)
{
sbBuilder.Append("1");
iByte -= (int)Math.Pow(2, i);
}
else
{
sbBuilder.Append("0");
}
}
}
return sbBuilder.ToString();
}
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
//**********ERROR HAPPENS HERE *************
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
byte[] arImageTEST = imageToByteArray(returnImage);
//**********byteArrayIn should be the same as arImageTEST ***********
return returnImage;
}
}
Maybe it has something to do with this information available here:
You must keep the stream open for the
lifetime of the Image.
Hope it helps.

Categories

Resources